diff --git a/Changelog/2026-10-14-boost-loot-one-kill-one-loot-0.5.66.md b/Changelog/2026-10-14-boost-loot-one-kill-one-loot-0.5.66.md new file mode 100644 index 0000000..f273e5f --- /dev/null +++ b/Changelog/2026-10-14-boost-loot-one-kill-one-loot-0.5.66.md @@ -0,0 +1,65 @@ +# RynthAi 0.5.66-legacy-ui - Boost Loot Priority loots each kill before the next fight + +Previous release: 0.5.65-legacy-ui. + +## Problem + +With Boost Loot Priority on, Silentkelpie still fought two or three monsters before looting +their corpses together (2026-10-14, 22:56): + +- 22:56:43.021 Old Growler killed. +- 22:56:43.027 the next target (Skitters McGee) locked, 6 ms later. +- 22:56:46 Old Growler's corpse found and claimed, but the arbiter kept Combat: + `want[cbt=True loot=True] eng=True boost[loot=True]`. +- 22:56:54 Skitters McGee killed, then both corpses were looted. + +Boost Loot Priority only lets looting outrank combat when combat is not engaged, and +"engaged" includes a locked target at any range. After a kill, combat locked the next target +in the same tick, 1-3 s before ACE creates the corpse (the death animation). So with monsters +around, the arbiter never saw a gap, and Boost Loot made no difference. + +## Change + +With Boost Loot Priority on, each of our kills is looted before the next fight: + +- A kill (KillerNotification) starts a wait of up to 4 s (`BoostLootKillWaitMs`) for its + corpse. +- While that wait runs, or while a corpse is claimed, open or lootable in range, combat locks + no new target (`CombatManager.HoldNewTarget`, answered by + `RynthAiPlugin.BoostLootHoldsNewTarget`). The log says + `[CombatTarget] next target waits: Boost Loot Priority loots the kill first` once per wait. +- The forming corpse counts as loot work, so the arbiter gives Looting the tick and nav + waits. +- Looting the kill's corpse ends the wait, so combat goes on right away. A corpse from an + earlier kill doesn't end it. +- Unchanged safety: a monster within 5 yd is fought at once, and a target already being + fought is finished first. +- No wait with Boost Loot off, Loot Only Rare Corpses on, looting off, packs full, or while + the server is refusing uses. If the corpse never comes, combat goes on after 4 s. + +## Tests + +- RynthCore.RynthAiHostTests: 1005 passed, 1 failed. The failure is the known + "map bake 0x6346" check, which needs the game data files. New cases: + - `BoostLootOneKillOneLoot`: no target is locked while the corpse forms, the arbiter + picks Looting, and the corpse is claimed and opened when it arrives. + - `BoostLootHoldLimits`: the wait runs out after 4 s; a monster at 2 m, Boost Loot off, or + Loot Only Rare Corpses means no wait. + - `BoostLootWaitEndsOnKillCorpse`: the kill's corpse ends the wait, and an older corpse + doesn't. +- RynthCore.RynthAiTests: 39/39. + +## Install + +Installed locally on 2026-10-14: RynthAi 0.5.66-legacy-ui (RynthSuite e85b49c, clean NativeAOT +publish) copied to C:\Games\RynthSuite\RynthAi. 0.5.65-legacy-ui was backed up to +PreviousReleases\0.5.65-legacy-ui. Running clients load it on a restart or the overlay's RL +(hot reload). + +## Files + +- `Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs` +- `Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs` +- `Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs` diff --git a/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md b/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md new file mode 100644 index 0000000..6d615e5 --- /dev/null +++ b/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md @@ -0,0 +1,102 @@ +# RynthAi 0.5.64-legacy-ui - fewer weapon swaps, faster point-blank stall recovery + +Previous release: 0.5.63-legacy-ui. + +Goes with RynthCore 2026.10.5.57 (gesture-safe attacks and target selects, +`RynthCore/Changelog/2026-10-14-gesture-safe-attacks-2026.10.5.57.md`). + +## Problem + +Silentkelpie (missile, several elemental crossbows) killed slowly in the +2026-10-14 logs. Silentstorm (magic) did not: about 1.7 s per cast, limited by +spawns. Kelpie's time went to three things: + +- **Weapon swaps.** About 58 swaps an hour, each costing 3-4 s of no attacks, + including ping-pong (Fire -> Piercing -> Fire crossbow 2.5 s apart, + 11:41:06-08). Causes: + - A wield that reached the hand after the choice had moved on (a new target + wanted another weapon) was timed out as "not seen in hand". The landing was + never recorded, so the swap straight back wasn't held. + - A swap started on a target that was locked 230 ms earlier, then the + target changed and another swap followed. + - Swaps for a target that was nearly dead. + - Weakness swaps for a small gain (for example 1.1x over 1.0x). +- **Attacks waiting behind crossbow gestures** in the engine's action queue + (fixed in RynthCore 2026.10.5.57). +- **Point-blank missile stalls.** 22 of 40 missile stalls were at 1.5-2.5 m. The + watchdog's step 1 (re-issue) usually brought swings back within half a + second, so the 6 s wait before it was nearly the whole cost. + +## Change + +- `WeaponSwapTracker`: a wield counts as landed when its weapon reaches the + hand, even if the choice moved on while it was in flight. The A -> B landing + is recorded, so the existing "just swapped away from it" and swaps-per-minute + holds apply. +- New swap settings in Advanced Settings > Melee Combat > "Weapon Swaps" (also + readable from meta expressions): + - `WeaponSwapSettleMs` (default 750, 0-3000): a swap for a target locked + less than this long ago waits. Combat holds with the weapon in hand until + the target has settled. + - `WeaponSwapMinHealthPct` (default 25, 0-100): a target at or under this + health is finished with the weapon in hand, when both weapons are the same + kind (bow for bow, sword for sword). + - `WeaponSwapMinGainPct` (default 20, 0-200): a swap chosen only by + weakness must beat the weapon in hand by this much (`WeaponPlanner.KeepInHand`). + It applies only when both multipliers are known. A Monsters rule element, + order-only (learned) weakness data, or a hand weapon that does nothing to + the target always swaps. + - Set any of them to 0 to turn it off. +- `CombatStallWatchdog`: missile targets within 3 m start the ladder after + 3.5 s instead of 6 s (`PointBlankStallMs`, `PointBlankMissileM`). The melee + "quiet" early start (2.5 s) is unchanged. +- Each deferred swap is logged once per 10 s: + `[EquipDiag] not swapping 0x.. 'X' for 0x.. 'Y' yet (why)`. + +## Ammo-swap fix kept + +The launcher and ammo fix (ccbbf86: the launcher swap holds the stance, the +400 ms ammo-off settle, and the ammo dequip not stamping the equip pacing) is +untouched. The new holds and delays never apply while any part of a swap is +under way (`SwapHoldsAllowed`): + +- a wield in flight +- old ammo or an off-hand item on its way into the pack +- the ammo follow-up armed + +A launcher in hand is only kept when the ammo wielded fits it. So a launcher is +never kept after its ammo went into the pack. + +## Tests + +- RynthCore.RynthAiTests: 34/34. New `PointBlank`: step 1 at 3.5 s, with + the default still 6 s. +- RynthCore.RynthAiHostTests: 1002 passed, 1 failed. The failure is the known + "map bake 0x6346" baseline (no dats in the worktree). New cases: + - `SwapLandsWhenChoiceMoved` (Kelpie's Fire / Piercing case). + - `ChoiceMinSwapGain`: threshold off, inside and outside the gain, + order-only data, immune hand, rule element. + - `LowHealthKeepsLauncher`. + - `LowHealthMidSwapFinishes`: a launcher swap already under way finishes even + when the target drops low. + - The existing `LauncherSwapTests` and `AmmoTests` all pass. +- Every other RynthSuite and RynthCore test project passes, except the 4 known + RynthLua ScriptWindowsTests failures (docs and icon data missing from the + worktree). + +## Files + +- `Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs`, `CombatStallWatchdog.cs`, + `WeaponPlanner.cs`, `WeaponSwapTracker.cs` +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs`, + `LegacyDashboardRenderer.cs`, `LegacyAdvancedSettingsUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs`, `RynthAiPlugin.cs`, + `RynthAiVersionCommand.cs` +- `Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs`, `LauncherSwapTests.cs` +- `Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs` + +## Install + +Installed locally on 2026-10-14: RynthAi 0.5.64-legacy-ui (RynthSuite 53af975, +NativeAOT publish) copied to C:\Games\RynthSuite\RynthAi. 0.5.63-legacy-ui was +backed up to PreviousReleases\0.5.63-legacy-ui. diff --git a/Changelog/2026-10-14-loot-baseline-0.5.65.md b/Changelog/2026-10-14-loot-baseline-0.5.65.md new file mode 100644 index 0000000..e3a3629 --- /dev/null +++ b/Changelog/2026-10-14-loot-baseline-0.5.65.md @@ -0,0 +1,87 @@ +# RynthAi 0.5.65-legacy-ui - loot timer baseline, logged; unused loot options hidden + +Previous release: 0.5.64-legacy-ui. + +## What the loot logs show + +Silentkelpie on InfiniteLeaftide (ACE), 2026-10-14 12:38-13:53, loot profile `01.utl`: + +- 226 corpses opened, 2191 items judged, 39 pickups, every one confirmed on the first + try (no retries, no failed pickups, no corpse timeouts). 199 of 203 timed corpses + opened on the first try. +- Kept: Thaelaryn Core 33, Necrolytic Extract 18, Coalesced Aetheria 1. Everything else + was left by the profile. +- No item was misjudged for lack of an appraisal. The 52 items judged without one were all + keepers matched by name; every item left had its appraisal. +- Appraisal (ID) replies: 127 ms median, 256 ms at the 95th percentile, 350 ms at most. +- Every open found its items already in the object cache, so Content Settle and Empty + Corpse Wait were never waited on. +- Pickups were confirmed 1.7-2.2 s after the send (the pickup animation). +- Skipped corpses, both as set: 133 killed by another player (Loot From = My Kills Only), + and 42 of his own kills beyond his 40 yd (36.6 m) loot range. +- His Approach Range Min is 240 yd with a Max of 40 yd; the loot code uses Max for Min. +- Silentstorm has looting off. + +## Baseline + +| Timer | Baseline | Was default | Why | +|---|---|---|---| +| Content Settle | 100 ms | 100 | never waited on (items already cached) | +| Empty Corpse Wait | 300 ms | 300 | no empty corpse or contents probe seen | +| Assess Window | 300 ms | 200 | above the 256 ms 95th percentile of appraisal replies | +| Loot Retry Timeout | 1000 ms | 500 | 39 of 39 pickups landed without a retry at 1000 ms | +| Corpse Open Retry | 1500 ms | 1500 | 199 of 203 opened on the first try | +| Corpse Timeout | 12000 ms | 12000 | no corpse timed out | + +`LootBaseline.cs` holds these values; the settings defaults now come from it, so a new +settings profile starts at the baseline. Saved profiles keep their own values. + +## Change + +- **Logged.** When looting runs, the log gets a `[LootSettings]` line with each loot timer + marked `baseline` or `custom (baseline N)`, a count, `[acts as N]` for a value under the + code's minimum, and a note when Approach Range Min is above Max. It is written again only + when one of those values changes. Kelpie's current settings would log: + `Content Settle 125 ms custom (baseline 100) | Empty Corpse Wait 550 ms custom (baseline 300) | + Assess Window 450 ms custom (baseline 300) | Loot Retry Timeout 1000 ms baseline | + Corpse Open Retry 1200 ms custom (baseline 1500) | Corpse Timeout 12000 ms baseline -- + 4 of 6 custom | Approach Range Min 240 yd is above Max 40 yd, so Min acts as 40 yd`. +- **Advanced Settings > Looting.** + - Each loot timer shows `baseline` next to it, or `baseline N` in amber when it differs, + and a tooltip saying what it does. + - New **Use Baseline** button sets all six timers to the baseline. +- **Hidden, not wired.** Nothing in the corpse looting reads these, so they are no longer + shown. The settings still load and save, so profiles are unchanged. + - Loot Only Rare Corpses (the meta/MagTools option of that name still sets Mine Only) + - Inter-Item Delay + - Closing Delay + +## Tests + +- RynthCore.RynthAiTests: 39/39, with 5 new baseline tests (the values; the all-baseline + line; Kelpie's custom timers and range note; a value under the floor; legacy fractional + ranges). +- RynthCore.RynthAiHostTests: loot tests 124/124. The pickup-retry pacing test now takes its + retry window from the settings instead of assuming 500 ms. The full run has one other + failure, `map bake: 0x6346 from the real dats ...` ("made no checks"), which fails the same + way on 0.5.64: it depends on the game data files on this machine. +- The plugin builds. + +## Install + +- Installed locally on 2026-10-14: RynthAi 0.5.65-legacy-ui (RynthSuite 81205e9, NativeAOT + publish) copied to C:\Games\RynthSuite\RynthAi. 0.5.64-legacy-ui (53af975) was backed up + to PreviousReleases\0.5.64-legacy-ui. Clients load it when they restart. +- Silentkelpie's loot timers set to the baseline with his client closed (Content Settle + 125 -> 100, Empty Corpse Wait 550 -> 300, Assess Window 450 -> 300, Corpse Open Retry + 1200 -> 1500). His Approach Range Min (240 yd) is left as it is. The previous file is + `SettingsProfiles\InfiniteLeaftide\Silentkelpie\Default.json.pre-loot-baseline-20261014.bak`. + +## Files + +- `Plugins/RynthCore.Plugin.RynthAi/LootBaseline.cs` (new) +- `Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs` +- `Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs`, `LegacyAdvancedSettingsUi.cs` +- `Plugins/RynthCore.Plugin.RynthAi/RynthAiVersionCommand.cs` +- `Tools/RynthCore.RynthAiTests/` (csproj, `Program.cs`, `Tests/LootBaselineTests.cs`) +- `Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs` diff --git a/Changelog/2026-10-15-combat-pointblank-settle-busy-wield-0.5.69.md b/Changelog/2026-10-15-combat-pointblank-settle-busy-wield-0.5.69.md new file mode 100644 index 0000000..c08bca1 --- /dev/null +++ b/Changelog/2026-10-15-combat-pointblank-settle-busy-wield-0.5.69.md @@ -0,0 +1,76 @@ +# RynthAi 0.5.69 - point-blank facing, settle only after a switch, 'too busy' wields + +Date: 2026-10-15 +Plugin: RynthCore.Plugin.RynthAi 0.5.69-legacy-ui (previous release 0.5.68-legacy-ui) + +Follow-ups from Silentkelpie's combat logs of 2026-10-14/15, after the 0.5.64 swap and stall +changes. + +## Point-blank missile stalls: turn to the target once + +7 of Kelpie's 13 missile stalls in one session were at about 1.7 m with the target about 177° +behind. In missile and melee modes the server rotates the character, so RynthAi doesn't turn on +the client (a client turn there caused spinning, 2026-09-27). At point blank with the target +behind, though, the server doesn't rotate, and the stall watchdog's first step (re-issue the +attack) didn't fix it. + +Now, in Missile mode only, when the target is within 3 m, more than 90° off, and no shot has +gone out for 2.5 s, combat turns to the target's heading once (`TurnToHeadingBy`, the same call +the wall-facing hold uses). It then waits 300 ms for the turn to settle. The same target is not +turned to again within 3 s. The watchdog's re-issue step also turns first, whatever the last shot. +The log line is `[Combat] point blank: turning to ...` with a running count. + +- `Combat/PointBlankFacing.cs` (new): the rule, pure and unit tested. +- `Combat/CombatManager.cs`: `HoldForPointBlankFacing`, called from the attack path and the + watchdog's re-issue. + +## Settle hold: only after a target switch + +`WeaponSwapSettleMs` (750 ms) held every swap until the target had been locked that long. In +Kelpie's logs this put 0.75 s in front of 22 of 25 swaps that went ahead anyway, nearly all on +a fresh lock after a kill. Only 2-4% of those were followed by a quick switch. + +The hold now applies only when the lock replaced another live target (a switch). A lock after a +kill or a drop swaps at once. The log reason is now "target switched N ms ago". The setting is +renamed in the Advanced settings to "Wait After Target Switch (ms)", with an updated tooltip. +The value and the settings key are unchanged. + +## Wields answered 'too busy' are not failed tries + +Kelpie's two "didn't wield after 3 tries" give-ups in the last four days both coincided with a +teleport: a house recall at 00:44:23 (one second after the wield went out) and a portal at +23:22:52. The flight recorder showed the server answering each try with `WeenieError 0x1D +(YoureTooBusy)` and then `InventoryServerSaveFailed` with no error. The engine keeps only the +last of those records, so RynthAi read "error 0", saw no refusal, and each try timed out as +"not seen in hand". After three, the better weapon was benched for 2 minutes, even after the +character had landed somewhere new. + +Now: + +- `0x1D` (WeenieError or UseDone), or an `InventoryServerSaveFailed` with no error, reads as + "busy". The try is given back and the wield goes again after 1.5 s. After 6 busy answers for + one weapon they count as tries, so a weapon the server always refuses is still rested. +- Leaving portal space (a portal, recall or teleport) clears every try and rest, for the main + hand, ammo and off hand. +- A real refusal still counts as a try, as before. +- The log line is `[EquipDiag] wield of ... answered 'too busy': not counted, again in 1.5 s`. + +Files: + +- `Combat/WeaponSwapTracker.cs`: `Busy`, `NewPlace`, `BusyRetryMs`, `MaxBusyRefunds`. +- `Combat/CombatManager.cs`: `ServerAnswerSinceSend` (was `ServerRefusedSinceSend`), + `FoldServerAnswer` for the weapon, ammo and off-hand trackers, and `NoteSwapPortal` on the + heartbeat. +- `Combat/CombatManager.Ammo.cs`, `Combat/CombatManager.Offhand.cs`: use `FoldServerAnswer`. + +## Tests + +- `Tools\RynthCore.RynthAiTests`: 40 tests, all passed. New: "point blank facing: one snap only + for a close target behind, after a full shot cycle". +- `Tools\RynthCore.RynthAiHostTests`: 1009 of 1010 passed. New: + - "swap holds: a lock after a kill swaps at once; a switch from a live target waits" + - "weapon swap: 'too busy' is no try, and a portal or recall ends the rest" + - "weapon swap: combat reads ACE's busy answer (0x1D then SaveFailed 0) as busy, a real + refusal as a try" + + The one failure is the map bake check, which needs the game dats. diff --git a/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj b/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj new file mode 100644 index 0000000..589c30a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthAChard + 0.1.0 + achard + AChard + a-chard.ddns.net + AChard|A-Chard + AChard only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs new file mode 100644 index 0000000..d3ec8dd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs @@ -0,0 +1,23 @@ +// ServerData.cs - What is known about AChard (RynthAChard). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvP", + Status = "Stable", + Summary = "ACE EOR PVP Server/Custom PK Content/PK Kill Rankings", + Facts = new[] + { + "PvP server: other players can attack you.", + "Custom PK content and PK kill rankings.", + }, + Discord = "https://discord.gg/gmHfqt2J2D", + Website = "http://a-chard.ddns.net/", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj new file mode 100644 index 0000000..630a200 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj @@ -0,0 +1,18 @@ + + + + + RynthCore.Plugin.RynthAelrynth + 0.1.0 + aelrynth + Aelrynth + aelrynth.com + Aelrynth*|Aeshnidae* + Aelrynth only: the server card (its mods, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs new file mode 100644 index 0000000..ae444f2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs @@ -0,0 +1,26 @@ +// ServerData.cs - What is known about Aelrynth (RynthAelrynth). Identity (id, hosts, world names) is in the csproj. +// Aelrynth isn't in the public server list; this comes from RynthCore's own Aelrynth support +// (Compatibility/AelrynthWire.cs, Net/AelrynthVaultWire.cs) and RynthOracle's quest pack. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9020, + Emulator = "ACE", + Ruleset = "PvE", + Summary = "Aelrynth (aelrynth.com), an ACE server with its own mods.", + Facts = new[] + { + "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).", + "RynthOracle has an Aelrynth quest pack (quests.aelrynth.csv).", + "The world was named Aeshnidae before; both names count.", + }, + Website = "https://aelrynth.com", + Source = "RynthCore's Aelrynth support and RynthOracle, 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs index 3599cfd..7352b23 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs @@ -39,6 +39,16 @@ public partial class CombatManager private DateTime _ammoDequipAt = DateTime.MinValue, _ammoDequipRestUntil = DateTime.MinValue; private const double AmmoDequipResolveMs = 2500; private const int AmmoDequipMaxTries = 3; + // When the old ammo first read out of the ammunition slot (MinValue = not seen yet). + private DateTime _ammoOffSeenAt = DateTime.MinValue; + + /// + /// How long the launcher waits once the old ammo reads off (2026-10-12). Before, the dequip + /// held the launcher for the swap gate's full 3 s (a pack move) and then the equip pacing's + /// 2 s, so a mixed-launcher swap took 5-6 s. Ammo has no unwield motion, and the server's own + /// drop to peace mode is waited out by the combat tick's animation gate. Settable for tests. + /// + internal double AmmoOffSettleMs { get; set; } = 400; private readonly HashSet _noAmmoNoted = new(); @@ -56,6 +66,7 @@ public partial class CombatManager _ammoFollowUpUntil = DateTime.MinValue; _ammoDequipPendingId = _ammoDequipTries = 0; _ammoDequipRestUntil = DateTime.MinValue; + _ammoOffSeenAt = DateTime.MinValue; _noAmmoNoted.Clear(); } @@ -186,14 +197,22 @@ public partial class CombatManager var wielded = pack.FirstOrDefault(a => a.Wielded); if (wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType)) { - _ammoDequipPendingId = 0; _ammoDequipTries = 0; + _ammoDequipPendingId = 0; _ammoDequipTries = 0; _ammoOffSeenAt = DateTime.MinValue; return AmmoPrep.Ready; // same ammo type: it stays } if (pack.Any(a => !a.Wielded && MissileAmmo.Fits(lt, a.AmmoType))) ArmAmmoFollowUp(launcherId, now); if (wielded == null) { - _ammoDequipPendingId = 0; _ammoDequipTries = 0; + // Our own dequip just landed: a short settle, then the swap gate is told the move is + // done so the launcher goes on the server's answers rather than its full 3 s. + if (_ammoDequipPendingId != 0) + { + if (_ammoOffSeenAt == DateTime.MinValue) _ammoOffSeenAt = now; + if ((now - _ammoOffSeenAt).TotalMilliseconds < AmmoOffSettleMs) return AmmoPrep.Busy; + _weaponSwapGate?.MoveDone(_ammoDequipPendingId); + } + _ammoDequipPendingId = 0; _ammoDequipTries = 0; _ammoOffSeenAt = DateTime.MinValue; return AmmoPrep.Ready; } @@ -224,7 +243,9 @@ public partial class CombatManager _ammoDequipPendingId = wielded.Id; _ammoDequipAt = now; _ammoDequipTries++; - _lastEquipTime = now; + _ammoOffSeenAt = DateTime.MinValue; + // No _lastEquipTime stamp: its 2 s equip pacing would hold the launcher after the ammo is + // already off. Busy above (until it reads off and settles) does the waiting instead. _host.Log($"[EquipDiag] {MissileAmmo.Label(wielded.AmmoType)} 0x{(uint)wielded.Id:X8} '{wielded.Name}' x{amount} -> pack 0x{(uint)packId:X8} before wielding 0x{(uint)launcherId:X8} '{WeaponName(launcherId)}' (try {_ammoDequipTries}/{AmmoDequipMaxTries})"); return AmmoPrep.Busy; } @@ -238,6 +259,26 @@ public partial class CombatManager private void EndAmmoFollowUp() { _ammoFollowUpFor = 0; _ammoFollowUpUntil = DateTime.MinValue; } + /// + /// True while ChangeCombatMode(Missile) must wait for (not yet + /// read in hand): combat is swapping to it and it, or its ammo, isn't on yet. Each request in + /// that window was bounced by the server (no launcher, or no ammo) and flickered the stance + /// Missile/peace/Melee for the whole swap; it also stayed the outstanding server action for + /// 2 s, which held the swap gate at its full 3 s per step (2026-10-11 14:45:11-17). Once the + /// launcher reads in hand, the wielded branch sends the stance after the ammo is on. + /// Thrown weapons and launchers of an unknown type: false (as before). + /// + private bool LauncherSwapHoldsStance(int launcherId) + { + int lt = LauncherTypeOf(_worldFilter[launcherId]); + if (lt == 0) return false; + if (_ammoDequipPendingId != 0) return true; // old ammo going into the pack + if (_ammoFollowUpFor == launcherId && AmmoSwapInProgress) return true; // its ammo goes on once it lands + if (SwapTracker.PendingId == launcherId) return true; // its wield is in flight + var wielded = PackAmmo().FirstOrDefault(a => a.Wielded); + return wielded != null && !MissileAmmo.Fits(lt, wielded.AmmoType); // the wrong ammo is still on + } + /// /// Step 3, with confirmed in hand. True while the attack should /// wait for the ammo wield. Only after combat's own launcher swap: an empty quiver otherwise is @@ -253,7 +294,7 @@ public partial class CombatManager if (wo == null || lt == 0) { EndAmmoFollowUp(); return false; } SwapTracker.Confirmed(launcherId, now); // the launcher landed - if (AmmoTracker.PendingId != 0 && ServerRefusedSinceSend()) AmmoTracker.Refused(now, WeaponName); + FoldServerAnswer(AmmoTracker, now); var pack = PackAmmo(); var wielded = pack.FirstOrDefault(a => a.Wielded); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs index e163141..42a1fd1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs @@ -303,7 +303,7 @@ public partial class CombatManager private bool OffhandFollowUp(WorldObject target, MonsterRule? rule, int mainId) { DateTime now = DateTime.Now; - if (OffhandTracker.PendingId != 0 && ServerRefusedSinceSend()) OffhandTracker.Refused(now, WeaponName); + FoldServerAnswer(OffhandTracker, now); var plan = OffhandPlanFor(target, rule, mainId); int off = OffhandInSlot(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index e2a9100..5d241b8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -291,6 +291,14 @@ public partial class CombatManager : IDisposable public Func? HoldIdlePeace { get; set; } private bool _idlePeaceHeldLogged; + /// + /// True = don't lock a new target yet. RynthAi answers true with Boost Loot Priority on while + /// our kill's corpse forms or is looted (RynthAiPlugin.BoostLootHoldsNewTarget): one kill, one + /// loot. A monster within CloseAttackYards is still fought at once. Null = never hold. + /// + public Func? HoldNewTarget { get; set; } + private bool _newTargetHeldLogged; + /// /// RynthAi's mana reserve (BuffManager.OffensiveCastHold): given the attack or debuff spell /// about to be cast, a reason to hold it (mana under its cost, or under the reserve kept for @@ -397,6 +405,8 @@ public partial class CombatManager : IDisposable private int _pendingJudgeTargetId = 0; private bool _damageSincePendingCast; private DateTime _targetLockedAt = DateTime.MinValue; + // The current lock replaced another live target (a switch), not a lock after a kill or drop. + private bool _lockWasSwitch; private DateTime _lastDamageDealtAt = DateTime.MinValue; // ── Server attack binding (the 2026-09-29 melee stall) ─────────────────── @@ -421,6 +431,8 @@ public partial class CombatManager : IDisposable private DateTime _lastMissAt = DateTime.MinValue; private DateTime _lastKillAt = DateTime.MinValue; // stall-watchdog evidence only; metas and the status feed read the plugin's KillClock private string _lastSwingEvidenceKind = "none"; + // Missile at point blank with the target behind: the server doesn't rotate, so one heading snap. + private readonly PointBlankFacing _pointBlankFacing = new(); private readonly CombatStallWatchdog _stallWatch = new(); @@ -727,6 +739,28 @@ public partial class CombatManager : IDisposable /// public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards); + /// + /// HoldNewTarget says wait (Boost Loot Priority, a kill's corpse to loot) and no monster is + /// within CloseAttackYards. One log line per hold. + /// + private bool NewTargetHeldForLoot() + { + bool held; + try { held = HoldNewTarget?.Invoke() == true && !HasCloseThreat(CloseAttackYards); } + catch { held = false; } + if (!held) + { + _newTargetHeldLogged = false; + return false; + } + if (!_newTargetHeldLogged) + { + _newTargetHeldLogged = true; + _host.Log("[CombatTarget] next target waits: Boost Loot Priority loots the kill first"); + } + return true; + } + /// /// Pure predicate for the ActivityArbiter: should Combat claim this tick? /// True iff we're already locked on a target, OR a scanned target (the @@ -1402,9 +1436,13 @@ public partial class CombatManager : IDisposable _damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount); } - public void HandleChatForDamage(string text) + /// A chat line for the damage meter and the stall watchdog. + /// is the line's eChatTypes (-1 = not known). + public void HandleChatForDamage(string text, int chatType = -1) { if (string.IsNullOrEmpty(text)) return; + // Combat lines come from the server; one in a player's chat type is someone's imitation. + if (RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return; // A miss is a swing too (stall watchdog). "You evaded X!" is the monster's miss, not ours. if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0) NoteSwingEvidence("miss"); @@ -3242,6 +3280,15 @@ public partial class CombatManager : IDisposable ClearCombatTurnMotions(); } + // The exception to "missile never turns": a target at point blank with the character's + // back to it (PointBlankFacing). One snap, then the attack waits for it to settle. + if (HoldForPointBlankFacing(currentDist)) + { + LastCombatSkipReason = "point-blank-face"; // D4 record-only + _tickWait = CombatLatencyTracker.Wait.Face; + return true; + } + // Don't attack in missile mode without ammo if (CurrentCombatMode == CombatMode.Missile && !HasWieldedAmmo()) { @@ -3498,7 +3545,9 @@ public partial class CombatManager : IDisposable } } - var act = _stallWatch.Tick(now, eligible, _lastSwingEvidenceAt, out double stalledMs, quiet); + double stallAfter = mode == CombatMode.Missile && currentDist <= CombatStallWatchdog.PointBlankMissileM + ? CombatStallWatchdog.PointBlankStallMs : CombatStallWatchdog.StallMs; + var act = _stallWatch.Tick(now, eligible, _lastSwingEvidenceAt, out double stalledMs, quiet, stallAfter); switch (act) { case CombatStallWatchdog.StallAction.None: @@ -3527,6 +3576,8 @@ public partial class CombatManager : IDisposable { case CombatStallWatchdog.StallAction.Reissue: { + // A re-issue alone never fixed a point-blank target behind the character. + HoldForPointBlankFacing(currentDist, force: true); ReleaseServerAttack("stall watchdog", log: false); lastAttackCmd = AttackAfterCancel(now); // the attack goes out again once the cancel has landed _ghostCheck.Arm(activeTargetId, now, TargetSpot(activeTargetId)); @@ -3866,6 +3917,8 @@ public partial class CombatManager : IDisposable public void OnHeartbeat() { + NoteSwapPortal(); + if (!_settings.IsMacroRunning) { // Clear turn motions once on the transition from running → stopped, @@ -3962,6 +4015,10 @@ public partial class CombatManager : IDisposable { if (_scannedTargets.Count == 0) return; if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs + // Boost Loot Priority: the next target waits for the last kill's corpse. Without this the + // next lock went out a few ms after each kill, 1-3 s before ACE creates the corpse, so the + // arbiter always saw combat engaged and corpses were looted in batches (2026-10-14). + if (_lockedTargetId == 0 && NewTargetHeldForLoot()) return; DateTime now = TargetClock(); double acquireRange = Math.Max(1.0, _settings.MonsterRange); @@ -4057,6 +4114,7 @@ public partial class CombatManager : IDisposable private void LockTarget(ScannedTarget best, int bestPriority, string picked, string? switchWhy) { int bestId = best.Id; + _lockWasSwitch = _lockedTargetId != 0 && _lockedTargetId != bestId; if (_lockedTargetId != 0) _host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' ({switchWhy}, {DescribeTargetPos(_lockedTargetId)}) " + $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})"); @@ -4278,8 +4336,12 @@ public partial class CombatManager : IDisposable if (ctype == 0 && _slayerTypeUnknownNoted.TryAdd(wcid != 0 ? wcid.ToString() : target.Name ?? "", 0)) _host.Log($"[EquipDiag] '{target.Name}' (wcid {wcid}): creature type not known yet (not appraised, not in the creature data) - no slayer check until it is"); } + // A weakness swap must beat the weapon in hand by WeaponSwapMinGainPct, but only while no + // swap is under way: a launcher whose ammo already went into the pack is never kept. + double minGain = _settings.WeaponSwapMinGainPct > 0 && SwapHoldsAllowed(InHandWeaponId()) + ? _settings.WeaponSwapMinGainPct / 100.0 : 0; return WeaponPlanner.Choose(listed, ruleElement, weak, e => CanCastElement(e, rule), - fixedId, fixedSource, learnedId, ctype, fixedIsDefault); + fixedId, fixedSource, learnedId, ctype, fixedIsDefault, minGain); } // PropertyInt 166 SlayerCreatureType, PropertyFloat 138 SlayerDamageBonus (ACE.Entity). @@ -4506,7 +4568,7 @@ public partial class CombatManager : IDisposable private WeaponSwapTracker.Step SwapStep(int chosenId, int inHandId) { DateTime now = DateTime.Now; - if (SwapTracker.PendingId != 0 && ServerRefusedSinceSend()) SwapTracker.Refused(now, WeaponName); + FoldServerAnswer(SwapTracker, now); var step = SwapTracker.Next(chosenId, inHandId, now, WeaponName, forKey: activeTargetId); if (SwapTracker.Notice != null) { @@ -4523,6 +4585,72 @@ public partial class CombatManager : IDisposable private DateTime _lastSwapHoldLogAt = DateTime.MinValue; + /// + /// Why a swap the tracker allows should not start now (null = start it). Settling: the + /// target was switched to (it replaced another live target) under WeaponSwapSettleMs ago; + /// wait (Kelpie 2026-10-14 11:41:06: the crossbow swap sent, then a switch to another monster + /// 230 ms later). A lock after a kill or a drop swaps at once: in Kelpie's 2026-10-14/15 logs + /// 2-4% of those were followed by a quick switch, and waiting on every one put 0.75 s in front + /// of 22 of 25 swaps that went ahead anyway. Not settling: keep the weapon in hand, because + /// the target is at or under WeaponSwapMinHealthPct (same kind of weapon only). Never once a + /// swap is under way (SwapHoldsAllowed), so a launcher is never kept after its ammo went into + /// the pack. + /// + private string? SwapDeferReason(WorldObject target, int chosenId, int inHand, out bool settling) + { + settling = false; + if (!SwapHoldsAllowed(inHand)) return null; + + int settleMs = _settings.WeaponSwapSettleMs; + if (settleMs > 0 && _lockWasSwitch && _lockedTargetId == target.Id && _targetLockedAt != DateTime.MinValue) + { + double lockedMs = (DateTime.Now - _targetLockedAt).TotalMilliseconds; + if (lockedMs >= 0 && lockedMs < settleMs) + { + settling = true; + return $"target switched {lockedMs:0} ms ago"; + } + } + + int minHealth = _settings.WeaponSwapMinHealthPct; + if (minHealth > 0 && WeaponKind(inHand) != 0 && WeaponKind(inHand) == WeaponKind(chosenId)) + { + float ratio = _worldFilter.GetHealthRatio(target.Id); + if (ratio >= 0f && ratio * 100f <= minHealth) + return $"target at {ratio * 100f:0}% health"; + } + return null; + } + + /// + /// True when a swap rule may keep or delay with : nothing of a swap + /// is under way (no wield in flight, no old ammo or off hand on its way into the pack, no + /// ammo follow-up armed), and a launcher in hand has fitting ammo on, so it can shoot. + /// + private bool SwapHoldsAllowed(int inHand) + { + if (inHand == 0 || SwapTracker.PendingId != 0) return false; + if (_ammoDequipPendingId != 0 || AmmoSwapInProgress || _offDequipPendingId != 0) return false; + int lt = LauncherTypeOf(_worldFilter[inHand]); + if (lt == 0) return true; + var wielded = PackAmmo().FirstOrDefault(a => a.Wielded); + return wielded != null && MissileAmmo.Fits(lt, wielded.AmmoType); + } + + // Last swap deferral logged: (chosen, in hand, reason kind) and when. + private (int Chosen, int Hand, bool Settle) _lastSwapDeferLogged; + private DateTime _lastSwapDeferLogAt = DateTime.MinValue; + + private void LogSwapDefer(int chosenId, int inHand, string why) + { + var key = (chosenId, inHand, why.StartsWith("target switched", StringComparison.Ordinal)); + DateTime now = DateTime.Now; + if (key == _lastSwapDeferLogged && (now - _lastSwapDeferLogAt).TotalSeconds < 10) return; + _lastSwapDeferLogged = key; + _lastSwapDeferLogAt = now; + _host.Log($"[EquipDiag] not swapping 0x{(uint)inHand:X8} '{WeaponName(inHand)}' for 0x{(uint)chosenId:X8} '{WeaponName(chosenId)}' yet ({why})"); + } + private string WeaponName(int id) => id == 0 ? "" : (_worldFilter[id]?.Name ?? ""); /// Send one combat wield of and tell the swap tracker. @@ -4546,21 +4674,71 @@ public partial class CombatManager : IDisposable _lastEquipTime = now; } - /// A WeenieError, or a UseDone with an error, arrived after the wield was sent. - private bool ServerRefusedSinceSend() + // The character was in portal space at the last heartbeat (a portal, recall or teleport). + private bool _swapSawPortal; + + /// On leaving portal space, the swap tracker forgets tries and rests from the old place. + private void NoteSwapPortal() { - if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out uint wErr, out _, out _) - && wSeq != _swapWeenieSeq && wErr != 0) + bool inPortal; + try { inPortal = _host.HasIsPortaling && _host.IsPortaling(); } + catch { return; } // a failed read must never stop the heartbeat + if (inPortal) { _swapSawPortal = true; return; } + if (!_swapSawPortal) return; + _swapSawPortal = false; + SwapTracker.NewPlace(); + AmmoTracker.NewPlace(); + OffhandTracker.NewPlace(); + } + + private enum WieldAnswer { None, Refused, Busy } + + /// + /// Folds the server's answer to the wield has in flight into it: a + /// refusal is a failed try, 'too busy' is not (logged). + /// + private void FoldServerAnswer(WeaponSwapTracker tracker, DateTime now) + { + int pending = tracker.PendingId; + if (pending == 0) return; + switch (ServerAnswerSinceSend()) + { + case WieldAnswer.Refused: + tracker.Refused(now, WeaponName); + break; + case WieldAnswer.Busy: + if (tracker.Busy(now, WeaponName)) + _host.Log($"[EquipDiag] wield of 0x{(uint)pending:X8} '{WeaponName(pending)}' answered 'too busy': not counted, again in {tracker.BusyRetryMs / 1000:0.#} s"); + break; + } + } + + // GameEvent InventoryServerSaveFailed: the server refused an inventory change. + private const uint InventorySaveFailedEvent = 0x00A0; + + /// + /// What the server said to the wield since it was sent. Busy: 'too busy' (0x1D), or an + /// InventoryServerSaveFailed with no error. ACE answers a wield while busy (a recall, a + /// portal, an animation) with a WeenieError 0x1D and then that SaveFailed, and the engine + /// keeps only the last record, so the 0x1D is usually read as "error 0" (flight recorder + /// 2026-10-15 00:44:23-31: three of these, read as no answer, cost all 3 tries). + /// + private WieldAnswer ServerAnswerSinceSend() + { + if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out uint wErr, out uint wEvt, out _) + && wSeq != _swapWeenieSeq) { _swapWeenieSeq = wSeq; - return true; + if (wErr == ActionPacer.TooBusyErr || (wEvt == InventorySaveFailedEvent && wErr == 0)) return WieldAnswer.Busy; + if (wErr != 0) return WieldAnswer.Refused; } if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out uint uErr) && uSeq != _swapUseDoneSeq) { _swapUseDoneSeq = uSeq; - return uErr != 0; + if (uErr == ActionPacer.TooBusyErr) return WieldAnswer.Busy; + if (uErr != 0) return WieldAnswer.Refused; } - return false; + return WieldAnswer.None; } /// @@ -4704,6 +4882,23 @@ public partial class CombatManager : IDisposable { var step = SwapStep(targetWeaponId, inHand); if (step == WeaponSwapTracker.Step.Wait) { if (inHand != 0) _equippedWeaponId = inHand; return false; } + if (step == WeaponSwapTracker.Step.Swap && inHand != 0 + && SwapDeferReason(target, targetWeaponId, inHand, out bool settling) is string defer) + { + LogSwapDefer(targetWeaponId, inHand, defer); + if (settling) + { + _equippedWeaponId = inHand; + LastCombatSkipReason = "swap-settle"; + return false; + } + if (_worldFilter[inHand] is WorldObject deferKeep) + { + weaponSource = $"in hand ({defer}); wanted 0x{(uint)targetWeaponId:X8}"; + targetWeaponId = inHand; + weaponObj = deferKeep; + } + } if (step == WeaponSwapTracker.Step.Hold) { if (inHand != 0 && _worldFilter[inHand] is WorldObject handObj) @@ -5008,12 +5203,20 @@ public partial class CombatManager : IDisposable MarkWieldSent(targetWeaponId, inHand); _lastEquipTime = DateTime.Now; } - if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs() - && _host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) + if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()) { - if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); } - lastStanceAttempt = DateTime.Now; - NoteStanceFlipSent(); + // A launcher swap: no Missile request until the launcher and its ammo are on (the + // wielded branch above sends it then). See LauncherSwapHoldsStance. + if (desiredMode == CombatMode.Missile && LauncherSwapHoldsStance(targetWeaponId)) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] stance held: 0x{targetWeaponId:X8} '{weaponObj.Name}' or its ammo isn't on yet (mode={CurrentCombatMode})"); } + } + else if (_host.ChangeCombatModeFor(desiredMode, "Combat", "stance")) + { + if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); } + lastStanceAttempt = DateTime.Now; + NoteStanceFlipSent(); + } } return false; } @@ -5375,6 +5578,29 @@ public partial class CombatManager : IDisposable return true; } + /// + /// Missile only: snap the heading to a point-blank target the character faces away from + /// (). skips the no-shot wait (the + /// stall watchdog's re-issue already waited longer). True = a snap was just sent or is still + /// settling, so don't attack this tick. + /// + private bool HoldForPointBlankFacing(double currentDist, bool force = false) + { + if (CurrentCombatMode != CombatMode.Missile || !_host.HasTurnToHeading) return false; + DateTime now = DateTime.Now; + int tid = activeTargetId; + if (_pointBlankFacing.Settling(now, tid)) return true; + if (!TryGetHeadingTo(tid, out double desiredDeg, out double error)) return false; + DateTime evidence = force ? DateTime.MinValue : _lastSwingEvidenceAt; + if (!_pointBlankFacing.ShouldSnap(now, tid, currentDist, error, evidence)) return false; + if (!_host.TurnToHeadingBy("Combat/PointBlank", (float)desiredDeg)) return false; // held by the pacer: attack as is + _pointBlankFacing.Snapped(now, tid); + _host.Log($"[Combat] point blank: turning to 0x{(uint)tid:X8} ({error:0} deg off at {currentDist:0.0} m, " + + $"last shot {(_lastSwingEvidenceAt == DateTime.MinValue ? "never" : $"{(now - _lastSwingEvidenceAt).TotalSeconds:0.0}s ago")}" + + $"{(force ? ", stall re-issue" : "")}; snaps={_pointBlankFacing.Snaps})"); + return true; + } + /// The heading from the player to (0 = north, clockwise) /// and how far the player's facing is off it (absolute degrees). private bool TryGetHeadingTo(int targetId, out double desiredDeg, out double absError) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs index 665c8a2..88747c2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatStallWatchdog.cs @@ -35,6 +35,18 @@ internal sealed class CombatStallWatchdog /// it at once every time, so most of the 7-9 s per stall was the wait). public const double QuietStallMs = 2500; + /// + /// The stall time for a missile attack at point blank (target within + /// ). Silentkelpie 2026-10-14: 22 of 40 missile stalls were + /// at 1.5-2.5 m, and step 1 (re-issue) brought the swings back within half a second in most + /// of them, so the 6 s wait was the whole cost. A bow or crossbow there shows a hit or miss + /// every 1.5-2 s. + /// + public const double PointBlankStallMs = 3500; + + /// Missile targets this close (metres) use . + public const double PointBlankMissileM = 3.0; + /// Time allowed for each step to show a swing before the next one. public const double StepMs = 3000; @@ -70,11 +82,14 @@ internal sealed class CombatStallWatchdog /// Advance the watchdog. is the full precondition set; /// the last hit, miss or kill. : /// the caller sees no swing playing and the character standing still (step 1 after - /// ). Returns the step to carry out now (or Recovered / GaveUp for - /// logging), with the stalled time. + /// ). : how long without evidence + /// starts an episode otherwise (0 = ). Returns the step to carry out now + /// (or Recovered / GaveUp for logging), with the stalled time. /// - public StallAction Tick(DateTime now, bool eligible, DateTime lastEvidenceAt, out double stalledMs, bool quiet = false) + public StallAction Tick(DateTime now, bool eligible, DateTime lastEvidenceAt, out double stalledMs, + bool quiet = false, double stallAfterMs = 0) { + if (stallAfterMs <= 0) stallAfterMs = StallMs; stalledMs = 0; bool gap = _lastTick != DateTime.MinValue && (now - _lastTick).TotalMilliseconds > TickGapResetMs; @@ -108,8 +123,8 @@ internal sealed class CombatStallWatchdog if (_step == 0) { bool early = quiet && stalledMs >= QuietStallMs; - if (stalledMs < StallMs && !early) return StallAction.None; - LastFireWasEarly = stalledMs < StallMs; + if (stalledMs < stallAfterMs && !early) return StallAction.None; + LastFireWasEarly = stalledMs < stallAfterMs; Episodes++; _stallRef = refAt; return Fire(now); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs index cdc6726..7522361 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs @@ -102,9 +102,20 @@ public class FellowshipTracker : IDisposable private const int OFF_ENTRY_LEVEL = 0x0C; private const int OFF_ENTRY_NEXT = 0x34; + /// + /// Most members read. Retail caps a fellowship at 9, but servers raise it: ACECustom + /// (Infinite Leaftide) allows 29. A count above this is treated as a torn read. + /// + public const int MaxMembers = 64; + + /// Most hash buckets walked (AC sizes the member table at 16; a larger value is a torn read). + internal const int MaxBuckets = 256; + // Replaced whole on each refresh, never changed in place: the radar snapshot (engine pump // thread) reads it while RynthAi's own thread may be refreshing it. private volatile Dictionary _memberCache = new(); + // Member levels by id, replaced together with _memberCache. + private volatile Dictionary _levelCache = new(); private DateTime _lastRefresh = DateTime.MinValue; private const double REFRESH_INTERVAL_MS = 2000; @@ -263,6 +274,28 @@ public class FellowshipTracker : IDisposable return 0; } + /// A member's level from the last read, or 0 when unknown. + public int GetMemberLevel(int characterId) + { + RefreshIfNeeded(); + return _levelCache.TryGetValue(characterId, out int level) ? level : 0; + } + + /// + /// The members from one read: id, name and level, in table order. Use this rather than + /// MemberCount with GetMemberId/GetMemberName, which can see two different reads. + /// + public List<(int Id, string Name, int Level)> GetMembers() + { + RefreshIfNeeded(); + Dictionary names = _memberCache; + Dictionary levels = _levelCache; + var list = new List<(int, string, int)>(names.Count); + foreach (var kvp in names) + list.Add((kvp.Key, kvp.Value, levels.TryGetValue(kvp.Key, out int level) ? level : 0)); + return list; + } + private IntPtr GetFellowshipPtr() { if (!IsReadablePointer(ADDR_FELLOWSHIP_SYSTEM)) return IntPtr.Zero; @@ -281,6 +314,7 @@ public class FellowshipTracker : IDisposable if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return; _lastRefresh = DateTime.Now; var members = new Dictionary(); + var levels = new Dictionary(); try { IntPtr fel = GetFellowshipPtr(); @@ -296,15 +330,14 @@ public class FellowshipTracker : IDisposable int tableSize = Marshal.ReadInt32(tableSizeAddr); int currNum = Marshal.ReadInt32(currNumAddr); - // Fellowship caps at 9 members; a corrupt/mid-mutation table_size - // here (bogus large value) would otherwise turn the bucket loop - // below into an unbounded scan over garbage addresses. - if (bucketsPtr == 0 || tableSize == 0 || tableSize > 64 || currNum == 0 || currNum > 9) + // A corrupt/mid-mutation table_size or count here (bogus large value) would + // otherwise turn the bucket loop below into an unbounded scan over garbage addresses. + if (!IsPlausibleTable(bucketsPtr, tableSize, currNum)) return; if (!IsReadablePointer(new IntPtr(bucketsPtr))) return; - int maxMembers = Math.Min(currNum, 9); + int maxMembers = currNum; int found = 0; for (int b = 0; b < tableSize && found < maxMembers; b++) @@ -317,13 +350,14 @@ public class FellowshipTracker : IDisposable // read racing AC's main thread) must not spin this pump thread // forever — cap the walk independent of the found-count exit. int chainGuard = 0; - while (entryPtr != 0 && found < maxMembers && chainGuard++ < 32) + while (entryPtr != 0 && found < maxMembers && chainGuard++ < MaxMembers) { IntPtr entry = new IntPtr(entryPtr); if (!IsReadablePointer(entry)) break; IntPtr keyAddr = entry + OFF_ENTRY_KEY; IntPtr nameFieldAddr = entry + OFF_ENTRY_NAME_PTR; + IntPtr levelAddr = entry + OFF_ENTRY_LEVEL; IntPtr nextAddr = entry + OFF_ENTRY_NEXT; if (!IsReadablePointer(keyAddr) || !IsReadablePointer(nameFieldAddr) || !IsReadablePointer(nextAddr)) break; @@ -331,13 +365,22 @@ public class FellowshipTracker : IDisposable int memberId = Marshal.ReadInt32(keyAddr); string name = ReadPString(nameFieldAddr); if (memberId != 0 && !string.IsNullOrEmpty(name)) - { members[memberId] = name; found++; } + { + members[memberId] = name; + if (IsReadablePointer(levelAddr)) levels[memberId] = Marshal.ReadInt32(levelAddr); + found++; + } entryPtr = Marshal.ReadInt32(nextAddr); } } } catch { } - finally { _memberCache = members; } // also on the early returns (no fellowship: empty) + finally + { + // Also on the early returns (no fellowship: empty). Levels first: readers take names, then levels. + _levelCache = levels; + _memberCache = members; + } } private string ReadPString(IntPtr addr) @@ -355,6 +398,13 @@ public class FellowshipTracker : IDisposable catch { return ""; } } + /// + /// Whether a fellowship hash table's header looks real enough to walk: a bucket array, a bucket + /// count and member count in range. Internal for the tests. + /// + internal static bool IsPlausibleTable(int bucketsPtr, int tableSize, int currNum) => + bucketsPtr != 0 && tableSize > 0 && tableSize <= MaxBuckets && currNum > 0 && currNum <= MaxMembers; + /// A fellowship member's name is at most this long (AC names are under 20). internal const int MaxNameChars = 64; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PointBlankFacing.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PointBlankFacing.cs new file mode 100644 index 0000000..7adb78d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PointBlankFacing.cs @@ -0,0 +1,64 @@ +using System; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// One heading snap for a missile target the character has its back to at point blank. +/// +/// Missile combat normally never turns the character: the server rotates to the target before +/// each shot, and a client turn servo on top of that spun archers in circles (2026-09-27, Lucy). +/// But with the target inside the server's rotate doesn't happen, so +/// the character stands facing away and fires nothing. Silentkelpie 2026-10-14/15: 7 of 13 +/// crossbow stalls were at 1.7 m with the target 177 degrees behind; the stall watchdog's +/// re-issue never fixed one of them (only dropping the target did, at step 2 or later). +/// +/// So, only when all of these hold, one instant heading snap (TurnToHeading, as for walls): +/// * the target is within , +/// * it is more than off the character's facing, +/// * no hit, miss or kill for (a full crossbow cycle: a shot in +/// progress is never interrupted), +/// * no snap for this target within . +/// Combat then holds the attack for so the turn reaches the server first. +/// Pure: the caller passes the time and readings in. +/// +internal sealed class PointBlankFacing +{ + /// Targets this close (metres) count as point blank (the stall watchdog's distance). + public double MaxDistanceM { get; set; } = CombatStallWatchdog.PointBlankMissileM; + /// Facing error (degrees) above which the character is turned. + public double MinErrorDeg { get; set; } = 90; + /// No swing evidence for this long before a snap. + public double NoShotMs { get; set; } = 2500; + /// At most one snap per target this often. + public double RetryMs { get; set; } = 3000; + /// Attack held this long after a snap. + public double SettleMs { get; set; } = 300; + + private int _target; + private DateTime _snapAt = DateTime.MinValue; + + /// Snaps done (diagnostics). + public int Snaps { get; private set; } + + /// True when the character should be turned to now. + public bool ShouldSnap(DateTime now, int targetId, double distanceM, double facingErrorDeg, DateTime lastEvidenceAt) + { + if (targetId == 0 || distanceM < 0 || distanceM > MaxDistanceM) return false; + if (facingErrorDeg <= MinErrorDeg) return false; + if (lastEvidenceAt != DateTime.MinValue && (now - lastEvidenceAt).TotalMilliseconds < NoShotMs) return false; + if (targetId == _target && _snapAt != DateTime.MinValue && (now - _snapAt).TotalMilliseconds < RetryMs) return false; + return true; + } + + /// The snap for was sent. + public void Snapped(DateTime now, int targetId) + { + _target = targetId; + _snapAt = now; + Snaps++; + } + + /// True while the attack should wait for the last snap to settle. + public bool Settling(DateTime now, int targetId) + => targetId == _target && _snapAt != DateTime.MinValue && (now - _snapAt).TotalMilliseconds < SettleMs; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs index ef5363e..e4d5da9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs @@ -45,7 +45,9 @@ internal readonly record struct WeaponPlan(int WeaponId, string Element, string /// multiplier) down; the first element a listed weapon of the character's main kind has /// wins, and that weapon is wielded. Elements tied on the multiplier count as one step, /// and within a step the weapon in hand wins, then a rending, then the weakness order. -/// A caster only counts for elements the character can cast. +/// A caster only counts for elements the character can cast. The weapon in hand is kept +/// when the winner is of another element and not at least minSwapGain more damage +/// (KeepInHand; both multipliers must be known). /// No listed weapon has any of them: keep the one in hand (else the learned best, else /// the first), and cast the weakest element the character can. /// 6. Weakness unknown: keep the weapon in hand (else the learned best, else the first) and @@ -76,7 +78,8 @@ internal static class WeaponPlanner string fixedSource = "Damage tab", int learnedBestId = 0, int creatureType = 0, - bool fixedIsDefault = false) + bool fixedIsDefault = false, + double minSwapGain = 0) { string rule = WeaponElements.Normalize(ruleElement); bool ruleSet = rule.Length > 0; @@ -156,7 +159,13 @@ internal static class WeaponPlanner if (rank < bestRank) { bestRank = rank; best = c; } } if (best != null) + { + var held = KeepInHand(pool, best, weak, canCast, minSwapGain); + if (held != null) + return new WeaponPlan(held.Id, held.Element, + $"weak to {best.Element} ({weak.Source}); {held.Element} in hand is within {minSwapGain * 100:0}%"); return new WeaponPlan(best.Id, best.Element, $"weak to {best.Element} ({weak.Source})"); + } } // No listed weapon has any element of the ranking: keep what we have. @@ -181,6 +190,34 @@ internal static class WeaponPlanner return new WeaponPlan(pool[0].Id, ElementOrFallback(pool[0], canCast), "ItemRules"); } + /// + /// Step 5's swap threshold: the weapon in hand, when is of another + /// element and does less than (0.2 = 20%) more damage to the + /// monster than it. A swap costs seconds of not attacking (a launcher with other ammo about + /// 4 s), so a small edge isn't worth it. Null (swap) when either multiplier isn't known + /// (a learned or seeded ranking has the order only), the hand weapon is immune-resisted (0), + /// or the threshold is off. + /// + public static WeaponCandidate? KeepInHand(IReadOnlyList pool, WeaponCandidate best, + CreatureWeakness.Ranking weak, Func canCast, double minSwapGain) + { + if (minSwapGain <= 0) return null; + var hand = InHand(pool); + if (hand == null || hand.Id == best.Id || hand.Element.Length == 0 || hand.Element == best.Element) return null; + if (hand.Kind == CombatMode.Magic && !canCast(hand.Element)) return null; + double handMult = MultOf(weak, hand.Element), bestMult = MultOf(weak, best.Element); + if (double.IsNaN(handMult) || double.IsNaN(bestMult) || handMult <= 0) return null; + return bestMult < handMult * (1 + minSwapGain) - TieEpsilon ? hand : null; + } + + /// The ranking's damage multiplier for ; NaN when not listed or not known. + private static double MultOf(CreatureWeakness.Ranking weak, string element) + { + foreach (var (e, m) in weak.Order) + if (e == element) return m; + return double.NaN; + } + /// /// The ranking's elements grouped by equal multiplier, weakest group first. A learned /// ranking (NaN multipliers) is one element per group. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs index 31703ea..2d5ae60 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs @@ -85,6 +85,20 @@ public sealed class WeaponSwapGate lock (_lock) _movingId = itemId; } + /// + /// The caller saw the noted move of finish and settle: the next swap + /// is paced on the server's answers () instead of the full MinIntervalMs. + /// Only for moves with no unwield motion behind them (ammo out of the ammunition slot); a + /// weapon or shield pack move keeps the full wait (see ). + /// + public void MoveDone(int itemId) + { + lock (_lock) + { + if (_movingId == itemId) _movingId = 0; + } + } + private bool LastSwapDone(long since) { if (since < FloorMs || ServerIdle == null || IsWielded == null) return false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs index bf4e822..fce334c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapTracker.cs @@ -20,6 +20,13 @@ namespace RynthCore.Plugin.RynthAi; /// was fought with the Quadrelle for 5-10 s until the 20 s dwell from the last swap ran out /// - "he attacks for about 5 seconds with the wrong element weapon"). The window cap still /// bounds a fight that alternates between two kinds of monster. +/// * A swap counts as landed when its weapon reaches the hand, even if the choice moved on +/// while it was in flight. +/// * A 'too busy' answer () is not a try: the server never looked at the +/// weapon. The wield goes again after , at most +/// times per weapon before they count. A portal or recall +/// () ends every rest (2026-10-15, Silentkelpie: a house recall and a +/// portal each spent all 3 tries on 'too busy' and benched the better weapon for 2 min). /// internal sealed class WeaponSwapTracker { @@ -41,10 +48,14 @@ internal sealed class WeaponSwapTracker public double MinDwellMs { get; set; } = 20_000; public int MaxSwapsPerWindow { get; set; } = 4; public double SwapWindowMs { get; set; } = 60_000; + public double BusyRetryMs { get; set; } = 1500; + public int MaxBusyRefunds { get; set; } = 6; private int _pendingId, _pendingFrom; private DateTime _pendingAt; + private DateTime _busyUntil = DateTime.MinValue; private readonly Dictionary _tries = new(); + private readonly Dictionary _busyRefunds = new(); private readonly Dictionary _restUntil = new(); private readonly List _landed = new(); private int _lastFrom, _lastTo; @@ -69,12 +80,22 @@ internal sealed class WeaponSwapTracker { HoldReason = ""; _askKey = forKey; + // The weapon in flight reached the hand although the choice has moved on (a new target + // wants another one). It still landed: without this the swap timed out as "not seen in + // hand", the A -> B landing was never recorded, and the swap straight back to A wasn't + // held (Fire -> Piercing -> Fire crossbow 2.5 s apart, 2026-10-14 11:41:06-08). + if (_pendingId != 0 && inHandId == _pendingId && inHandId != chosenId) + { + _tries.Remove(_pendingId); + Land(now); + } if (chosenId == 0) return Step.InHand; if (inHandId == chosenId) { if (_pendingId == chosenId) Land(now); _tries.Remove(chosenId); + _busyRefunds.Remove(chosenId); return Step.InHand; } @@ -84,6 +105,8 @@ internal sealed class WeaponSwapTracker Fail(now, "not seen in hand", nameOf); } + if (now < _busyUntil) return Step.Wait; + if (_restUntil.TryGetValue(chosenId, out DateTime rest) && now < rest) { HoldReason = "resting after failed tries"; @@ -124,6 +147,39 @@ internal sealed class WeaponSwapTracker if (_pendingId != 0) Fail(now, "refused by the server", nameOf); } + /// + /// The server answered the wield in flight 'too busy' (a recall, a portal, an animation): + /// it never looked at the weapon, so the try is given back and the wield goes again after + /// . Past for one weapon it counts as + /// a refusal, so a weapon the server always answers that way still gets rested. + /// True when the try was given back. + /// + public bool Busy(DateTime now, Func? nameOf = null) + { + int id = _pendingId; + if (id == 0) return false; + int refunds = _busyRefunds.TryGetValue(id, out int r) ? r : 0; + if (refunds >= MaxBusyRefunds) { Fail(now, "server too busy", nameOf); return false; } + _busyRefunds[id] = refunds + 1; + if (_tries.TryGetValue(id, out int t) && t > 0) _tries[id] = t - 1; + _pendingId = _pendingFrom = 0; + _busyUntil = now.AddMilliseconds(BusyRetryMs); + return true; + } + + /// + /// The character went through a portal or recalled: tries and rests from the last place no + /// longer say anything about the weapon (they were spent while the server was busy moving us). + /// + public void NewPlace() + { + _pendingId = _pendingFrom = 0; + _tries.Clear(); + _busyRefunds.Clear(); + _restUntil.Clear(); + _busyUntil = DateTime.MinValue; + } + /// The chosen weapon was seen in hand some other way (the wield-location read). public void Confirmed(int id, DateTime now) { @@ -135,6 +191,8 @@ internal sealed class WeaponSwapTracker { _pendingId = _pendingFrom = 0; _tries.Clear(); + _busyRefunds.Clear(); + _busyUntil = DateTime.MinValue; _restUntil.Clear(); _landed.Clear(); _lastFrom = _lastTo = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index 7481d3f..5377640 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -1572,7 +1572,8 @@ public class WorldObjectCache // Snapshot overload — caller supplies an already-built inventory list (AutoCram // reuses its single per-tick GetDirectInventory snapshot here; do NOT re-refresh). public static int FindPackFor(IReadOnlyList inv, int playerId, - bool includeMainPack, int requireFree, RynthCoreHost? host = null) + bool includeMainPack, int requireFree, RynthCoreHost? host = null, + Func? skip = null) { if (inv == null || playerId == 0) return 0; if (requireFree < 1) requireFree = 1; @@ -1593,6 +1594,7 @@ public class WorldObjectCache // Skip foci — technically containers but reserved for spell components. if (!string.IsNullOrEmpty(p.Name) && p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) continue; + if (skip != null && skip(p.Id)) continue; // the server refused it lately (PackRefusals) int capacity = p.Values(LongValueKey.ItemsCapacity, 0); if (capacity <= 0) continue; // capacity unknown — don't risk the move int used = 0; @@ -1612,7 +1614,7 @@ public class WorldObjectCache // Dequip fallback: the bow needs ONE free main-pack slot; a dequip into a // non-full main pack is AV-safe (the AV is only on a genuinely FULL target). int mainFree = 102 - mainUsed; - return mainFree > 0 ? playerId : 0; + return mainFree > 0 && !(skip != null && skip(playerId)) ? playerId : 0; } /// @@ -1623,7 +1625,9 @@ public class WorldObjectCache /// (2026-10-02). A move needs an explicit target, and the engine refuses a move into a /// full pack of ours, so this finds one with room. /// - public static int FindLootDestination(IReadOnlyList inv, int playerId, RynthCoreHost? host = null) + /// : packs (or the player id, for the main pack) the server refused lately. + public static int FindLootDestination(IReadOnlyList inv, int playerId, RynthCoreHost? host = null, + Func? skip = null) { if (inv == null || playerId == 0) return 0; int mainUsed = 0; // same tally as FindPackFor @@ -1635,8 +1639,8 @@ public class WorldObjectCache if (host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)) continue; mainUsed++; } - if (102 - mainUsed > 0) return playerId; - return FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host); + if (102 - mainUsed > 0 && !(skip != null && skip(playerId))) return playerId; + return FindPackFor(inv, playerId, includeMainPack: false, requireFree: 1, host, skip); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 316c846..795336f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -107,6 +107,11 @@ public sealed partial class RynthAiPlugin private bool _currentLootItemMovePending; private bool _corpseAutorunActive; private int _currentLootItemMoveAttempts; + // Where the current item's last move went, and whether it already got a second pack. + private int _currentLootItemDest; + private bool _currentLootItemPackRetried; + // Packs the server took none of an item's tries into (Loot/PackRefusals.cs). + private readonly RynthCore.Plugin.RynthAi.Loot.PackRefusals _packRefusals = new(); private long _currentLootItemStillSince; private long _currentLootItemLeftAt; private bool _currentLootItemSawAnim; @@ -145,6 +150,26 @@ public sealed partial class RynthAiPlugin Log(message); } + // The values behind the last [LootSettings] line; a new line goes out only when one changes. + private (LootBaseline.Timers Timers, double Max, double Min)? _lootSettingsLogged; + + /// + /// Logs the loot timers against the measured baseline (LootBaseline.cs), each marked "baseline" + /// or "custom (baseline N)", so a loot log says which settings it ran with. Runs every loot tick, + /// so it compares the raw values and builds the line only on a change. + /// + private void NoteLootSettings(LegacyUiSettings settings) + { + var timers = new LootBaseline.Timers( + settings.LootContentSettleMs, settings.LootEmptyCorpseMs, settings.LootAssessWindowMs, + settings.LootRetryTimeoutMs, settings.LootOpenRetryMs, settings.LootCorpseTimeoutMs); + var current = (timers, settings.CorpseApproachRangeMax, settings.CorpseApproachRangeMin); + if (_lootSettingsLogged == current) + return; + _lootSettingsLogged = current; + LootDiag(LootBaseline.Describe(timers, settings.CorpseApproachRangeMax, settings.CorpseApproachRangeMin)); + } + public override void OnBusyCountIncremented() { if (_busyCount == 0) @@ -579,6 +604,7 @@ public sealed partial class RynthAiPlugin ResetCorpseTarget(); return; } + NoteLootSettings(settings); // Wedge halt: AC's item-action state is locked (consecutive open // timeouts). Stop firing opens into a dead client until the halt window @@ -1985,6 +2011,22 @@ public sealed partial class RynthAiPlugin if (!freeRetry && _currentLootItemMoveAttempts >= 3) { + // None of the tries landed: the pack they went to is likely full (its contents + // unknown to the client). Leave that pack out for a while and give the item one + // more round into the next one; with no other pack, the item is left as before. + if (_currentLootItemDest != 0) + { + _packRefusals.Refuse(_currentLootItemDest, now); + if (!_currentLootItemPackRetried) + { + LootDiag($"[RynthAi] {LootTag}: {(_currentLootItemDest == _playerId ? "the main pack" : $"pack 0x{(uint)_currentLootItemDest:X8}")} took none of {_currentLootItemMoveAttempts} tries for 0x{(uint)_currentLootItemId:X8}; treating it as full for {RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs / 60_000} min and trying another pack."); + _currentLootItemPackRetried = true; + _currentLootItemMoveAttempts = 0; + _currentLootItemStillSince = 0; + _lastLootActionAt = now; + return; + } + } LootDiag($"[RynthAi] {LootTag}: pickup failed for 0x{(uint)_currentLootItemId:X8}; container remained 0x{(uint)_openedContainerId:X8} after {_currentLootItemMoveAttempts} attempt(s)."); _processedCorpseItems.Add(_currentLootItemId); ResetCurrentLootItem(); @@ -2054,7 +2096,9 @@ public sealed partial class RynthAiPlugin uint dest; LootPickupResult r = ownCorpse ? SendOwnCorpsePickup(itemId, out dest) - : LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest); + : LootPickup.Send(Host, _objectCache, unchecked((uint)itemId), _playerId, out dest, + id => _packRefusals.IsRefused(id, CorpseNowMs)); + if (r == LootPickupResult.Moved) _currentLootItemDest = unchecked((int)dest); if (ownCorpse && r == LootPickupResult.NoRoom) { PauseOwnCorpseNoRoom(corpseId, itemName); @@ -2093,6 +2137,7 @@ public sealed partial class RynthAiPlugin return; int itemId = _currentLootItemId; + if (answered && _currentLootItemDest != 0) _packRefusals.Accepted(_currentLootItemDest); _processedCorpseItems.Add(_currentLootItemId); LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" + $" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")})."); @@ -2183,6 +2228,15 @@ public sealed partial class RynthAiPlugin if (_combatEndedAt != 0 && (nowMs - _combatEndedAt) < LootGraceMs) return true; + // Boost Loot Priority: our kill's corpse is still forming. Looting holds the tick (combat + // holds its next target) so the corpse is looted before the next fight starts. + if (BoostLootAwaitsKillCorpse(settings)) + { + double range = GetCorpseApproachRangeMaxMeters(settings); + if (range > 0.25) HasUnlootedCorpsesInRange(range); // keeps _lootableInRange current + return true; + } + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); if (maxMeters <= 0.25) return false; @@ -2282,6 +2336,62 @@ public sealed partial class RynthAiPlugin => wantLoot && wantCombat && _lootStarved && _combatManager?.HasCloseThreat(LootStarveCloseYards) != true; + // -- Boost Loot Priority: one kill, one loot (2026-10-14) -------------------------------- + // Combat locked its next target a few ms after each kill, and ACE creates the corpse 1-3 s + // later (the death animation), so the arbiter always saw combat engaged and Boost Loot never + // won: Kelpie's corpses waited for a lull and were looted two or three at a time. Now our kill + // starts a wait of up to BoostLootKillWaitMs for its corpse. While it runs, or while a corpse + // is claimed, open or lootable in range, CombatManager locks no new target (HoldNewTarget) + // and looting counts as work, so the arbiter gives Looting the tick. + internal const long BoostLootKillWaitMs = 4000; + private long _boostLootKillAt; // CorpseNowMs of our last kill whose corpse isn't looted yet; 0 = none + + /// Our kill (KillerNotification): its corpse is on its way. + private void NoteBoostLootKill() => _boostLootKillAt = CorpseNowMs; + + /// + /// A completed corpse first seen after the kill (or never timed) is the kill's corpse: the + /// wait is over, so combat doesn't stand idle for the rest of it. + /// + private void EndBoostLootKillWait(int corpseId) + { + if (_boostLootKillAt == 0) return; + if (!_corpseWaitingSince.TryGetValue(corpseId, out long seen) || seen >= _boostLootKillAt) + _boostLootKillAt = 0; + } + + /// Boost Loot Priority is on and a corpse could be looted now (not with rare-only looting, + /// where most kills leave nothing to wait for). + private bool BoostLootCanRun(LegacyUiSettings settings) + => settings.BoostLootPriority && settings.IsMacroRunning && settings.EnableLooting + && !settings.LootOnlyRareCorpses + && !IsLootingBlockedByPack(settings) + && !_useRefusals.HoldsOpens(CorpseNowMs); + + /// Our last kill was under BoostLootKillWaitMs ago and its corpse isn't looted yet. + private bool BoostLootAwaitsKillCorpse(LegacyUiSettings settings) + { + if (_boostLootKillAt == 0) return false; + if (CorpseNowMs - _boostLootKillAt >= BoostLootKillWaitMs) + { + _boostLootKillAt = 0; + return false; + } + return BoostLootCanRun(settings); + } + + /// + /// CombatManager.HoldNewTarget: with Boost Loot Priority on, no new target while a corpse is + /// claimed, open or lootable in range, or our kill's corpse is still forming. + /// + private bool BoostLootHoldsNewTarget() + { + LegacyUiSettings? settings = _dashboard?.Settings; + if (settings == null || !BoostLootCanRun(settings)) return false; + return _targetCorpseId != 0 || _openedContainerId != 0 || _lootableInRange.Count > 0 + || BoostLootAwaitsKillCorpse(settings); + } + private static bool IsOwnKill(CorpseLootDecision d) => !string.IsNullOrWhiteSpace(d.KillerName) && !string.IsNullOrWhiteSpace(d.PlayerName) && NormalizeCharName(d.KillerName).Equals(NormalizeCharName(d.PlayerName), StringComparison.OrdinalIgnoreCase); @@ -2803,6 +2913,7 @@ public sealed partial class RynthAiPlugin } _completedCorpses[corpseId] = CorpseNowMs; + EndBoostLootKillWait(corpseId); _corpseCooldownUntil.Remove(corpseId); _processedCorpseItems.Clear(); _corpseItemAttempts.Clear(); @@ -2868,6 +2979,8 @@ public sealed partial class RynthAiPlugin _currentLootItemMovePending = false; _currentLootItemMoveRequestedAt = 0; _currentLootItemMoveAttempts = 0; + _currentLootItemDest = 0; + _currentLootItemPackRetried = false; _currentLootItemStillSince = 0; _currentLootItemLeftAt = 0; _currentLootItemSawAnim = false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs index 9309e16..35b6572 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs @@ -178,7 +178,7 @@ internal static class LogEvents LogCat.Meta => "Meta (VTank-style) state machine and actions.", LogCat.Expressions => "Meta expression evaluation.", LogCat.Quests => "Quest tracking.", - LogCat.Crafting => "Missile ammo crafting.", + LogCat.Crafting => "Missile ammo crafting and the Mini Remote's Crafting tab.", LogCat.Raycast => "Line-of-sight raycasts and geometry loading.", LogCat.Radar => "Radar window.", LogCat.UI => "RynthAi UI windows and panels.", diff --git a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs index 08cb945..410e01e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs @@ -43,6 +43,7 @@ internal static unsafe class HubInterface t->RenderSection = &RenderSection; t->SessionStats = &SessionStats; t->SessionReset = &SessionReset; + t->SessionStatsMore = &SessionStatsMore; t->Version = RynthAiHubApiV1.InterfaceVersion; _table = t; } @@ -230,6 +231,25 @@ internal static unsafe class HubInterface catch { return 0; } } + /// The rest of the same session (RynthTracker's panel shows it whole). 0 before login. + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SessionStatsMore(SessionStatsMoreV1* more) + { + try + { + var tracker = Plugin?.SessionStatsForIlt; + if (tracker == null || more == null) return 0; + var v = tracker.View; + more->XpPerKill = v.XpPerKill; + more->Deaths = v.Deaths; + more->MaxLevel = v.MaxLevel ? 1 : 0; + more->Rad = v.Rad; + more->RadPerHour = v.RadPerHour; + return 1; + } + catch { return 0; } + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void SessionReset() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/FellowshipSectionUi.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/FellowshipSectionUi.cs new file mode 100644 index 0000000..a371692 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/FellowshipSectionUi.cs @@ -0,0 +1,144 @@ +// FellowshipSectionUi.cs - RynthCore's Fellowship section (RynthPluginRenderEmbed +// "section:fellowship") and the Mini Remote's Fellowship tab: the fellowship you are in, from +// FellowshipTracker. Render thread only. +// +// Name, leader, open / locked / XP sharing, and the members with their levels (you and the +// leader marked). The tracker reads AC's fellowship object, which AC's main thread (the render +// thread here) owns, and caches the member list for two seconds; this view re-reads it once a +// second. The Mini Remote tab also draws the active server's fellowship commands +// (ServerCommandModel, e.g. RynthILT's /fship); RynthCore's section shows the server plugin's +// own pane for those, so the embedded view leaves them out. +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.Huds; + +internal sealed class FellowshipSectionUi +{ + /// The section id server plugins send fellowship commands for. + public const string CommandSection = "fellowship"; + + private const long RefreshMs = 1000; + + private static readonly Vector4 ColLeader = new(0.95f, 0.80f, 0.35f, 1f); + private static readonly Vector4 ColMute = new(0.80f, 0.84f, 0.90f, 1f); + + private readonly Func _tracker; + private readonly Func _playerId; + private readonly Func _sendCommand; + private readonly ServerCommandPanel _commands = new("fellow"); + + // The last read (render thread only). + private long _readAt = long.MinValue / 2; + private bool _inFellowship; + private string _name = string.Empty; + private int _leaderId; + private bool _open, _locked, _shareXp; + private readonly List<(int Id, string Name, int Level)> _members = new(); + + /// Queues a chat command for the plugin tick; false when it can't. + public FellowshipSectionUi(Func tracker, Func playerId, Func sendCommand) + { + _tracker = tracker; + _playerId = playerId; + _sendCommand = sendCommand; + } + + /// + /// Draws the view into the current window. adds the + /// active server's fellowship commands above the member list. Render thread. + /// + public void Render(bool withServerCommands) + { + FellowshipTracker? t = _tracker(); + if (t == null) + { + ImGui.TextDisabled("Fellowship tracking starts at login."); + return; + } + Refresh(t); + + if (_inFellowship) + { + SafeImGui.TextColored(ColLeader, _name.Length > 0 ? _name : "(unnamed fellowship)"); + SafeImGui.TextDisabled($"{_members.Count} member(s) {(_open ? "Open" : "Closed")} {(_locked ? "Locked" : "Unlocked")} XP {(_shareXp ? "shared" : "not shared")}"); + } + else + { + ImGui.TextDisabled("Not in a fellowship."); + } + + // Shown out of a fellowship too: that's when "create" is wanted. + if (withServerCommands) RenderServerCommands(); + if (!_inFellowship) return; + ImGui.Separator(); + + uint me = SafePlayerId(); + if (ImGui.BeginTable("##fellows", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.ScrollY, + new Vector2(0, MathF.Max(60f, ImGui.GetContentRegionAvail().Y)))) + { + ImGui.TableSetupColumn("Member", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Level", ImGuiTableColumnFlags.WidthFixed, 50f); + ImGui.TableSetupColumn("Role", ImGuiTableColumnFlags.WidthFixed, 90f); + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableHeadersRow(); + foreach ((int id, string name, int level) in _members) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + bool leader = id == _leaderId; + if (leader) SafeImGui.TextColored(ColLeader, name); + else SafeImGui.Text(name); + ImGui.TableNextColumn(); + SafeImGui.TextColored(ColMute, level > 0 ? level.ToString() : string.Empty); + ImGui.TableNextColumn(); + string role = (leader ? "Leader" : string.Empty) + ((uint)id == me && me != 0 ? (leader ? ", you" : "You") : string.Empty); + SafeImGui.TextColored(ColMute, role); + } + ImGui.EndTable(); + } + } + + // The fellowship commands the active server's plugin sent, if any. + private void RenderServerCommands() + { + ServerCommandSet? set = ServerCommandModel.For(CommandSection); + if (set == null || set.Commands.Count == 0) return; + ImGui.Separator(); + SafeImGui.TextColored(ColMute, (set.ServerName.Length > 0 ? set.ServerName : "Server") + " fellowship commands"); + _commands.Render(set, _sendCommand); + } + + private void Refresh(FellowshipTracker t) + { + long now = Environment.TickCount64; + if (now - _readAt < RefreshMs) return; + _readAt = now; + _members.Clear(); + _inFellowship = t.IsInFellowship; + if (!_inFellowship) return; + _name = t.FellowshipName ?? string.Empty; + _leaderId = t.LeaderId; + _open = t.IsOpen; + _locked = t.IsLocked; + _shareXp = t.ShareXP; + foreach ((int id, string name, int level) in t.GetMembers()) + _members.Add((id, name.Length > 0 ? name : $"0x{id:X8}", level)); + int leaderId = _leaderId; + _members.Sort((a, b) => + { + // Leader first, then by name. + int byLeader = (b.Id == leaderId).CompareTo(a.Id == leaderId); + return byLeader != 0 ? byLeader : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + } + + private uint SafePlayerId() + { + try { return _playerId(); } + catch { return 0; } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs index b646f40..0d4c6f3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs @@ -521,8 +521,23 @@ internal sealed class HudController { tab ??= string.Empty; string label = tab.Length == 0 ? "Remote" : char.ToUpperInvariant(tab[0]) + tab.Substring(1); - bool selected = string.Equals(State.MiniRemoteTab, tab, StringComparison.OrdinalIgnoreCase); string m = (mode ?? string.Empty).ToLowerInvariant(); + // Character / Charms / Banking left the Mini Remote (2026-10-13): open their new home. + if (MovedTabs.CommandFor(tab) is string moved) + { + if (string.Equals(State.MiniRemoteTab, tab, StringComparison.OrdinalIgnoreCase)) _miniRemote.RequestTab(string.Empty); + if (m is "hide" or "off" or "close") return $"{label} isn't a Mini Remote tab any more ({MovedTabs.HomeOf(moved)}, {moved})."; + RunEngineCommand(moved); + return $"{label} moved to {MovedTabs.HomeOf(moved)} ({moved})."; + } + bool selected = string.Equals(State.MiniRemoteTab, tab, StringComparison.OrdinalIgnoreCase); + // RynthCore shows the tabs as sections: open it there. Not for "select", which is how + // RynthCore itself falls back to this tab bar (re-sending would bounce between the two). + if (EngineHostsSections && m is not ("select" or "hide" or "off" or "close")) + { + RunEngineCommand(tab.Length == 0 ? "/rc miniremote section remote" : "/rc miniremote tab " + tab); + return $"Mini Remote (RynthCore's window): {label}."; + } bool hide = m is "hide" or "off" or "close" || (m is not ("show" or "on" or "open" or "select") && selected && MiniRemoteActive); if (hide) @@ -540,6 +555,9 @@ internal sealed class HudController // ── Render thread ─────────────────────────────────────────────────────── + /// RynthCore's Mini Remote "Session Stats" section (SectionsManifest.SessionSurface). Render thread. + public void RenderSessionSection() => _miniRemote.RenderSessionSection(); + public void Render() { int pushed = LegacyDashboardRenderer.PushDashboardStyle(); @@ -561,7 +579,7 @@ internal sealed class HudController /// Mini Remote drawer, or with the engine's Mini Remote window) /// and returns the content size it wants. Render thread. /// - public System.Numerics.Vector2 RenderEmbedded(bool window = false) + public System.Numerics.Vector2 RenderEmbedded(bool window = false, bool tabs = true) { long now = NowMs; System.Threading.Interlocked.Exchange(ref _embeddedDrawnAt, now); @@ -569,11 +587,25 @@ internal sealed class HudController int pushed = LegacyDashboardRenderer.PushDashboardStyle(); try { - return _miniRemote.RenderEmbedded(window); + return _miniRemote.RenderEmbedded(window, tabs); } finally { ImGuiNET.ImGui.PopStyleColor(pushed); } } + + /// + /// RynthCore's Mini Remote window is open on one of its sections (not the remote): it is still + /// the one Mini Remote, so the floating copy stays hidden and the data keeps polling. Render thread. + /// + public void MarkEngineWindow() + { + long now = NowMs; + System.Threading.Interlocked.Exchange(ref _embeddedDrawnAt, now); + System.Threading.Interlocked.Exchange(ref _windowDrawnAt, now); + } + + /// RynthCore shows the Mini Remote's tabs as its own sections (it sent their list). + public static bool EngineHostsSections => ServerMenuModel.Sections.Length > 0; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs index ff41ed1..9ebb50b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs @@ -11,6 +11,7 @@ using System.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.Huds; @@ -148,7 +149,7 @@ internal sealed class HudSetupUi ImGui.SetCursorPos(start); HudDraw.Icon(_hud.Icons, iconDid, name, ListIcon, dim); ImGui.SameLine(); - if (dim) ImGui.TextDisabled(label); + if (dim) SafeImGui.TextDisabled(label); else ImGui.TextUnformatted(label); return clicked; } @@ -158,7 +159,7 @@ internal sealed class HudSetupUi var slots = s.MiniRemoteSlots.ToArray(); if (slots.Length == 0) return; ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Mini Remote slots"); - ImGui.TextDisabled($"Slot 01 = top-left of the Mini Remote grid ({HudState.MiniRemoteColumns} per row). " + SafeImGui.TextDisabled($"Slot 01 = top-left of the Mini Remote grid ({HudState.MiniRemoteColumns} per row). " + "Select an item in your pack, pick the slot, then Set."); _slot = Math.Clamp(_slot, 0, slots.Length - 1); string Label(int i) => $"{i + 1:00} - {(slots[i].IsEmpty ? "(empty)" : slots[i].Name)}"; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs index 7ae9702..eddadb6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Numerics; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.Huds; @@ -52,16 +53,16 @@ internal sealed class ItemCountHud { long count = pack.CountOf(e.Name); HudDraw.Icon(_hud.Icons, e.IconDid, e.Name, size, count == 0); - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{e.Name}\n{count:N0} carried"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{e.Name}\n{count:N0} carried"); ImGui.SameLine(); // Vertically centre the text on the icon. float pad = (size - ImGui.GetTextLineHeight()) * 0.5f; if (pad > 0) ImGui.SetCursorPosY(ImGui.GetCursorPosY() + pad); - ImGui.TextColored(count == 0 ? ColNone : ColCount, count.ToString("N0")); + SafeImGui.TextColored(count == 0 ? ColNone : ColCount, count.ToString("N0")); if (s.ItemHudShowNames) { ImGui.SameLine(); - ImGui.TextColored(ColName, e.Name); + SafeImGui.TextColored(ColName, e.Name); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs index 570f446..c4658cb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs @@ -1,16 +1,18 @@ // MiniRemoteHud.cs — The Mini Remote (UtilityBelt-style) for RynthAi. Render thread only. // -// One window with tabs: Remote (the sections below), the universal tabs Quests and Pets (every -// world, MiniRemote/), and on Infinite Leaftide the RynthILT plugin's ILT tabs (Character, -// Banking, Gear, Charms, Games: RynthILT.Hub GetTabs / RenderTab through IltClient; an ILT tab +// 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). -// Right-click on the remote: "Character" (Spells, Quests, Pets, 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, which RynthCore sends (ServerMenuModel), or "Treat -// this world as ..." when none matches. The Options button holds the Mini Remote's own settings. +// 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, +// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a +// server is forced) when none matches. The Options button holds the Mini Remote's own settings. // 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): @@ -30,12 +32,13 @@ // All game actions are posted to the pump thread. // // RenderEmbedded draws the same sections and Options menu inside the engine's RynthAi dashboard -// (its Mini Remote drawer, opened by the Hub launcher's right-click or the drawer tab) and +// (its Mini Remote drawer, opened by the drawer tab) and // reports the size it wants; the drawer is sized from that. The drawer leaves out Toggles (the // dashboard it sits on already has those switches) and the tabs (it is too narrow for them). // RenderEmbedded(window: true) draws it in the engine's Mini Remote window instead (bar button, // /rc miniremote): tabs and Toggles included, and the floating window stays hidden meanwhile -// (HudController), so that window is the one Mini Remote. +// (HudController), so that window is the one Mini Remote. RynthCore 2026.10.5.46+ shows the tabs +// as its own sections (RynthPluginGetSectionsJson) and asks for the remote alone (tabs: false). using System; using System.Collections.Generic; using System.Linq; @@ -136,7 +139,7 @@ internal sealed class MiniRemoteHud /// themselves from the result) instead of a window of their own. Returns the content size it /// wants: the selected tab's width, and the height drawn. ///
- public Vector2 RenderEmbedded(bool window = false) + public Vector2 RenderEmbedded(bool window = false, bool tabs = true) { var s = _hud.State; _slotMenuIndex = -1; @@ -146,7 +149,8 @@ internal sealed class MiniRemoteHud ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3)); try { - float width = RenderBody(s, _hud.Remote(), allowTabs: !InDrawer); + // Without tabs (RynthCore's sections show them instead) the remote alone. + float width = RenderBody(s, _hud.Remote(), allowTabs: tabs && !InDrawer); if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuPopup); @@ -214,7 +218,7 @@ internal sealed class MiniRemoteHud // 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) ImGui.TextDisabled(tab.Ilt ? "RynthILT isn't drawing this tab (not loaded, or not ready yet)." : "Not ready."); + if (!drawn) SafeImGui.TextDisabled(tab.Ilt ? "RynthILT isn't drawing this tab (not loaded, or not ready yet)." : "Not ready."); ImGui.EndChild(); width = Math.Max(width, tab.Size.X); ImGui.EndTabItem(); @@ -313,7 +317,7 @@ internal sealed class MiniRemoteHud if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0))) s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal; if (ImGui.IsItemHovered()) - ImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns."); + SafeImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns."); ImGui.SameLine(); // Opened by RenderOptions: this row sits inside the Remote tab, whose ID the popup must not get. if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) _openOptions = true; @@ -418,7 +422,7 @@ internal sealed class MiniRemoteHud private static void Stat(string label, string value) { - ImGui.TextColored(ColLabel, label); + SafeImGui.TextColored(ColLabel, label); ImGui.SameLine(); ImGui.TextUnformatted(value); } @@ -438,7 +442,7 @@ internal sealed class MiniRemoteHud if (v.PassUpTracked) { Stat("Pass-up:", HudDraw.Compact(v.PassUpPerHour) + "/h"); - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{PassUpTooltip}"); + 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; @@ -446,7 +450,53 @@ internal sealed class MiniRemoteHud Stat("Pyr:", HudDraw.Compact(pyreals) + "/h"); } - /// What the pass-up figure is (RynthILT's Character tab says the same). + /// + /// RynthCore's Mini Remote "Session Stats" section (surface "section:session"): the one session, + /// totals and per-hour rates, with Reset and Report. RynthTracker, RynthOracle and RynthILT read + /// these same numbers (RynthAi.Hub SessionStats), so every XP/h and lum/h on screen agrees. + /// Render thread. + /// + public void RenderSessionSection() + { + var v = _hud.SessionStats?.View ?? RynthCore.Plugin.Shared.SessionStatsView.Empty; + bool running = !ReferenceEquals(v, RynthCore.Plugin.Shared.SessionStatsView.Empty); + SafeImGui.TextDisabled(running + ? "Session " + MiniRemoteText.Duration(TimeSpan.FromSeconds(SessionClock(v))) + : "The session starts once you are in the world."); + if (ImGui.BeginTable("##mrsession", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Stat", ImGuiTableColumnFlags.WidthStretch, 1.2f); + ImGui.TableSetupColumn("Session", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGui.TableSetupColumn("Per hour", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGui.TableHeadersRow(); + SessionRow("XP", HudDraw.Compact(v.Xp), HudDraw.Compact(v.XpPerHour)); + SessionRow("Luminance", HudDraw.Compact(v.Lum), HudDraw.Compact(v.LumPerHour)); + // The last five minutes' luminance, and that pace for an hour. + SessionRow(" last 5 min", HudDraw.Compact(v.LumLast5Min), HudDraw.Compact(v.LumLast5Min * 12.0)); + if (v.PassUpTracked) SessionRow(" pass-up", HudDraw.Compact(v.LumPassUp), HudDraw.Compact(v.PassUpPerHour), PassUpTooltip); + if (v.Rad > 0) SessionRow("Radiance", HudDraw.Compact(v.Rad), HudDraw.Compact(v.RadPerHour)); + SessionRow("Kills", v.Kills.ToString("N0"), HudDraw.Compact(v.KillsPerHour)); + if (v.XpPerKill > 0) SessionRow(" XP per kill", HudDraw.Compact(v.XpPerKill), string.Empty); + if (v.Deaths > 0) SessionRow("Deaths", v.Deaths.ToString("N0"), string.Empty); + ImGui.EndTable(); + } + RenderStatButtons(_hud.Remote()); + } + + /// One Session Stats row: label, session total, per hour (and an optional tooltip on the label). + private static void SessionRow(string label, string total, string perHour, string tooltip = "") + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.TextColored(ColLabel, label); + if (tooltip.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(tooltip); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(total); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(perHour); + } + + /// What the pass-up figure is (RynthILT's session rates say the same). private const string PassUpTooltip = "Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\n" + "Fellowship and Zone Share splits arrive the same silent way and are included."; @@ -465,7 +515,7 @@ internal sealed class MiniRemoteHud if (c.TargetDistance >= 0) { ImGui.SameLine(); - ImGui.TextDisabled($"{c.TargetDistance:F0}yd"); + SafeImGui.TextDisabled($"{c.TargetDistance:F0}yd"); } HealthBar("##mrtargethp", c.TargetHealth); } @@ -484,7 +534,7 @@ internal sealed class MiniRemoteHud if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; } ImGui.TextUnformatted(name); var col = status switch { "Ready" => ColReady, "Out" => ColOut, "Healing" => ColBusy, _ => ColEmpty }; - ImGui.TextColored(col, status); + SafeImGui.TextColored(col, status); } private static void RenderSummon(MiniRemoteController? remote, CombatHudSnapshot c) @@ -513,14 +563,14 @@ internal sealed class MiniRemoteHud } else { - ImGui.TextColored(left.TotalSeconds <= 30 ? ColEmpty : ColOut, text); + SafeImGui.TextColored(left.TotalSeconds <= 30 ? ColEmpty : ColOut, text); } } else { // No RemainingLifespan from the server: show how long it has been out instead. var up = TimeSpan.FromMilliseconds(Math.Max(0, now - c.PetSeenAtMs)); - ImGui.TextDisabled($"Out {FormatClock(up)}"); + SafeImGui.TextDisabled($"Out {FormatClock(up)}"); if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server hasn't reported this summon's lifespan yet."); } } @@ -556,7 +606,7 @@ internal sealed class MiniRemoteHud _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 (the Tracker panel keeps its own session)."); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (RynthTracker, RynthOracle and RynthILT 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)."); @@ -604,7 +654,7 @@ internal sealed class MiniRemoteHud if (e.IsEmpty) ImGui.PopStyleColor(); } if (ImGui.IsItemHovered()) - ImGui.SetTooltip(e.IsEmpty ? EmptySlotTip(i) : $"{e.Name}\n{count:N0} carried\nClick to use, right-click for options.\nCtrl+wheel: box size."); + SafeImGui.SetTooltip(e.IsEmpty ? EmptySlotTip(i) : $"{e.Name}\n{count:N0} carried\nClick to use, right-click for options.\nCtrl+wheel: box size."); int slotIndex = i; if (clicked) { @@ -678,7 +728,7 @@ internal sealed class MiniRemoteHud { if (!ImGui.BeginPopup(SlotPopup)) return; _slotMenuIndex = index; - ImGui.TextDisabled(e.IsEmpty ? $"Slot {index + 1:00}" : $"Slot {index + 1:00}: {e.Name}"); + SafeImGui.TextDisabled(e.IsEmpty ? $"Slot {index + 1:00}" : $"Slot {index + 1:00}: {e.Name}"); string candidate = _hud.AssignCandidate; if (ImGui.MenuItem(candidate.Length > 0 ? $"Assign {candidate}" : "Assign selected item")) _hud.Post(() => _hud.SetSlotFromSelection(index)); @@ -805,8 +855,9 @@ internal sealed class MiniRemoteHud } /// - /// "Character": RynthAi's own windows, the universal Mini Remote tabs (Quests, Pets), and - /// RynthCore's panels when it runs /rc commands. + /// "Character": RynthAi's own windows, the universal Mini Remote tabs (Pets, Crafting), RynthOracle's + /// quest and fellowship windows (the Quests and Fellowship tabs moved there 2026-10-13) and + /// RynthCore's panels, when chat commands can be run. /// private void RenderCharacterMenu(HudState s) { @@ -822,6 +873,17 @@ 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). + 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"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle: quest timers, tracking and rewards."); + if (ImGui.MenuItem("Quest Timers##mrqtimers", "/ro timers")) _hud.RunEngineCommand("/ro timers"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Quest Timers window: your tracked quests and the time left on each."); + if (ImGui.MenuItem("Fellowship##mrfellow", "/ro fellowship")) _hud.RunEngineCommand("/ro fellowship"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Fellowship tab: members, levels and XP sharing."); if (ImGui.MenuItem("Skills##mrskills", "/rc skills")) _hud.RunEngineCommand("/rc skills toggle"); if (ImGui.MenuItem("Inventory##mrinv", "/rc inventory")) _hud.RunEngineCommand("/rc inventory"); if (ImGui.MenuItem("Item Count##mritemcount", "/rc itemcount")) _hud.RunEngineCommand("/rc itemcount"); @@ -852,17 +914,21 @@ internal sealed class MiniRemoteHud if (!g.Active && !forcedHere) continue; any = true; ImGui.Separator(); - ImGui.TextDisabled("Server: " + (g.Active ? g.Name : g.Name + " (forced)")); + SafeImGui.TextDisabled("Server: " + (g.Active ? g.Name : g.Name + " (forced)")); foreach (ServerMenuEntry item in g.Items) { string? tab = ServerMenuModel.TabOf(item.Feature); - // Universal tabs are under Character; RynthCore 2026.10.5.30 and older list them here too. - if (tab != null && MiniRemoteTabs.Parse(tab) != null) continue; + // Universal tabs are under Character; RynthCore 2026.10.5.30 and older list them here too + // (with the retired Quests tab, now RynthOracle's). + if (tab != null && (MiniRemoteTabs.Parse(tab) != null || tab.Equals("quests", StringComparison.OrdinalIgnoreCase))) continue; + // Character (an older RynthCore still lists it) moved out: it is under Character above + // (RynthOracle's Character tab). + if (tab != null && MovedTabs.CommandFor(tab) != null) continue; bool enabled = tab == null || TabAvailable(remote, tab); if (ImGui.MenuItem(item.Label + "##mrsrv_" + g.Id, item.Command, false, enabled)) RunServerItem(item, tab); if (item.Tooltip.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on."); + SafeImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on."); } if (ilt) remote?.Ilt.RenderSection(RynthIltHub.SectionIltStatus); } @@ -870,14 +936,12 @@ internal sealed class MiniRemoteHud ImGui.Separator(); ImGui.TextDisabled("Server: no installed server plugin matches this world"); - foreach (ServerMenuGroup g in groups) - { - if (g.ForceCommand.Length == 0) continue; - if (ImGui.MenuItem("Treat this world as " + g.Name + "##mrforce_" + g.Id, g.ForceCommand)) - ForceServer(g, remote); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Shows this server's windows here anyway. It only says which world this is:\nthe server still decides which features exist."); - } + // Forcing a server lives in one place since 2026-10-13: RynthCore's Options > Diagnostics. + if (_hud.Host.HasInvokeChatParser && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", MovedTabs.Diagnostics)) + _hud.RunEngineCommand(MovedTabs.Diagnostics); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) shows a server's windows here anyway.\n" + + "It only says which world this is: the server still decides which features exist."); } /// A Mini Remote tab switches here and now; anything else is a RynthCore command. @@ -887,16 +951,6 @@ internal sealed class MiniRemoteHud else if (item.Command.Length > 0) _hud.RunEngineCommand(item.Command); } - /// - /// Forces a server: RynthCore's session override, plus for Infinite Leaftide this character's - /// "Treat this world as ILT" (so RynthILT's tabs come too). - /// - private void ForceServer(ServerMenuGroup g, MiniRemoteController? remote) - { - if (g.Id.Equals(IltServerId, StringComparison.OrdinalIgnoreCase) && remote != null) remote.Ilt.ForceIlt = true; - _hud.RunEngineCommand(g.ForceCommand); - } - /// RynthILT reports that ILT tab's feature on (false without RynthILT). private static bool TabAvailable(MiniRemoteController? remote, string tab) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs new file mode 100644 index 0000000..aac6f91 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs @@ -0,0 +1,41 @@ +// MovedTabs.cs - Mini Remote tabs that moved out of the Mini Remote (2026-10-13), and where to. +// +// RynthILT's Character tab left the Mini Remote: its character overview and session went to +// 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. +// 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. +using System; + +namespace RynthCore.Plugin.RynthAi.Huds; + +internal static class MovedTabs +{ + /// RynthOracle's Character tab (the character overview and this session). + public const string OracleCharacter = "/ro character"; + + /// RynthCore Options > Diagnostics (the server picker; RynthCore 2026.10.5.54+). + public const string Diagnostics = "/rc diagnostics"; + + /// + /// The chat command that opens where tab lives now, or null when it is + /// still a Mini Remote tab (or not a tab at all). Case and padding don't matter. + /// + public static string? CommandFor(string? tab) => (tab ?? string.Empty).Trim().ToLowerInvariant() switch + { + "character" or "char" or "rates" => OracleCharacter, + _ => null, + }; + + /// Where opens, in words, for chat replies and tooltips. + public static string HomeOf(string command) => command switch + { + OracleCharacter => "RynthOracle's Character tab", + Diagnostics => "RynthCore Options > Diagnostics", + _ => command, + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs new file mode 100644 index 0000000..827b1ca --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs @@ -0,0 +1,184 @@ +// SectionsManifest.cs - What RynthAi adds to RynthCore's Mini Remote sections. +// +// RynthCore 2026.10.5.46+ shows the Mini Remote as a rail of sections: its core twelve (Session +// 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. +// +// Pure: RynthILT's tabs come in as a list, so the host tests build it offline. +using System; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.MiniRemote; + +namespace RynthCore.Plugin.RynthAi.Huds; + +internal static class SectionsManifest +{ + /// Prefix of every RynthAi section surface ("section:pets"). + public const string SurfacePrefix = "section:"; + + public const string PetsSurface = SurfacePrefix + MiniRemoteTabs.Pets; + public const string CraftingSurface = SurfacePrefix + MiniRemoteTabs.Crafting; + public const string SpellsSurface = SurfacePrefix + "spells"; + public const string FellowshipSurface = SurfacePrefix + "fellowship"; + /// 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); + + /// 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), + }; + + 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)."), + }; + + /// The surface name of a tab's view ("section:gear"). + 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) + { + var views = new List + { + // Every world. Session Stats first: a universal primary view, so RynthCore drops its own overview. + new("char", string.Empty, "Session stats", SessionSurface, true, new Vector2(360, 240), true, string.Empty, + "XP, luminance and kills this session, per hour (RynthAi; RynthTracker, RynthOracle and RynthILT show the same session).", 100), + 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), + 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; + } + + /// The manifest JSON for (UTF-8 text, schema version 1). + public static string Build(IReadOnlyList views, IReadOnlyList
sections) + { + using var stream = new MemoryStream(4096); + using (var w = new Utf8JsonWriter(stream)) + { + w.WriteStartObject(); + w.WriteNumber("version", 1); + w.WriteStartArray("sections"); + foreach (Section s in sections) + { + w.WriteStartObject(); + w.WriteString("id", s.Id); + w.WriteString("label", s.Label); + w.WriteNumber("order", s.Order); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteStartArray("contributions"); + foreach (View v in views) + { + w.WriteStartObject(); + w.WriteString("section", v.Section); + w.WriteString("server", v.Server); + w.WriteString("label", v.Label); + w.WriteString("surface", v.Surface); + w.WriteBoolean("primary", v.Primary); + if (v.Size.X > 0) w.WriteNumber("width", v.Size.X); + if (v.Size.Y > 0) w.WriteNumber("height", v.Size.Y); + w.WriteBoolean("enabled", v.Enabled); + if (v.Note.Length > 0) w.WriteString("note", v.Note); + if (v.Tooltip.Length > 0) w.WriteString("tooltip", v.Tooltip); + w.WriteNumber("order", v.Order); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// The Mini Remote tab of RynthAi's own a surface draws ("pets", "crafting"), if it is one. + public static bool TryOwnTabOf(string surface, out string tabId) + { + tabId = surface switch + { + PetsSurface => MiniRemoteTabs.Pets, + CraftingSurface => MiniRemoteTabs.Crafting, + _ => string.Empty, + }; + 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/Huds/ServerCommandModel.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerCommandModel.cs new file mode 100644 index 0000000..3ce2b37 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerCommandModel.cs @@ -0,0 +1,51 @@ +// ServerCommandModel.cs - Server commands other plugins hand RynthAi for its section views. +// +// A server plugin sends the "servercommands" remote command (Plugins/Shared/ServerCommandShare.cs) +// while its server is active: RynthILT sends Infinite Leaftide's /fship commands for the +// "fellowship" section every 10 s, and an empty list when ILT isn't active. RynthAi keeps the +// latest set per section and drops one that hasn't been re-sent for StaleMs (the sender unloaded +// or the engine lost it), so the buttons follow the server without RynthAi knowing any of them. +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.Huds; + +internal static class ServerCommandModel +{ + /// A set not re-sent within this long is dropped (senders re-send every 10 s). + public const long StaleMs = 35_000; + + private sealed record Entry(ServerCommandSet Set, long ReceivedAt); + + // Replaced whole on each change: the pump thread writes, the render thread reads. + private static Dictionary _sets = new(StringComparer.OrdinalIgnoreCase); + + /// Pump thread: stores a "servercommands" push. A malformed payload is ignored, never thrown. + public static void Apply(string payload) => Apply(payload, Environment.TickCount64); + + /// Stores a push received at (tests pass the clock). + public static void Apply(string payload, long now) + { + ServerCommandSet? set = ServerCommandShare.Parse(payload); + if (set == null) return; + var next = new Dictionary(Volatile.Read(ref _sets), StringComparer.OrdinalIgnoreCase); + if (set.Commands.Count == 0) next.Remove(set.Section); + else next[set.Section] = new Entry(set, now); + Volatile.Write(ref _sets, next); + } + + /// The commands for , or null when none are current. Any thread. + public static ServerCommandSet? For(string section) => For(section, Environment.TickCount64); + + /// The commands for at , or null. + public static ServerCommandSet? For(string section, long now) + { + if (!Volatile.Read(ref _sets).TryGetValue(section, out Entry? e)) return null; + return now - e.ReceivedAt <= StaleMs ? e.Set : null; + } + + /// Forgets every set (logout: the next character's server sends its own). + public static void Clear() => Volatile.Write(ref _sets, new Dictionary(StringComparer.OrdinalIgnoreCase)); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerMenuModel.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerMenuModel.cs index 9b2c0b6..4bdab4a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerMenuModel.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/ServerMenuModel.cs @@ -1,13 +1,19 @@ -// ServerMenuModel.cs - The server sections RynthCore pushes for the Mini Remote's right-click menu. +// ServerMenuModel.cs - The servers and sections RynthCore pushes for the Mini Remote's menus. // -// RynthCore defines each server it knows (Infinite Leaftide today), whether the client is on it -// (or forced onto it), and the windows its installed plugins add for it (UI/ServerMenus.cs in -// RynthCore). It sends that list as the "servermenu" remote command when it changes, and again -// every 30 s. The payload is one tab-separated line per section ("S", id, name, active 0/1, force -// command), then its items ("I", label, command, tooltip, feature). +// RynthCore decides which servers the client is on (one world check for the engine and every +// plugin, with a per-character Auto / On / Off override) and what the engine and the installed +// plugins add for each (UI/ServerMenus.cs and UI/Sections in RynthCore). It sends that list as +// the "servermenu" remote command when it changes, and again every 30 s. Tab-separated lines: +// V id name active 0/1 force auto|on|off detected 0/1 every server (RynthCore 2026.10.5.46+) +// X id label every Mini Remote section, rail order (.46+) +// S id name active 0/1 force command a server with items +// I label command tooltip feature its items +// A "tab:" feature is one of RynthAi's own Mini Remote tabs (older RynthCore); "section:" +// opens that section in RynthCore's Mini Remote (its command does that). // // Groups stays null until the first push: an older RynthCore, or the ImGui shell off. The menu -// then falls back to RynthILT's own ILT entries (RynthILT.Hub section "server-menu"). +// then falls back to RynthILT's own ILT entries (RynthILT.Hub section "server-menu"). Servers stays +// empty until a RynthCore that sends V lines: the world check is then RynthILT's own. using System; using System.Collections.Generic; using System.Threading; @@ -20,27 +26,78 @@ internal sealed record ServerMenuEntry(string Label, string Command, string Tool /// One server's section: shown while (detected or forced in RynthCore). internal sealed record ServerMenuGroup(string Id, string Name, bool Active, string ForceCommand, ServerMenuEntry[] Items); +/// RynthCore's verdict for one server: active now, its saved override ("auto", "on", "off"), what detection said. +internal sealed record ServerVerdictLine(string Id, string Name, bool Active, string Force, bool Detected); + +/// One of RynthCore's Mini Remote sections. +internal sealed record SectionLine(string Id, string Label); + +/// Everything one push carries. +internal sealed record ServerMenuPayload(ServerMenuGroup[] Groups, ServerVerdictLine[] Servers, SectionLine[] Sections); + internal static class ServerMenuModel { /// Feature prefix for items that are Mini Remote tabs (drawn by RynthAi itself). public const string TabFeaturePrefix = "tab:"; + /// Feature prefix for items that open a section of RynthCore's Mini Remote. + public const string SectionFeaturePrefix = "section:"; + private static ServerMenuGroup[]? _groups; + private static ServerVerdictLine[] _servers = Array.Empty(); + private static SectionLine[] _sections = Array.Empty(); /// The latest sections from RynthCore; null until it sends any. Any thread. public static ServerMenuGroup[]? Groups => Volatile.Read(ref _groups); + /// The latest server verdicts (empty from a RynthCore older than 2026.10.5.46). Any thread. + public static ServerVerdictLine[] Servers => Volatile.Read(ref _servers); + + /// RynthCore's Mini Remote sections, rail order (empty from an older RynthCore). Any thread. + public static SectionLine[] Sections => Volatile.Read(ref _sections); + /// Pump thread: stores a "servermenu" push. A malformed line is skipped, never thrown. - public static void Apply(string payload) => Volatile.Write(ref _groups, Parse(payload)); + public static void Apply(string payload) + { + ServerMenuPayload p = ParsePayload(payload); + Volatile.Write(ref _servers, p.Servers); + Volatile.Write(ref _sections, p.Sections); + Volatile.Write(ref _groups, p.Groups); + } /// - /// Parses a payload. Items before the first section line, short lines and unknown line kinds - /// are skipped. + /// RynthCore's verdict for server : true / false once it sends V lines, + /// null before (an older RynthCore, or no push yet). Any thread. /// - public static ServerMenuGroup[] Parse(string? payload) + public static bool? ServerActive(string id) + { + foreach (ServerVerdictLine s in Servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s.Active; + return null; + } + + /// RynthCore's line for server , or null. + public static ServerVerdictLine? Server(string id) + { + foreach (ServerVerdictLine s in Servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + + /// + /// Parses a payload's server groups. Items before the first section line, short lines and + /// unknown line kinds are skipped. + /// + public static ServerMenuGroup[] Parse(string? payload) => ParsePayload(payload).Groups; + + /// Parses a whole payload (groups, server verdicts, sections). Never throws. + public static ServerMenuPayload ParsePayload(string? payload) { var groups = new List(); - if (string.IsNullOrEmpty(payload)) return groups.ToArray(); + var servers = new List(); + var sections = new List(); + if (string.IsNullOrEmpty(payload)) + return new ServerMenuPayload(groups.ToArray(), servers.ToArray(), sections.ToArray()); string id = "", name = "", force = ""; bool active = false, open = false; @@ -71,9 +128,17 @@ internal static class ServerMenuModel { items.Add(new ServerMenuEntry(f[1], f[2], f[3], f[4])); } + else if (f[0] == "V" && f.Length >= 6 && f[1].Length > 0) + { + servers.Add(new ServerVerdictLine(f[1], f[2].Length > 0 ? f[2] : f[1], f[3] == "1", f[4], f[5] == "1")); + } + else if (f[0] == "X" && f.Length >= 3 && f[1].Length > 0 && f[2].Length > 0) + { + sections.Add(new SectionLine(f[1], f[2])); + } } Close(); - return groups.ToArray(); + return new ServerMenuPayload(groups.ToArray(), servers.ToArray(), sections.ToArray()); } /// The tab id of a "tab:<id>" feature, else null. @@ -81,4 +146,10 @@ internal static class ServerMenuModel feature.StartsWith(TabFeaturePrefix, StringComparison.OrdinalIgnoreCase) && feature.Length > TabFeaturePrefix.Length ? feature.Substring(TabFeaturePrefix.Length) : null; + + /// The section id of a "section:<id>" feature, else null. + public static string? SectionOf(string feature) => + feature.StartsWith(SectionFeaturePrefix, StringComparison.OrdinalIgnoreCase) && feature.Length > SectionFeaturePrefix.Length + ? feature.Substring(SectionFeaturePrefix.Length) + : null; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfRatings.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfRatings.cs new file mode 100644 index 0000000..64e801e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfRatings.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +/// +/// The character's own ratings for Item Info's "select yourself" output. Pure: every value comes +/// in through a reader, so the tests format it without a client. +/// +/// Where the numbers come from (ACE / ACECustom, nothing server-specific): +/// * Totals (PropertyInt 307-316, 323, 331, 350, 351, 381, 382) are what the server resolves +/// into an identify of a creature (AppraiseInfo.AddRatings): base + gear + augmentations + +/// buffs, the same numbers the client's Ratings page shows. They arrive only with an identify, +/// so the plugin asks for one on itself first (they are AssessmentProperty, not SendOnLogin). +/// * Luminance augmentations (333-338, 341, 342) are SendOnLogin: always on the player. +/// Zero or absent ratings are left out (the server omits zeros too). Plain ASCII. +/// +internal static class SelfRatings +{ + /// One rating: the property id, the Item Info tag and a readable name. + internal readonly record struct Rating(uint Stype, string Tag, string Name); + + /// The combat totals, in Item Info's rating order (D, DR, C, CD, CR, CDR). + internal static readonly Rating[] Combat = + { + new(307, "D", "Damage"), + new(308, "DR", "Damage Resist"), + new(313, "C", "Crit"), + new(314, "CD", "Crit Damage"), + new(315, "CR", "Crit Resist"), + new(316, "CDR", "Crit Damage Resist"), + }; + + /// Healing and resistance totals. + internal static readonly Rating[] Other = + { + new(323, "HB", "Healing Boost"), + new(331, "NR", "Nether Resist"), + new(350, "DoTR", "DoT Resist"), + new(351, "LR", "Life Resist"), + }; + + /// PK totals (only non-zero on PK characters). + internal static readonly Rating[] Pk = + { + new(381, "PKD", "PK Damage"), + new(382, "PKDR", "PK Damage Resist"), + }; + + /// Luminance augmentation ratings (already part of the totals above). + internal static readonly Rating[] LumAugs = + { + new(333, "D", "Damage"), + new(334, "DR", "Damage Reduction"), + new(335, "CD", "Crit Damage"), + new(336, "CR", "Crit Reduction"), + new(337, "SE", "Surge Effect"), + new(338, "SC", "Surge Chance"), + new(341, "V", "Vitality"), + new(342, "HB", "Healing"), + }; + + /// + /// The output lines. returns a property's value (0 when absent); + /// is false when the self-identify didn't come back in time, so + /// the totals may be missing. joins everything Mag-style. + /// + public static List Build(string name, Func readInt, bool identified, bool oneLine) + { + var lines = new List(4); + + string combat = Join(Combat, readInt, plus: false); + string header = (string.IsNullOrWhiteSpace(name) ? "Your" : name.Trim() + "'s") + " ratings: " + + (combat.Length > 0 ? combat : "no combat ratings"); + if (!identified) header += " (not identified - totals may be incomplete)"; + lines.Add(header); + + string other = Join(Other, readInt, plus: false); + if (other.Length > 0) lines.Add(other); + + string pk = Join(Pk, readInt, plus: false); + if (pk.Length > 0) lines.Add("PK: " + pk); + + string lum = Join(LumAugs, readInt, plus: true); + if (lum.Length > 0) lines.Add("Lum augs (in the totals): " + lum); + + return oneLine ? new List { string.Join(" | ", lines) } : lines; + } + + /// "D 45, DR 30, ..." for the non-zero ratings in ; "" when none. + private static string Join(Rating[] set, Func readInt, bool plus) + { + var sb = new StringBuilder(); + foreach (Rating r in set) + { + int v = readInt(r.Stype); + if (v == 0) continue; + if (sb.Length > 0) sb.Append(", "); + sb.Append(r.Tag).Append(' '); + if (plus && v > 0) sb.Append('+'); + sb.Append(v.ToString(CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index ece73dd..ea0052e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -1,6 +1,7 @@ using System; using System.Numerics; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -90,12 +91,12 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); string status = _autoVendorStatus?.Invoke() ?? "Not logged in"; - ImGui.TextDisabled($"Status: {status}"); + SafeImGui.TextDisabled($"Status: {status}"); ImGui.Spacing(); ImGui.Checkbox("Enabled##AV", ref _settings.AutoVendorEnabled); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\n" + + SafeImGui.SetTooltip("Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\n" + "Profiles: .utl or default.utl in your character's AutoVendor\n" + "folder, the server folder, or " + Vendor.AutoVendorManager.MainProfileDir + "."); ImGui.Checkbox("Test Mode (only print what it would do)##AV", ref _settings.AutoVendorTestMode); @@ -139,12 +140,12 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); string status = _autoTradeStatus?.Invoke() ?? "Not logged in"; - ImGui.TextDisabled($"Status: {status}"); + SafeImGui.TextDisabled($"Status: {status}"); ImGui.Spacing(); ImGui.Checkbox("Enabled##AT", ref _settings.AutoTradeEnabled); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("When a trade window opens, add the items that match Keep / Keep # rules in\n" + + SafeImGui.SetTooltip("When a trade window opens, add the items that match Keep / Keep # rules in\n" + ".utl or default.utl (your character's AutoTrade folder, the\n" + "server folder, or " + Trade.AutoTradeManager.MainProfileDir + ")."); ImGui.Checkbox("Test Mode (only print what it would add)##AT", ref _settings.AutoTradeTestMode); @@ -208,13 +209,42 @@ internal sealed class LegacyAdvancedSettingsUi _settings.SetBuffEnabled(toggle.Buff, on); } + /// + /// One loot timer: the input, then "baseline" when it matches LootBaseline, or "baseline N" when + /// it doesn't (hover for what the timer does). + /// + private static void LootTimerInput(string label, ref int value, int baseline, string tip) + { + ImGui.SetNextItemWidth(120); + ImGui.InputInt(label, ref value); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip(tip); + ImGui.SameLine(); + if (value == baseline) + ImGui.TextDisabled("baseline"); + else + SafeImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1.0f), $"baseline {baseline}"); + } + + /// Writes the six loot timers' baseline values (LootBaseline.cs) into the settings. + private void ApplyLootBaseline() + { + LootBaseline.Timers b = LootBaseline.Values; + _settings.LootContentSettleMs = b.ContentSettleMs; + _settings.LootEmptyCorpseMs = b.EmptyCorpseMs; + _settings.LootAssessWindowMs = b.AssessWindowMs; + _settings.LootRetryTimeoutMs = b.RetryTimeoutMs; + _settings.LootOpenRetryMs = b.OpenRetryMs; + _settings.LootCorpseTimeoutMs = b.CorpseTimeoutMs; + } + private void RenderTabContent(int tabIndex) { if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length) return; string tabName = _settings.AdvancedTabs[tabIndex]; - ImGui.TextColored(new Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}"); + SafeImGui.TextColored(new Vector4(0.4f, 0.7f, 1.0f, 1.0f), $"Advanced Settings > {tabName}"); ImGui.Separator(); ImGui.Spacing(); @@ -409,28 +439,28 @@ internal sealed class LegacyAdvancedSettingsUi break; case "Recharge": - ImGui.Text("Self Vitals (%)"); + SafeImGui.Text("Self Vitals (%)"); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Heal At", ref _settings.HealAt, 0, 100); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Emergency Heal At", ref _settings.EmergencyHealAt, 0, 100); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("At or under this health %, a healing kit goes first out of Magic mode,\nand a kit or potion is used while a cast is pending. 0 = off."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("At or under this health %, a healing kit goes first out of Magic mode,\nand a kit or potion is used while a cast is pending. 0 = off."); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Stamina To Health At", ref _settings.StaminaToHealthAt, 0, 100); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("At or under this health %, cast Stamina to Health Self ahead of Heal At\n(after a kit out of Magic mode). 0 = never cast it."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("At or under this health %, cast Stamina to Health Self ahead of Heal At\n(after a kit out of Magic mode). 0 = never cast it."); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Stamina To Health Min Stamina", ref _settings.StaminaToHealthMinStamina, 0, 100); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Don't cast Stamina to Health unless stamina is over this %."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Don't cast Stamina to Health unless stamina is over this %."); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Re-stam To", ref _settings.RestamTo, 0, 100); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before."); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100); ImGui.Spacing(); - ImGui.Text("Top-Off Vitals (%)"); + SafeImGui.Text("Top-Off Vitals (%)"); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Top HP", ref _settings.TopOffHP, 0, 100); ImGui.SetNextItemWidth(120); @@ -439,7 +469,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SliderInt("Top Mana", ref _settings.TopOffMana, 0, 100); ImGui.Spacing(); - ImGui.Text("Helper Settings (%)"); + SafeImGui.Text("Helper Settings (%)"); ImGui.SetNextItemWidth(120); ImGui.SliderInt("Heal Others", ref _settings.HealOthersAt, 0, 100); ImGui.SetNextItemWidth(120); @@ -453,7 +483,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Separator(); ImGui.Checkbox("Use Recklessness", ref _settings.UseRecklessness); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("When enabled and Recklessness is trained, auto power uses 80% instead of 100%."); + SafeImGui.SetTooltip("When enabled and Recklessness is trained, auto power uses 80% instead of 100%."); ImGui.Spacing(); bool meleeAuto = _settings.MeleeAttackPower < 0; @@ -499,6 +529,26 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetNextItemWidth(120); ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length); + ImGui.Spacing(); + ImGui.Text("Weapon Swaps"); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("Wait After Target Switch (ms)", ref _settings.WeaponSwapSettleMs, 0, 3000); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("After switching from one live target to another, wait this long before a weapon\n" + + "swap starts, so a target that changes again doesn't cost a wasted swap.\n" + + "A new target after a kill swaps at once. 0 = never wait."); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("No Swap Under Target Health %", ref _settings.WeaponSwapMinHealthPct, 0, 100); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("A target at or under this health is finished with the weapon in hand\n" + + "(same kind of weapon only). A swap under way always completes. 0 = off."); + ImGui.SetNextItemWidth(150); + ImGui.SliderInt("Weakness Swap Min Gain %", ref _settings.WeaponSwapMinGainPct, 0, 200); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Auto (weakness) picks only: swap to another element only when it does at least this\n" + + "much more damage than the weapon in hand. A launcher swap with other ammo costs about 4 s.\n" + + "Damage tab, slayer and Monsters rule picks always swap. 0 = off."); + ImGui.Separator(); ImGui.Spacing(); ImGui.Checkbox("Use Native Attack", ref _settings.UseNativeAttack); @@ -689,7 +739,7 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Go To Closest Waypoint", ref _settings.NavResumeNearest); if (ImGui.IsItemHovered()) - ImGui.SetTooltip(NavResumeNearestTip); + SafeImGui.SetTooltip(NavResumeNearestTip); ImGui.Checkbox("Find A Way Back When Stuck", ref _settings.NavRecoveryEnabled); if (ImGui.IsItemHovered()) @@ -819,7 +869,7 @@ internal sealed class LegacyAdvancedSettingsUi "listed weapons."); string skipped = _buffSkips?.Invoke() ?? ""; if (_settings.SkipUnusableBuffs && skipped.Length > 0) - ImGui.TextWrapped("Skipping: " + skipped); + SafeImGui.TextWrapped("Skipping: " + skipped); ImGui.Spacing(); if (ImGui.Button("Force Buff##forceBuff") && _forceBuff != null) _forceBuff(); @@ -887,7 +937,7 @@ internal sealed class LegacyAdvancedSettingsUi case "Looting": ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting); ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority); - ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses); + // "Loot Only Rare Corpses" is hidden: nothing reads LootOnlyRareCorpses. ImGui.Checkbox("Learn Unknown Spells", ref _settings.ReadUnknownScrolls); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too."); @@ -934,22 +984,26 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Spacing(); ImGui.Separator(); ImGui.Text("Loot Timers (ms)"); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Inter-Item Delay", ref _settings.LootInterItemDelayMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Content Settle", ref _settings.LootContentSettleMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Closing Delay", ref _settings.LootClosingDelayMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Assess Window", ref _settings.LootAssessWindowMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Corpse Open Retry", ref _settings.LootOpenRetryMs); - ImGui.SetNextItemWidth(120); - ImGui.InputInt("Corpse Timeout", ref _settings.LootCorpseTimeoutMs); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The baseline is measured from live looting on ACE (2026-10-14). The log's\n[LootSettings] line lists each timer as baseline or custom."); + ImGui.SameLine(); + if (ImGui.SmallButton("Use Baseline##lootTimers")) + ApplyLootBaseline(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Set all six loot timers to the baseline."); + // Inter-Item Delay and Closing Delay are hidden: the corpse looting never reads them. + LootTimerInput("Content Settle", ref _settings.LootContentSettleMs, LootBaseline.ContentSettleMs, + "Wait after an open for the container's items. Only used when the items\naren't already known; on ACE they always were."); + LootTimerInput("Empty Corpse Wait", ref _settings.LootEmptyCorpseMs, LootBaseline.EmptyCorpseMs, + "Wait for a corpse's contents before probing it or calling it empty."); + LootTimerInput("Assess Window", ref _settings.LootAssessWindowMs, LootBaseline.AssessWindowMs, + "Hold items for their appraisal. Measured replies: 127 ms typical,\n256 ms at the 95th percentile, 350 ms at most."); + LootTimerInput("Loot Retry Timeout", ref _settings.LootRetryTimeoutMs, LootBaseline.RetryTimeoutMs, + "Wait, once the character is still, before resending a pickup that hasn't\nlanded. Too short resends pickups the server is still doing."); + LootTimerInput("Corpse Open Retry", ref _settings.LootOpenRetryMs, LootBaseline.OpenRetryMs, + "Wait before sending another open to a corpse that hasn't opened."); + LootTimerInput("Corpse Timeout", ref _settings.LootCorpseTimeoutMs, LootBaseline.CorpseTimeoutMs, + "Give up on a claimed corpse after this long. The clock stops during combat\nand buffing."); ImGui.Spacing(); ImGui.Separator(); @@ -995,10 +1049,10 @@ internal sealed class LegacyAdvancedSettingsUi : new Vector4(0.5f, 0.5f, 0.5f, 1.0f); ImGui.Text("State:"); ImGui.SameLine(); - ImGui.TextColored(stateColor, stateLabel); + SafeImGui.TextColored(stateColor, stateLabel); if (!string.IsNullOrEmpty(_missileCraftingManager.StatusMessage)) - ImGui.TextWrapped(_missileCraftingManager.StatusMessage); + SafeImGui.TextWrapped(_missileCraftingManager.StatusMessage); } break; @@ -1007,7 +1061,7 @@ internal sealed class LegacyAdvancedSettingsUi break; default: - ImGui.Text($"Settings for {tabName} are currently under development."); + SafeImGui.Text($"Settings for {tabName} are currently under development."); break; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 4326187..e2728dd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1056,6 +1056,9 @@ internal sealed partial class LegacyDashboardRenderer SummonPets = s.SummonPets, PetMinMonsters = s.PetMinMonsters, // Spell Combat + WeaponSwapSettleMs = s.WeaponSwapSettleMs, + WeaponSwapMinHealthPct = s.WeaponSwapMinHealthPct, + WeaponSwapMinGainPct = s.WeaponSwapMinGainPct, SpellCastIntervalMs = s.SpellCastIntervalMs, AttackSpellIntervalMs = s.AttackSpellIntervalMs, CastDispelSelf = s.CastDispelSelf, @@ -1292,6 +1295,9 @@ internal sealed partial class LegacyDashboardRenderer s.SummonPets = p.SummonPets; s.PetMinMonsters = p.PetMinMonsters; // Spell Combat + if (p.WeaponSwapSettleMs is int wsSettle) s.WeaponSwapSettleMs = Math.Clamp(wsSettle, 0, 3000); + if (p.WeaponSwapMinHealthPct is int wsHealth) s.WeaponSwapMinHealthPct = Math.Clamp(wsHealth, 0, 100); + if (p.WeaponSwapMinGainPct is int wsGain) s.WeaponSwapMinGainPct = Math.Clamp(wsGain, 0, 200); s.SpellCastIntervalMs = p.SpellCastIntervalMs; if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged s.CastDispelSelf = p.CastDispelSelf; @@ -1841,6 +1847,9 @@ internal sealed partial class LegacyDashboardRenderer dst.MeleeAttackPower = tmp.MeleeAttackPower; dst.MissileAttackPower = tmp.MissileAttackPower; dst.UseRecklessness = tmp.UseRecklessness; + dst.WeaponSwapSettleMs = Math.Clamp(tmp.WeaponSwapSettleMs, 0, 3000); + dst.WeaponSwapMinHealthPct = Math.Clamp(tmp.WeaponSwapMinHealthPct, 0, 100); + dst.WeaponSwapMinGainPct = Math.Clamp(tmp.WeaponSwapMinGainPct, 0, 200); dst.UseNativeAttack = tmp.UseNativeAttack; dst.WieldUnlistedWandWhenNoneListed = tmp.WieldUnlistedWandWhenNoneListed; dst.OffhandDefault = OffhandRules.SettingValue(OffhandRules.Parse(tmp.OffhandDefault, OffhandMode.Auto)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs index 958ee0d..c069e57 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs @@ -2,6 +2,7 @@ using System; using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -87,7 +88,7 @@ internal sealed class LegacyItemInfoUi if (string.IsNullOrEmpty(_previewText)) ImGui.TextDisabled("Select an item to preview its info line."); else - ImGui.TextWrapped(s.Prefix + _previewText); + SafeImGui.TextWrapped(s.Prefix + _previewText); ImGui.EndChild(); if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke(); @@ -155,7 +156,7 @@ internal sealed class LegacyItemInfoUi if (ImGui.Combo("Layout" + idSuffix, ref s.Layout, MagItemInfoCatalog.Layouts, MagItemInfoCatalog.Layouts.Length)) s.Sanitize(); if (ImGui.IsItemHovered()) - ImGui.SetTooltip( + SafeImGui.SetTooltip( "Pet-style lines (like the Mini Remote's Pets roster):\n" + " 1 Name (type mastery), set, AL, tinks, applied, craft\n" + " 2 imbues, slayer, damage, variance, %a / %md / %mc\n" + @@ -191,7 +192,7 @@ internal sealed class LegacyItemInfoUi if (ImGui.Checkbox($"{f.Label}##iiF{(int)f.Field}", ref shown)) s.SetHidden(f.Field, !shown); ImGui.TableNextColumn(); - ImGui.TextColored(ExampleColor, f.Example); + SafeImGui.TextColored(ExampleColor, f.Example); } ImGui.TableNextRow(); ImGui.TableNextColumn(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs index a30f278..7a30287 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -6,6 +6,7 @@ using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.Meta; using RynthCore.Install; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -140,7 +141,7 @@ internal sealed class LegacyMetaUi if (!string.IsNullOrEmpty(_sourceApplyMessage) && (DateTime.Now - _sourceApplyTime).TotalSeconds < 4) { - ImGui.TextColored(new Vector4(0, 1, 0.4f, 1f), _sourceApplyMessage); + SafeImGui.TextColored(new Vector4(0, 1, 0.4f, 1f), _sourceApplyMessage); ImGui.SameLine(); } @@ -345,7 +346,7 @@ internal sealed class LegacyMetaUi : rule.Children; int childCount = actionList?.Count ?? 0; bool expanded = _expandedRuleIndices.Contains(globalIdx); - ImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions] (right-click to expand)"); + SafeImGui.TextColored(new Vector4(1, 1, 0, 1), $"All: [{childCount} actions] (right-click to expand)"); if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ToggleExpand(); @@ -356,7 +357,7 @@ internal sealed class LegacyMetaUi var child = actionList[ai]; string childText = child.Action.ToString() + (string.IsNullOrEmpty(child.ActionData) ? "" : $": {child.ActionData}"); - ImGui.TextDisabled($" {ai + 1}. {childText}"); + SafeImGui.TextDisabled($" {ai + 1}. {childText}"); if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ToggleExpand(); } @@ -366,13 +367,13 @@ internal sealed class LegacyMetaUi !string.IsNullOrEmpty(rule.ActionData) && rule.ActionData.Contains(';')) { var parts = rule.ActionData.Split(';'); - ImGui.Text($"EmbeddedNavRoute: {parts[0]} ({parts[1]} pts)"); + SafeImGui.Text($"EmbeddedNavRoute: {parts[0]} ({parts[1]} pts)"); if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ToggleExpand(); } else { - ImGui.Text(rule.Action.ToString() + + SafeImGui.Text(rule.Action.ToString() + (string.IsNullOrEmpty(rule.ActionData) ? "" : $": {rule.ActionData}")); if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) ToggleExpand(); @@ -557,7 +558,7 @@ internal sealed class LegacyMetaUi ImGui.SameLine(); } - ImGui.TextColored(new Vector4(1, 1, 0, 1), $"{rule.Condition} Sub-Conditions"); + SafeImGui.TextColored(new Vector4(1, 1, 0, 1), $"{rule.Condition} Sub-Conditions"); ImGui.Indent(15f); for (int i = 0; i < rule.Children.Count; i++) @@ -641,7 +642,7 @@ internal sealed class LegacyMetaUi if (!string.IsNullOrEmpty(sName)) { ImGui.SameLine(); - ImGui.TextColored(new Vector4(0, 1, 1, 1), $"({sName})"); + SafeImGui.TextColored(new Vector4(0, 1, 1, 1), $"({sName})"); } } @@ -1078,7 +1079,7 @@ internal sealed class LegacyMetaUi // Status message if (!string.IsNullOrEmpty(_statusMessage) && (DateTime.Now - _statusTime).TotalSeconds < 5) - ImGui.TextColored(new Vector4(0, 1, 0, 1), _statusMessage); + SafeImGui.TextColored(new Vector4(0, 1, 0, 1), _statusMessage); // Save popup if (_openSavePopup) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs index 507ff6f..3b30005 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs @@ -35,14 +35,14 @@ internal sealed class LegacyNavigationUi } string activeNavName = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None (Unsaved)" : Path.GetFileName(_settings.CurrentNavPath); - ImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}"); + SafeImGui.TextColored(new Vector4(1, 1, 0, 1), $"Active Nav: {activeNavName}"); if (!string.IsNullOrEmpty(_settings.NavStatusLine)) { var statusColor = _settings.NavIsStuck ? new Vector4(0.91f, 0.70f, 0.20f, 1.00f) // amber : new Vector4(0.25f, 0.85f, 0.45f, 1.00f); // green - ImGui.TextColored(statusColor, _settings.NavStatusLine); + SafeImGui.TextColored(statusColor, _settings.NavStatusLine); } ImGui.Spacing(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacySpellsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacySpellsUi.cs index 155eefd..6ced88f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacySpellsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacySpellsUi.cs @@ -13,6 +13,7 @@ using System.IO; using System.Numerics; using System.Threading; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -80,8 +81,18 @@ internal sealed unsafe class LegacySpellsUi _refreshProfileList = refreshProfileList; } - /// True while the window is open (the plugin only feeds it data then). - public bool Visible => _settings.ShowSpellsWindow; + /// How long after its last embedded frame the body still counts as on screen. + private const long EmbeddedVisibleMs = 1500; + + /// When RynthCore's Spells section last drew the body (TickCount64); render thread writes. + private long _embeddedDrawnAt = long.MinValue / 2; + + /// + /// True while the window is open or RynthCore's Spells section shows the body (the plugin only + /// feeds it data then). Any thread. + /// + public bool Visible => _settings.ShowSpellsWindow + || Environment.TickCount64 - Interlocked.Read(ref _embeddedDrawnAt) < EmbeddedVisibleMs; // ── Pump-thread side ──────────────────────────────────────────────────── @@ -115,36 +126,55 @@ internal sealed unsafe class LegacySpellsUi if (ImGui.Begin(WindowTitle, ref _settings.ShowSpellsWindow)) { UiPlacement.RescueOncePerShow(ref _rescueChecked); - ApplyBuiltInList(); - - if (!SpellCatalog.IsLoaded) - { - ImGui.TextDisabled("The spell catalog is not loaded yet (it loads at login; see chat for errors)."); - } - else - { - EnsureEffectItems(); - float avail = ImGui.GetContentRegionAvail().X; - float leftW = MathF.Max(460f, avail * 0.58f); - - if (ImGui.BeginChild("##spcatalog", new Vector2(leftW, 0), ImGuiChildFlags.Borders | ImGuiChildFlags.ResizeX)) - { - RenderFilters(); - RenderCatalogTable(); - } - ImGui.EndChild(); - - ImGui.SameLine(); - if (ImGui.BeginChild("##spprofile", Vector2.Zero, ImGuiChildFlags.Borders)) - RenderProfileEditor(); - ImGui.EndChild(); - } - - RenderConfirmPopup(); + RenderBody(); } ImGui.End(); } + /// + /// RynthCore's Spells section (RynthPluginRenderEmbed "section:spells"): the window's body + /// drawn into the engine's current window. Render thread. + /// + public void RenderEmbedded() + { + long now = Environment.TickCount64; + // First frame after a gap: the same refresh as the window's open. + if (now - Interlocked.Read(ref _embeddedDrawnAt) >= EmbeddedVisibleMs && !_settings.ShowSpellsWindow) OnShown(); + Interlocked.Exchange(ref _embeddedDrawnAt, now); + RenderBody(); + } + + /// The catalog (left, resizable) and the profile editor (right), in the current window. + private void RenderBody() + { + ApplyBuiltInList(); + + if (!SpellCatalog.IsLoaded) + { + ImGui.TextDisabled("The spell catalog is not loaded yet (it loads at login; see chat for errors)."); + } + else + { + EnsureEffectItems(); + float avail = ImGui.GetContentRegionAvail().X; + float leftW = MathF.Max(460f, avail * 0.58f); + + if (ImGui.BeginChild("##spcatalog", new Vector2(leftW, 0), ImGuiChildFlags.Borders | ImGuiChildFlags.ResizeX)) + { + RenderFilters(); + RenderCatalogTable(); + } + ImGui.EndChild(); + + ImGui.SameLine(); + if (ImGui.BeginChild("##spprofile", Vector2.Zero, ImGuiChildFlags.Borders)) + RenderProfileEditor(); + ImGui.EndChild(); + } + + RenderConfirmPopup(); + } + /// Each time the window opens: refresh the file list and open the active profile. private void OnShown() { @@ -187,7 +217,7 @@ internal sealed unsafe class LegacySpellsUi bool knownReady = Volatile.Read(ref _known) != null; if (ImGui.Checkbox("Known only##spknown", ref _knownOnly)) _rowsDirty = true; if (ImGui.IsItemHovered()) - ImGui.SetTooltip(knownReady + SafeImGui.SetTooltip(knownReady ? "Only spells in your spellbook." : "Waiting for your spellbook (it is read a few seconds after login)."); @@ -225,7 +255,7 @@ internal sealed unsafe class LegacySpellsUi private void RenderCatalogTable() { RebuildRowsIfNeeded(); - ImGui.TextDisabled($"{_rows.Count} of {SpellCatalog.All.Count} spells. Click a header to sort, Shift+click for a second sort. + or double-click adds a buff."); + SafeImGui.TextDisabled($"{_rows.Count} of {SpellCatalog.All.Count} spells. Click a header to sort, Shift+click for a second sort. + or double-click adds a buff."); const ImGuiTableFlags flags = ImGuiTableFlags.Sortable | ImGuiTableFlags.SortMulti | ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable @@ -275,7 +305,7 @@ internal sealed unsafe class LegacySpellsUi else if (inProfile) ImGui.TextColored(GoodColor, "*"); else if (ImGui.SmallButton("+")) AddSpell(e); if (ImGui.IsItemHovered()) - ImGui.SetTooltip(!e.IsBuff ? "Only buffs can go in a buff profile." + SafeImGui.SetTooltip(!e.IsBuff ? "Only buffs can go in a buff profile." : inProfile ? $"Already in the profile (as {key})." : $"Add to the profile (buffing casts {key})."); ImGui.TableSetColumnIndex((int)Col.Name); @@ -468,7 +498,7 @@ internal sealed unsafe class LegacySpellsUi // Which list buffing uses. if (editIsActive) { - ImGui.TextColored(GoodColor, _dirty ? "Buffing uses this profile (save to apply edits)." : "Buffing uses this profile."); + SafeImGui.TextColored(GoodColor, _dirty ? "Buffing uses this profile (save to apply edits)." : "Buffing uses this profile."); } else if (ImGui.Button("Use for buffing##spuse")) { @@ -499,7 +529,7 @@ internal sealed unsafe class LegacySpellsUi ImGui.SameLine(); int enabled = 0; foreach (var en in _edit.Entries) if (en.Enabled) enabled++; - ImGui.TextDisabled($"{enabled} of {_edit.Entries.Count} on"); + SafeImGui.TextDisabled($"{enabled} of {_edit.Entries.Count} on"); float notesH = ImGui.GetTextLineHeightWithSpacing() * 3.2f; float statusH = ImGui.GetTextLineHeightWithSpacing() * 1.4f; @@ -515,8 +545,8 @@ internal sealed unsafe class LegacySpellsUi if (_status.Length > 0) { - if (_statusIsWarning) ImGui.TextColored(WarnColor, _status); - else ImGui.TextDisabled(_status); + if (_statusIsWarning) SafeImGui.TextColored(WarnColor, _status); + else SafeImGui.TextDisabled(_status); } } @@ -555,12 +585,12 @@ internal sealed unsafe class LegacySpellsUi ImGui.TableSetColumnIndex(1); if (entry.Enabled) ImGui.TextUnformatted(entry.Name); - else ImGui.TextDisabled(entry.Name); + else SafeImGui.TextDisabled(entry.Name); var spell = entry.SpellId != 0 ? SpellCatalog.Get(entry.SpellId) : null; if (spell != null && ImGui.IsItemHovered()) SpellTooltip(spell, entry.Key); ImGui.TableSetColumnIndex(2); - ImGui.TextDisabled(entry.Key); + SafeImGui.TextDisabled(entry.Key); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Buffing casts the highest level of this spell you know."); ImGui.TableSetColumnIndex(3); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index b86c7c2..5cdaa81 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -113,14 +113,19 @@ public sealed class LegacyUiSettings public bool EnableMissileCrafting = true; public int MissileCraftAmmoThreshold = 1000; + /// Not read by the corpse looting (pickups are paced by the server's confirmations); + /// kept so saved profiles round-trip. Hidden in Advanced Settings. public int LootInterItemDelayMs = 50; - public int LootContentSettleMs = 100; - public int LootEmptyCorpseMs = 300; + // Loot timer defaults are the measured baseline (LootBaseline.cs). + public int LootContentSettleMs = LootBaseline.ContentSettleMs; + public int LootEmptyCorpseMs = LootBaseline.EmptyCorpseMs; + /// Not read by the corpse looting (a close is timed by the deferred-close logic); kept + /// so saved profiles round-trip. Hidden in Advanced Settings. public int LootClosingDelayMs = 200; - public int LootAssessWindowMs = 200; - public int LootRetryTimeoutMs = 500; - public int LootOpenRetryMs = 1500; - public int LootCorpseTimeoutMs = 12000; + public int LootAssessWindowMs = LootBaseline.AssessWindowMs; + public int LootRetryTimeoutMs = LootBaseline.RetryTimeoutMs; + public int LootOpenRetryMs = LootBaseline.OpenRetryMs; + public int LootCorpseTimeoutMs = LootBaseline.CorpseTimeoutMs; public bool LootJumpEnabled = false; public int LootJumpHeight = 10; // 0–100; maps to 0.0–1.0 JumpNonAutonomous extent @@ -271,6 +276,8 @@ public sealed class LegacyUiSettings /// on the way as usual, recover the corpse, then carry on. Off by default. /// public bool TravelToOwnCorpse; + /// Not read by the corpse looting (no rare-corpse check exists); kept so saved profiles + /// round-trip. Hidden in Advanced Settings. The meta/MagTools option of that name sets Mine Only. public bool LootOnlyRareCorpses; /// Also pick up loose ground items that match the loot profile, within the corpse max range. public bool EnableGroundLoot; @@ -473,6 +480,18 @@ public sealed class LegacyUiSettings /// Auto: dual wield rather than a shield when the Dual Wield skill is trained and a /// second one-handed melee weapon is listed. Off by default (the shield). public bool PreferDualWield; + /// + /// Weapon swaps (CombatManager.SwapDeferReason). A switch from one live target to another + /// waits this long (ms) before a swap starts, so a target that changes again doesn't cost a + /// wasted swap. A lock after a kill or drop swaps at once. 0 = never wait. + /// + public int WeaponSwapSettleMs = 750; + /// No new swap (same kind) onto a target at or under this health %: finish it with + /// the weapon in hand. 0 = off. + public int WeaponSwapMinHealthPct = 25; + /// A weakness pick (Auto) swaps only for at least this % more damage than the weapon + /// in hand (WeaponPlanner.KeepInHand). Damage tab, slayer and Monsters rule picks always swap. 0 = off. + public int WeaponSwapMinGainPct = 20; public int MeleeAttackHeight = 1; public int MissileAttackHeight = 1; @@ -1028,6 +1047,11 @@ public sealed class SettingsBridgePayload public bool SummonPets { get; set; } public int PetMinMonsters { get; set; } + // Weapon swaps (only when the sender includes them). + public int? WeaponSwapSettleMs { get; set; } + public int? WeaponSwapMinHealthPct { get; set; } + public int? WeaponSwapMinGainPct { get; set; } + // Spell Combat public int SpellCastIntervalMs { get; set; } // Nullable since 0 became a real value (2026-10-08): a file without it keeps the default. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs index c905f5e..19d46ae 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPickup.cs @@ -27,8 +27,9 @@ internal enum LootPickupResult /// internal static class LootPickup { + /// : destinations the server refused lately (). public static LootPickupResult Send(RynthCoreHost host, WorldObjectCache? cache, uint itemId, uint playerId, - out uint destination) + out uint destination, System.Func? skip = null) { destination = 0; if (itemId == 0) return LootPickupResult.Failed; @@ -39,7 +40,7 @@ internal static class LootPickup int pid = unchecked((int)playerId); int dest = cache == null ? pid - : WorldObjectCache.FindLootDestination(cache.GetDirectInventory(forceRefresh: false), pid, host); + : WorldObjectCache.FindLootDestination(cache.GetDirectInventory(forceRefresh: false), pid, host, skip); if (dest == 0) return LootPickupResult.NoRoom; destination = unchecked((uint)dest); return host.MoveItemExternal(itemId, destination, 0) ? LootPickupResult.Moved : LootPickupResult.Failed; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs new file mode 100644 index 0000000..f17c472 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/PackRefusals.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// Packs the server would not take loot into. The destination comes from the client's own +/// item counts, and a side pack whose contents the client never loaded counts as nearly empty +/// however full it is: every item went to that one pack, the server refused all 3 tries each +/// time, and every item on every corpse was skipped (Drakkon, 2026-10-15, 62 items in a row). +/// A pack that takes none of an item's tries counts as full for ; the +/// destination search skips it, so the next pack is tried. Pure: the caller passes the time. +/// +internal sealed class PackRefusals +{ + /// How long a refusing pack is left out (time to free some room, or open it). + public const long HoldMs = 5 * 60_000; + + private readonly Dictionary _until = new(); + + /// The server took none of the tries into . + public void Refuse(int packId, long nowMs) + { + if (packId != 0) _until[packId] = nowMs + HoldMs; + } + + /// True while is left out. + public bool IsRefused(int packId, long nowMs) + { + if (!_until.TryGetValue(packId, out long until)) return false; + if (nowMs < until) return true; + _until.Remove(packId); + return false; + } + + /// An item landed in : it has room after all. + public void Accepted(int packId) => _until.Remove(packId); + + public void Clear() => _until.Clear(); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LootBaseline.cs b/Plugins/RynthCore.Plugin.RynthAi/LootBaseline.cs new file mode 100644 index 0000000..9c1a885 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LootBaseline.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// The baseline loot timers: what the Loot Timers in Advanced Settings should be unless a server or +/// connection needs otherwise. Measured from live corpse looting on ACE (Silentkelpie on +/// InfiniteLeaftide, 2026-10-14 12:38-13:53: 226 corpses opened, 39 pickups): +/// +/// Every open found its items already in the object cache, so Content Settle and Empty Corpse +/// Wait were never waited on. +/// Appraisals (ID replies) for a corpse arrived 127 ms after the request at the median, 256 ms +/// at the 95th percentile, 350 ms at most. +/// No pickup needed a retry with a 1000 ms Loot Retry Timeout (it counts from when the +/// character stops animating); every pickup was confirmed 1.7-2.2 s after the send. +/// No corpse reached the 12 s Corpse Timeout, and 199 of 203 corpses opened on the first try. +/// +/// Dependency-free so the RynthAi tests compile it directly. +/// +internal static class LootBaseline +{ + /// Wait after an open for the client to fill the container (used only when the cache is empty). + public const int ContentSettleMs = 100; + /// Wait for the container's contents before probing it, and before calling a corpse empty. + public const int EmptyCorpseMs = 300; + /// Hold items for their appraisal; above the 256 ms 95th percentile of the measured replies. + public const int AssessWindowMs = 300; + /// Wait, once the character is still, before resending a pickup that hasn't landed. + public const int RetryTimeoutMs = 1000; + /// Wait before sending another open to a corpse that hasn't opened. + public const int OpenRetryMs = 1500; + /// Give up on a claimed corpse after this long (the clock stops during combat and buff holds). + public const int CorpseTimeoutMs = 12000; + + /// The six loot timers that the corpse looting reads. + public readonly record struct Timers( + int ContentSettleMs, int EmptyCorpseMs, int AssessWindowMs, + int RetryTimeoutMs, int OpenRetryMs, int CorpseTimeoutMs); + + /// The baseline as a set of timers (what "Use Baseline" writes into the settings). + public static Timers Values => new(ContentSettleMs, EmptyCorpseMs, AssessWindowMs, + RetryTimeoutMs, OpenRetryMs, CorpseTimeoutMs); + + /// + /// One timer compared with its baseline. is the lowest value the loot + /// code honours; a setting below it behaves as the floor. + /// + public readonly record struct Entry(string Label, int Value, int Baseline, int FloorMs) + { + public bool IsBaseline => Value == Baseline; + public bool BelowFloor => Value < FloorMs; + } + + /// + /// The timers next to their baselines, in the order the Advanced Settings show them. The floors + /// are the Math.Max minimums in CorpseOpenController (Empty Corpse Wait is floored at 200 ms for + /// the empty check and at 300 ms for the contents wait; the lower one is reported). + /// + public static IReadOnlyList Compare(Timers t) => new[] + { + new Entry("Content Settle", t.ContentSettleMs, ContentSettleMs, 50), + new Entry("Empty Corpse Wait", t.EmptyCorpseMs, EmptyCorpseMs, 200), + new Entry("Assess Window", t.AssessWindowMs, AssessWindowMs, 100), + new Entry("Loot Retry Timeout", t.RetryTimeoutMs, RetryTimeoutMs, 150), + new Entry("Corpse Open Retry", t.OpenRetryMs, OpenRetryMs, 500), + new Entry("Corpse Timeout", t.CorpseTimeoutMs, CorpseTimeoutMs, 2000), + }; + + /// + /// The log line for a character's loot timers: each one marked "baseline" or "custom (baseline N)", + /// plus a count, and a note when the approach range's Min is above its Max (Min is then used as Max). + /// Ranges are in yards as stored in the settings. + /// + public static string Describe(Timers t, double approachMaxYards, double approachMinYards) + { + IReadOnlyList entries = Compare(t); + var sb = new StringBuilder("[LootSettings] "); + int custom = 0; + for (int i = 0; i < entries.Count; i++) + { + Entry e = entries[i]; + if (i > 0) sb.Append(" | "); + sb.Append(e.Label).Append(' ').Append(e.Value).Append(" ms "); + if (e.IsBaseline) + { + sb.Append("baseline"); + } + else + { + custom++; + sb.Append("custom (baseline ").Append(e.Baseline).Append(')'); + } + if (e.BelowFloor) + sb.Append(" [acts as ").Append(e.FloorMs).Append(']'); + } + sb.Append(custom == 0 ? " -- all baseline" : $" -- {custom} of {entries.Count} custom"); + double max = RangeYards(approachMaxYards, 10.0), min = RangeYards(approachMinYards, 2.0); + if (min > max) + sb.Append($" | Approach Range Min {min:0.#} yd is above Max {max:0.#} yd, so Min acts as {max:0.#} yd"); + return sb.ToString(); + } + + /// + /// A stored approach range in yards, read the way CorpseOpenController.NormalizeCorpseRangeYards + /// reads it: unset falls back, and a value of 1 or less is a legacy fraction of 240 yards. + /// + private static double RangeYards(double value, double fallbackYards) + { + if (double.IsNaN(value) || double.IsInfinity(value) || value <= 0.0) + return fallbackYards; + return value <= 1.0 ? value * 240.0 : value; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index e4003ec..6782695 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -99,6 +99,8 @@ internal sealed class ExpressionEngine = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _giveNativeProfileCache = new(StringComparer.OrdinalIgnoreCase); + // actiontrygiveprofile arguments already logged as refused (the meta retries every pulse). + private readonly HashSet _giveProfileRefused = new(StringComparer.OrdinalIgnoreCase); // The three data paths are settable only so offline tests can point them at a scratch // folder before anything reads or writes them; the plugin never changes them. internal static string ItemGiverDir { get; set; } @@ -3017,24 +3019,27 @@ internal sealed class ExpressionEngine // The item disappearing from GetInventory() is the confirmation it was accepted. if (_worldObjectCache == null || string.IsNullOrEmpty(profileArg) || string.IsNullOrEmpty(targetNameArg)) return "0"; + // An NPC ignores MoveItemExternal (move-to-container): only AC's give action reaches one. + if (!_host.HasGiveObjectTo) return "0"; - // Resolve profile path — bare name → ItemGiverDir. - // .utl extension added automatically if no extension and not .json. - string profilePath = Path.IsPathRooted(profileArg) - ? profileArg - : Path.Combine(ItemGiverDir, profileArg); - + // The profile stays inside ItemGiverDir: a shared meta can't point the give at another file. + string? profilePath = ResolveGiveProfilePath(profileArg, ItemGiverDir); + if (profilePath == null) + { + if (_giveProfileRefused.Add(profileArg)) // once per argument, not every pulse + _host.Log($"[RynthAi] actiontrygiveprofile: refused profile '{profileArg}' (only files inside ItemGiver\\)."); + return "0"; + } bool isJson = profilePath.EndsWith(".json", StringComparison.OrdinalIgnoreCase); - if (!isJson && !profilePath.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) - profilePath += ".utl"; if (!File.Exists(profilePath)) return "0"; - // Find target by exact name (case-insensitive) among landscape objects + // Target: an NPC or vendor with that exact name (case-insensitive). Never a player, so a + // shared meta can't hand the inventory to someone's character; /ra ig gives to players. uint targetId = 0; foreach (var wo in _worldObjectCache.GetLandscape()) { - if (string.Equals(wo.Name, targetNameArg, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(wo.Name, targetNameArg, StringComparison.OrdinalIgnoreCase) && IsGiveProfileTarget(wo)) { targetId = (uint)wo.Id; break; @@ -3067,8 +3072,7 @@ internal sealed class ExpressionEngine { var (action, _) = RynthCore.Plugin.RynthAi.Loot.LootEvaluator.Classify(nativeProfile, wo, null); if (action != RynthCore.Loot.LootAction.Keep) continue; - int amount = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)); - _host.MoveItemExternal((uint)wo.Id, targetId, amount); + _host.GiveObjectTo((uint)wo.Id, targetId, 0); return "1"; } } @@ -3095,8 +3099,7 @@ internal sealed class ExpressionEngine if (VTankLootEvaluator.Match(rule, wo, lootCtx)) { match = rule; break; } if (match == null || match.Action != VTankLootAction.Keep) continue; - int amount = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)); - _host.MoveItemExternal((uint)wo.Id, targetId, amount); + _host.GiveObjectTo((uint)wo.Id, targetId, 0); return "1"; } } @@ -3104,6 +3107,45 @@ internal sealed class ExpressionEngine return "0"; // No matching items remain } + /// An NPC or a vendor (weenie bitfield first, as the meta's ObjectClass): a player never is. + private bool IsGiveProfileTarget(WorldObject wo) + { + int cls = ResolveEffectiveObjectClass(wo); + return cls == (int)AcObjectClass.Npc || cls == (int)AcObjectClass.Vendor; + } + + /// + /// actiontrygiveprofile's profile file: relative to + /// , ".utl" added unless it ends in .utl or .json. Null when the + /// argument is rooted (C:\..., \\server\..., \x, C:x), names an alternate stream (':'), or + /// leaves ("..\"). + /// + internal static string? ResolveGiveProfilePath(string profileArg, string baseDir) + { + string arg = profileArg.Trim(); + if (arg.Length == 0 || string.IsNullOrWhiteSpace(baseDir) || arg.IndexOf(':') >= 0 || Path.IsPathRooted(arg)) + return null; + + string root; + string full; + try + { + root = Path.GetFullPath(baseDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + full = Path.GetFullPath(Path.Combine(root, arg)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return null; + } + if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase) || full.Length == root.Length) + return null; + + if (!full.EndsWith(".json", StringComparison.OrdinalIgnoreCase) && !full.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) + full += ".utl"; + return full; + } + private string EvalGetCombatState() { if (!_host.HasGetCurrentCombatMode) return "Peace"; @@ -3587,6 +3629,9 @@ internal sealed class ExpressionEngine ["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0), ["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0), ["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0), + ["WeaponSwapSettleMs"] = (() => I(s.WeaponSwapSettleMs), v => { if (int.TryParse(v, out int i)) s.WeaponSwapSettleMs = Math.Clamp(i, 0, 3000); }), + ["WeaponSwapMinHealthPct"] = (() => I(s.WeaponSwapMinHealthPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinHealthPct = Math.Clamp(i, 0, 100); }), + ["WeaponSwapMinGainPct"] = (() => I(s.WeaponSwapMinGainPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinGainPct = Math.Clamp(i, 0, 200); }), ["UseNativeAttack"] = (() => B(s.UseNativeAttack), v => s.UseNativeAttack = ToDouble(v) != 0), ["WieldUnlistedWandWhenNoneListed"] = (() => B(s.WieldUnlistedWandWhenNoneListed), v => s.WieldUnlistedWandWhenNoneListed = ToDouble(v) != 0), // The off hand when a monster rule doesn't choose: Auto, Shield, Weapon or None (or 0-3). diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerCatalog.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerCatalog.cs new file mode 100644 index 0000000..cd9cbc4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerCatalog.cs @@ -0,0 +1,348 @@ +// TinkerCatalog.cs - The salvage each Crafting tinker tab can apply. +// +// Retail: ACE's stock tinkering (RecipeManager Tinkering_ModifyItem): armor protections and +// imbues, weapon tinks and imbues, caster tinks, jewelry cantrip gems, item value / burden / +// mana / retain. Every retail tinker (imbues too) uses one of the item's 10 tinker slots and the +// success chance follows RecipeManager.GetTinkerChance (TinkerMath). +// +// Server: the connected server's own recipes come from the plugin that owns it (its +// "RynthServer.Profile" JSON's "salvage" list, read by FromServerPlugin): a server plugin, or +// RynthILT for Infinite Leaftide. Nothing server-specific lives here. Their chances are the +// server's: the Crafting runner relies on the confirmation's percent. +// The player adds their own rows per world (CraftingTabState.CustomByWorld). +using System; +using System.Collections.Generic; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting; + +/// A Crafting tinker tab. +internal enum TinkerBench +{ + Armor, + Melee, + Missile, + Caster, + Jewelry, + Items, + /// Trinkets (compass, goggles, scarab...): server salvage, often tier-prepared. + Trinkets, +} + +/// Where a material's recipe comes from. +internal enum TinkerOrigin +{ + /// Stock ACE (retail) tinkering. + Retail, + /// A row the player added for this server. + Custom, + /// A row the server's own plugin defines (its profile's "salvage" list, ServerPackInfo.Salvage). + Plugin, +} + +/// How often a material can go on one item. +internal enum TinkerKind +{ + /// Repeatable stat tink (count = how many times). + Tink, + /// One imbue per item (ImbuedEffect): a second imbue of any kind is refused. + Imbue, + /// One application (retain, heritage, a server's flag recipes...). + Once, +} + +/// One salvage a tab can apply. +/// MaterialType (131); = the weapon's damage-type rend. +/// Counts toward the 10-tink cap. +/// An int property of the item: the material is on it when it reads 2 (0 = none). +/// The bag must have this in its name (server bags that share a material id). +/// Apply order (lower first). +/// The bag must first be prepared on tier Ammunition: its name then carries the tier. +/// Goes on last, and only once the item's tink slots are full. +/// Rows with the same group share per item ("" = none). +/// The group's combined cap per item. +internal sealed record TinkerMaterial( + int Id, string Name, TinkerOrigin Origin, TinkerKind Kind, string Effect, int Order, + bool UsesTinkSlot = true, int AppliedInt = 0, string NameMatch = "", int Skill = 0, bool Prepared = false, + bool AfterCap = false, string StackGroup = "", int StackCap = 0); + +internal static class TinkerCatalog +{ + /// Pseudo material: the rend gem that matches the weapon's damage type. + public const int RendId = -1; + + // Tinkering skills (Skill enum). + public const int SkillItem = 18; + public const int SkillWeapon = 28; + public const int SkillArmor = 29; + public const int SkillMagicItem = 30; + + // Material ids used by the rules below (MaterialType). + public const int Ceramic = 1, Porcelain = 2, Linen = 4, Satin = 5, Silk = 6, Velvet = 7, Wool = 8; + public const int Agate = 10, Aquamarine = 13, Azurite = 14, BlackGarnet = 15, BlackOpal = 16, Bloodstone = 17, + Carnelian = 18, Citrine = 19, Emerald = 21, FireOpal = 22, GreenGarnet = 23, GreenJade = 24, Hematite = 25, + ImperialTopaz = 26, Jet = 27, LapisLazuli = 28, LavenderJade = 29, Malachite = 30, Moonstone = 31, Onyx = 32, + Opal = 33, Peridot = 34, RedGarnet = 35, RedJade = 36, RoseQuartz = 37, SmokeyQuartz = 40, Sunstone = 41, + TigerEye = 42, Tourmaline = 43, Turquoise = 44, WhiteJade = 45, WhiteQuartz = 46, WhiteSapphire = 47, + YellowGarnet = 48, YellowTopaz = 49, Zircon = 50; + public const int Ivory = 51, Leather = 52, Armoredillo = 53, Reedshark = 55, Brass = 57, Bronze = 58, Copper = 59, + Gold = 60, Iron = 61, Silver = 63, Steel = 64, Alabaster = 66, Granite = 67, Marble = 68, Sandstone = 70, + Serpentine = 71, Ebony = 73, Mahogany = 74, Oak = 75, Pine = 76, Teak = 77; + + public const int Diamond = 20, Ruby = 38, GromnieHide = 54, Pyreal = 62; + + /// Prepared salvage tiers: the word in the Ammunition's and the prepared bag's name. + public static readonly string[] TrinketTiers = { "Minor", "Moderate", "Major" }; + + /// The ordinary tinker slots on an item. + public const int MaxTinks = 10; + + private static readonly Dictionary Retail = new() + { + [TinkerBench.Armor] = new TinkerMaterial[] + { + new(Peridot, "Peridot", TinkerOrigin.Retail, TinkerKind.Imbue, "Melee defense imbue", 105, Skill: SkillArmor), + new(YellowTopaz, "Yellow Topaz", TinkerOrigin.Retail, TinkerKind.Imbue, "Missile defense imbue", 106, Skill: SkillArmor), + new(Zircon, "Zircon", TinkerOrigin.Retail, TinkerKind.Imbue, "Magic defense imbue", 107, Skill: SkillArmor), + new(Steel, "Steel", TinkerOrigin.Retail, TinkerKind.Tink, "+20 armor level", 300, Skill: SkillArmor), + new(Alabaster, "Alabaster", TinkerOrigin.Retail, TinkerKind.Tink, "+0.2 pierce protection", 310, Skill: SkillArmor), + new(Bronze, "Bronze", TinkerOrigin.Retail, TinkerKind.Tink, "+0.2 slash protection", 311, Skill: SkillArmor), + new(Marble, "Marble", TinkerOrigin.Retail, TinkerKind.Tink, "+0.2 bludgeon protection", 312, Skill: SkillArmor), + new(Armoredillo, "Armoredillo Hide", TinkerOrigin.Retail, TinkerKind.Tink, "+0.4 acid protection", 313, Skill: SkillArmor), + new(Ceramic, "Ceramic", TinkerOrigin.Retail, TinkerKind.Tink, "+0.4 fire protection", 314, Skill: SkillArmor), + new(Wool, "Wool", TinkerOrigin.Retail, TinkerKind.Tink, "+0.4 cold protection", 315, Skill: SkillArmor), + new(Reedshark, "Reedshark Hide", TinkerOrigin.Retail, TinkerKind.Tink, "+0.4 lightning protection", 316, Skill: SkillArmor), + new(Copper, "Copper", TinkerOrigin.Retail, TinkerKind.Once, "Activation: missile defense to melee defense", 380, Skill: SkillItem), + new(Silver, "Silver", TinkerOrigin.Retail, TinkerKind.Once, "Activation: melee defense to missile defense", 381, Skill: SkillItem), + }, + [TinkerBench.Melee] = new TinkerMaterial[] + { + new(BlackOpal, "Black Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Critical Strike imbue", 101, Skill: SkillWeapon), + new(FireOpal, "Fire Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Crippling Blow imbue", 102, Skill: SkillWeapon), + new(Sunstone, "Sunstone", TinkerOrigin.Retail, TinkerKind.Imbue, "Armor Rending imbue", 103, Skill: SkillWeapon), + new(RendId, "Damage-type rend", TinkerOrigin.Retail, TinkerKind.Imbue, "Rend matching the weapon's damage type", 110, Skill: SkillWeapon), + new(Brass, "Brass", TinkerOrigin.Retail, TinkerKind.Tink, "+1% melee defense", 170, Skill: SkillWeapon), + new(Granite, "Granite", TinkerOrigin.Retail, TinkerKind.Tink, "-20% damage variance", 180, Skill: SkillWeapon), + new(Iron, "Iron", TinkerOrigin.Retail, TinkerKind.Tink, "+1 maximum damage", 190, Skill: SkillWeapon), + new(Oak, "Oak", TinkerOrigin.Retail, TinkerKind.Tink, "-50 weapon speed", 200, Skill: SkillWeapon), + new(Velvet, "Velvet", TinkerOrigin.Retail, TinkerKind.Tink, "+1% attack", 210, Skill: SkillWeapon), + }, + [TinkerBench.Missile] = new TinkerMaterial[] + { + new(BlackOpal, "Black Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Critical Strike imbue", 101, Skill: SkillWeapon), + new(FireOpal, "Fire Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Crippling Blow imbue", 102, Skill: SkillWeapon), + new(Sunstone, "Sunstone", TinkerOrigin.Retail, TinkerKind.Imbue, "Armor Rending imbue", 103, Skill: SkillWeapon), + new(RendId, "Damage-type rend", TinkerOrigin.Retail, TinkerKind.Imbue, "Rend matching the weapon's damage type", 110, Skill: SkillWeapon), + new(Brass, "Brass", TinkerOrigin.Retail, TinkerKind.Tink, "+1% melee defense", 170, Skill: SkillWeapon), + new(Oak, "Oak", TinkerOrigin.Retail, TinkerKind.Tink, "-50 weapon speed", 200, Skill: SkillWeapon), + new(Mahogany, "Mahogany", TinkerOrigin.Retail, TinkerKind.Tink, "+4% damage modifier", 220, Skill: SkillWeapon), + }, + [TinkerBench.Caster] = new TinkerMaterial[] + { + new(BlackOpal, "Black Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Critical Strike imbue", 101, Skill: SkillMagicItem), + new(FireOpal, "Fire Opal", TinkerOrigin.Retail, TinkerKind.Imbue, "Crippling Blow imbue", 102, Skill: SkillMagicItem), + new(Sunstone, "Sunstone", TinkerOrigin.Retail, TinkerKind.Imbue, "Armor Rending imbue", 103, Skill: SkillMagicItem), + new(RendId, "Element rend", TinkerOrigin.Retail, TinkerKind.Imbue, "Rend matching the caster's element", 110, Skill: SkillMagicItem), + new(GreenGarnet, "Green Garnet", TinkerOrigin.Retail, TinkerKind.Tink, "+1% elemental damage", 150, Skill: SkillMagicItem), + new(Opal, "Opal", TinkerOrigin.Retail, TinkerKind.Tink, "+1% mana conversion", 160, Skill: SkillMagicItem), + new(Brass, "Brass", TinkerOrigin.Retail, TinkerKind.Tink, "+1% melee defense", 170, Skill: SkillWeapon), + }, + [TinkerBench.Jewelry] = new TinkerMaterial[] + { + new(Agate, "Agate", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Focus", 120, Skill: SkillMagicItem), + new(Azurite, "Azurite", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Wizard's Intellect", 121, Skill: SkillMagicItem), + new(Bloodstone, "Bloodstone", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Endurance", 122, Skill: SkillMagicItem), + new(Carnelian, "Carnelian", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Strength", 123, Skill: SkillMagicItem), + new(Citrine, "Citrine", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Stamina Gain", 124, Skill: SkillMagicItem), + new(Hematite, "Hematite", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Warrior's Vitality", 125, Skill: SkillMagicItem), + new(LapisLazuli, "Lapis Lazuli", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Willpower", 126, Skill: SkillMagicItem), + new(LavenderJade, "Lavender Jade", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Mana Gain", 127, Skill: SkillMagicItem), + new(Malachite, "Malachite", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Warrior's Vigor", 128, Skill: SkillMagicItem), + new(RedJade, "Red Jade", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Health Gain", 129, Skill: SkillMagicItem), + new(RoseQuartz, "Rose Quartz", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Quickness", 130, Skill: SkillMagicItem), + new(SmokeyQuartz, "Smokey Quartz", TinkerOrigin.Retail, TinkerKind.Imbue, "Cantrip: Coordination", 131, Skill: SkillMagicItem), + }, + [TinkerBench.Items] = new TinkerMaterial[] + { + new(Gold, "Gold", TinkerOrigin.Retail, TinkerKind.Tink, "+25% value", 400, Skill: SkillItem), + new(Pine, "Pine", TinkerOrigin.Retail, TinkerKind.Tink, "-25% value", 410, Skill: SkillItem), + new(Linen, "Linen", TinkerOrigin.Retail, TinkerKind.Tink, "-25% burden", 420, Skill: SkillItem), + new(Moonstone, "Moonstone", TinkerOrigin.Retail, TinkerKind.Tink, "+500 maximum mana", 430, Skill: SkillItem), + new(Silk, "Silk", TinkerOrigin.Retail, TinkerKind.Once, "Allegiance rank requirement becomes spellcraft", 440, Skill: SkillItem), + new(Teak, "Teak", TinkerOrigin.Retail, TinkerKind.Once, "Heritage requirement: Aluvian", 450, Skill: SkillItem), + new(Ebony, "Ebony", TinkerOrigin.Retail, TinkerKind.Once, "Heritage requirement: Gharu'ndim", 451, Skill: SkillItem), + new(Porcelain, "Porcelain", TinkerOrigin.Retail, TinkerKind.Once, "Heritage requirement: Sho", 452, Skill: SkillItem), + new(Satin, "Satin", TinkerOrigin.Retail, TinkerKind.Once, "Heritage requirement: Viamontian", 453, Skill: SkillItem), + new(Ivory, "Ivory", TinkerOrigin.Retail, TinkerKind.Once, "Removes attunement", 490, UsesTinkSlot: false, Skill: SkillItem), + new(Leather, "Leather", TinkerOrigin.Retail, TinkerKind.Once, "Retained (can't be salvaged or sold)", 500, UsesTinkSlot: false, Skill: SkillItem), + new(Sandstone, "Sandstone", TinkerOrigin.Retail, TinkerKind.Once, "Removes Retained", 510, UsesTinkSlot: false, Skill: SkillItem), + }, + [TinkerBench.Trinkets] = Array.Empty(), + }; + + /// The retail rows of a tab. + public static IReadOnlyList RetailFor(TinkerBench bench) => Retail[bench]; + + /// + /// A server plugin's salvage rows for one tab (its profile's "salvage" list). Rows for other + /// tabs, unknown tab names and unknown kinds are left out. A row's own "order" decides where it + /// runs; without one, imbues run before tinks and one-application rows after them, each in the + /// plugin's list order. + /// + public static List FromServerPlugin(TinkerBench bench, IEnumerable? salvage) + { + var rows = new List(); + if (salvage == null) return rows; + string benchName = bench.ToString().ToLowerInvariant(); + int i = 0; + foreach (var s in salvage) + { + if (s == null || s.Material <= 0 || !string.Equals(s.Bench, benchName, StringComparison.OrdinalIgnoreCase)) continue; + TinkerKind? kind = s.Kind switch + { + "tink" or "" => TinkerKind.Tink, + "imbue" => TinkerKind.Imbue, + "once" => TinkerKind.Once, + _ => null, + }; + if (kind == null) continue; + int order = kind switch + { + TinkerKind.Imbue => 115, + TinkerKind.Once => 600, + _ => 400, + } + i++; + if (s.Order != 0) order = s.Order; + string group = s.StackCap > 0 ? (s.StackGroup ?? string.Empty).Trim() : string.Empty; + rows.Add(new TinkerMaterial(s.Material, MaterialName(s.Material), TinkerOrigin.Plugin, kind.Value, + string.IsNullOrWhiteSpace(s.Effect) ? "server recipe" : s.Effect.Trim(), order, + UsesTinkSlot: s.UsesTinkSlot, AppliedInt: s.AppliedInt, NameMatch: s.NameMatch ?? string.Empty, + Prepared: s.Prepared, AfterCap: s.AfterCap, StackGroup: group, StackCap: group.Length > 0 ? s.StackCap : 0)); + } + return rows; + } + + /// + /// Settings key for a row: retail and server rows of one tab share ids (Wool, Steel...). Keys + /// with the old "s" prefix (RynthAi's own Leaftide rows before they moved to RynthILT) match no row. + /// + public static string Key(TinkerMaterial m) => m.Origin switch + { + TinkerOrigin.Retail => "r" + m.Id, + TinkerOrigin.Plugin => "p" + m.Id, + _ => "c" + m.Id, + }; + + /// The object classes a tab scans. + public static bool Targets(TinkerBench bench, AcObjectClass oc) => bench switch + { + TinkerBench.Armor => oc is AcObjectClass.Armor or AcObjectClass.Clothing, + TinkerBench.Melee => oc == AcObjectClass.MeleeWeapon, + TinkerBench.Missile => oc == AcObjectClass.MissileWeapon, + TinkerBench.Caster => oc == AcObjectClass.WandStaffOrb, + TinkerBench.Jewelry or TinkerBench.Trinkets => oc == AcObjectClass.Jewelry, + TinkerBench.Items => oc is not (AcObjectClass.Salvage or AcObjectClass.Container or AcObjectClass.Unknown + or AcObjectClass.Money or AcObjectClass.TradeNote or AcObjectClass.SpellComponent or AcObjectClass.Food), + _ => false, + }; + + /// + /// Trinkets (compass, goggles, scarab, watch, puzzle box, tops) are jewelry the Jewelry tab + /// leaves alone: they take the Trinkets tab's recipes instead (UB-IT IsLeaftideTrinketJewelry). + /// + public static bool IsTrinket(string name) + { + string n = (name ?? string.Empty).ToLowerInvariant(); + if (n.Contains("compass") || n.Contains("goggles") || n.Contains("scarab") || n.Contains("watch") || n.Contains("puzzle box")) + return true; + return n.Contains("top") && !n.Contains("topaz"); + } + + public static string Label(TinkerBench bench) => bench switch + { + TinkerBench.Armor => "Armor", + TinkerBench.Melee => "Melee", + TinkerBench.Missile => "Missile", + TinkerBench.Caster => "Caster", + TinkerBench.Jewelry => "Jewelry", + TinkerBench.Items => "Items", + TinkerBench.Trinkets => "Trinkets", + _ => bench.ToString(), + }; + + /// The default tinkering skill a tab's custom rows use for the chance. + public static int DefaultSkill(TinkerBench bench) => bench switch + { + TinkerBench.Armor => SkillArmor, + TinkerBench.Melee or TinkerBench.Missile => SkillWeapon, + TinkerBench.Caster or TinkerBench.Jewelry => SkillMagicItem, + _ => SkillItem, + }; + + /// + /// The rend gem for a weapon's damage type (melee/missile DamageType 45, the caster's element + /// the same field): Slash+Pierce takes ; Nether is Onyx. + /// 0 when the type has no rend. + /// + public static int RendFor(int damageType, bool pierceForCombo) + { + if (damageType == 3) return pierceForCombo ? BlackGarnet : ImperialTopaz; + if ((damageType & 0x400) != 0) return Onyx; + return damageType switch + { + 1 => ImperialTopaz, + 2 => BlackGarnet, + 4 => WhiteSapphire, + 8 => Aquamarine, + 16 => RedGarnet, + 32 => Emerald, + 64 => Jet, + _ => 0, + }; + } + + /// The rend gem a Foolproof bag's name advertises (server bags may not set Material), else 0. + public static int RendFromFoolproofName(string name) + { + if (string.IsNullOrEmpty(name) || name.IndexOf("Foolproof", StringComparison.OrdinalIgnoreCase) < 0) return 0; + // Longer names first: "Black Opal" must not read as "Black Garnet", "Onyx" before both. + (string Text, int Id)[] map = + { + ("Imperial Topaz", ImperialTopaz), ("White Sapphire", WhiteSapphire), ("Onyx", Onyx), + ("Black Garnet", BlackGarnet), ("Black Opal", BlackOpal), ("Aquamarine", Aquamarine), + ("Red Garnet", RedGarnet), ("Emerald", Emerald), ("Jet", Jet), + }; + foreach (var (text, id) in map) + if (name.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0) return id; + return 0; + } + + /// Material names for the custom-row picker and status text. + public static readonly (int Id, string Name)[] MaterialNames = + { + (Ceramic, "Ceramic"), (Porcelain, "Porcelain"), (3, "Cloth"), (Linen, "Linen"), (Satin, "Satin"), (Silk, "Silk"), + (Velvet, "Velvet"), (Wool, "Wool"), (Agate, "Agate"), (11, "Amber"), (12, "Amethyst"), (Aquamarine, "Aquamarine"), + (Azurite, "Azurite"), (BlackGarnet, "Black Garnet"), (BlackOpal, "Black Opal"), (Bloodstone, "Bloodstone"), + (Carnelian, "Carnelian"), (Citrine, "Citrine"), (Diamond, "Diamond"), (Emerald, "Emerald"), (FireOpal, "Fire Opal"), + (GreenGarnet, "Green Garnet"), (GreenJade, "Green Jade"), (Hematite, "Hematite"), (ImperialTopaz, "Imperial Topaz"), + (Jet, "Jet"), (LapisLazuli, "Lapis Lazuli"), (LavenderJade, "Lavender Jade"), (Malachite, "Malachite"), + (Moonstone, "Moonstone"), (Onyx, "Onyx"), (Opal, "Opal"), (Peridot, "Peridot"), (RedGarnet, "Red Garnet"), + (RedJade, "Red Jade"), (RoseQuartz, "Rose Quartz"), (Ruby, "Ruby"), (39, "Sapphire"), (SmokeyQuartz, "Smokey Quartz"), + (Sunstone, "Sunstone"), (TigerEye, "Tiger Eye"), (Tourmaline, "Tourmaline"), (Turquoise, "Turquoise"), + (WhiteJade, "White Jade"), (WhiteQuartz, "White Quartz"), (WhiteSapphire, "White Sapphire"), + (YellowGarnet, "Yellow Garnet"), (YellowTopaz, "Yellow Topaz"), (Zircon, "Zircon"), (Ivory, "Ivory"), + (Leather, "Leather"), (Armoredillo, "Armoredillo Hide"), (GromnieHide, "Gromnie Hide"), (Reedshark, "Reedshark Hide"), + (Brass, "Brass"), (Bronze, "Bronze"), (Copper, "Copper"), (Gold, "Gold"), (Iron, "Iron"), (Pyreal, "Pyreal"), + (Silver, "Silver"), (Steel, "Steel"), (Alabaster, "Alabaster"), (Granite, "Granite"), (Marble, "Marble"), + (Sandstone, "Sandstone"), (Serpentine, "Serpentine"), (Ebony, "Ebony"), (Mahogany, "Mahogany"), (Oak, "Oak"), + (Pine, "Pine"), (Teak, "Teak"), + }; + + /// A material's display name ("#id" when unknown). + public static string MaterialName(int id) + { + foreach (var (mid, name) in MaterialNames) + if (mid == id) return name; + return "#" + id; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerMath.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerMath.cs new file mode 100644 index 0000000..ef4bdd1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerMath.cs @@ -0,0 +1,72 @@ +// TinkerMath.cs - Retail tinkering success chance, as ACE computes it +// (RecipeManager.GetTinkerChance, GetMaterialMod, TinkeringDifficulty; SkillCheck.GetSkillChance). +// +// difficulty = floor((salvageMod*5 + itemWork*salvageMod*2 - toolWork*wkMod*salvageMod/5) * attemptMod) +// chance = 1 - 1 / (1 + e^(0.03 * (skill - difficulty))) imbue: chance / 3 +// +// toolWork is the bag's average workmanship (ItemWorkmanship / NumItemsInMaterial), wkMod is 2 +// when the bag is at least as good as the item, attemptMod grows with the item's tinker count. +// Foolproof bags always succeed. Server extras (ILT recipes, augmentation, charms) are not +// modelled: the server's confirmation percent is the final word (ConfirmationResponder). +using System; + +namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting; + +internal static class TinkerMath +{ + /// Difficulty multiplier by how many tinks the item already has (index 0-9). + private static readonly double[] AttemptMod = { 1.0, 1.1, 1.3, 1.6, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 }; + + /// Salvage difficulty factor (GetMaterialMod). + public static double SalvageMod(int material) => material switch + { + TinkerCatalog.Gold or TinkerCatalog.Oak => 10.0, + TinkerCatalog.Alabaster or TinkerCatalog.Armoredillo or TinkerCatalog.Brass or TinkerCatalog.Bronze + or TinkerCatalog.Ceramic or TinkerCatalog.Granite or TinkerCatalog.Linen or TinkerCatalog.Marble + or TinkerCatalog.Moonstone or TinkerCatalog.Opal or TinkerCatalog.Pine or TinkerCatalog.Reedshark + or TinkerCatalog.Velvet or TinkerCatalog.Wool => 11.0, + TinkerCatalog.Ebony or TinkerCatalog.GreenGarnet or TinkerCatalog.Iron or TinkerCatalog.Mahogany + or TinkerCatalog.Porcelain or TinkerCatalog.Satin or TinkerCatalog.Steel or TinkerCatalog.Teak => 12.0, + TinkerCatalog.Bloodstone or TinkerCatalog.Carnelian or TinkerCatalog.Citrine or TinkerCatalog.Hematite + or TinkerCatalog.LavenderJade or TinkerCatalog.Malachite or TinkerCatalog.RedJade or TinkerCatalog.RoseQuartz => 25.0, + _ => 20.0, + }; + + /// The recipe difficulty for one attempt (an item at 10 tinks can't be tinkered: int.MaxValue). + public static int Difficulty(int material, double itemWorkmanship, double toolWorkmanship, int tinks) + { + if (tinks < 0) tinks = 0; + if (tinks >= AttemptMod.Length) return int.MaxValue; + double salvageMod = SalvageMod(material); + double wkMod = toolWorkmanship >= itemWorkmanship ? 2.0 : 1.0; + return (int)Math.Floor(((salvageMod * 5.0) + (itemWorkmanship * salvageMod * 2.0) + - (toolWorkmanship * wkMod * salvageMod / 5.0)) * AttemptMod[tinks]); + } + + /// SkillCheck.GetSkillChance: the logistic curve AC uses for every skill check. + public static double SkillChance(int skill, int difficulty) + { + if (difficulty == int.MaxValue) return 0.0; + double chance = 1.0 - (1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty)))); + return Math.Clamp(chance, 0.0, 1.0); + } + + /// + /// The retail chance (0-1) of one application: is the buffed + /// tinkering skill, divides by 3, is 1. + /// + public static double Chance(int material, int skill, double itemWorkmanship, double toolWorkmanship, + int tinks, bool imbue, bool foolproof) + { + if (foolproof) return 1.0; + double c = SkillChance(skill, Difficulty(material, itemWorkmanship, toolWorkmanship, tinks)); + return imbue ? c / 3.0 : c; + } + + /// A bag's average workmanship: ItemWorkmanship over NumItemsInMaterial. + public static double BagWorkmanship(int itemWorkmanship, int numItemsInMaterial) + => numItemsInMaterial > 0 ? itemWorkmanship / (double)numItemsInMaterial : itemWorkmanship; + + /// Whole percent the way the server's dialog rounds it ("You determine that you have a N percent chance"). + public static int Percent(double chance) => (int)Math.Round(Math.Clamp(chance, 0.0, 1.0) * 100.0, MidpointRounding.AwayFromZero); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerPlanner.cs new file mode 100644 index 0000000..8b60d96 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerPlanner.cs @@ -0,0 +1,249 @@ +// TinkerPlanner.cs - What a Crafting tab would apply to one item, and which bag to use. +// +// Pure: the scan reads the item into TinkerItemFacts and the runner re-plans from fresh facts, +// so these rules are the only place the apply order and caps live (and the host tests drive +// them directly). Server rows say which rules apply to them (TinkerMaterial, from the server +// plugin's profile); nothing here knows a server: +// * rows run in TinkerMaterial.Order (imbues and server crit lines before stat tinks; with +// "rend last" the rend moves to the end, the way UB-IT's foolproof-rend option does); +// * a tink-slot row is cut to the free slots (10 minus the item's tinks); no-slot rows aren't; +// * one imbue per item (the item's own, or the first planned one); +// * a row with an applied int is skipped once that int reads 2 on the item; +// * rows of one stack group stop at the group's cap combined; +// * an after-cap row goes on last, once, and only when the tink slots are full; +// * a prepared row needs a bag prepared at the chosen tier (its name says Minor, Moderate or +// Major); a raw bag becomes one on that tier's Ammunition. +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting; + +/// What the planner needs to know about an item. +internal sealed class TinkerItemFacts +{ + public int Id; + public string Name = string.Empty; + public AcObjectClass Class; + /// The item's workmanship (ItemWorkmanship 105; 0 = can't be tinkered). + public double Workmanship; + /// NumTimesTinkered (171). + public int Tinks; + /// ImbuedEffect (179) is set. + public bool Imbued; + /// DamageType (45): melee/missile damage, the caster's element. + public int DamageType; + /// Retained (bool 91). + public bool Retained; + /// ItemMaxMana (108). + public int MaxMana; + public bool Equipped; + /// Reads an int property of the item (a row's applied int: 2 = that salvage is on). + public Func FlagInt = _ => 0; +} + +/// One planned application: the row and the salvage it resolves to (a rend resolves per item). +internal readonly record struct TinkerStep(TinkerMaterial Row, int Material); + +/// A bag a step could use (for ). +internal readonly record struct TinkerBagChoice(int Id, double Workmanship, double? Chance); + +internal static class TinkerPlanner +{ + /// + /// The rows a tab offers: retail, then (the connected server's own + /// salvage, from the plugin that owns it), then the player's custom rows. + /// + public static List Rows(TinkerBench bench, IEnumerable? server, IEnumerable? custom) + { + var rows = new List(TinkerCatalog.RetailFor(bench)); + if (server != null) rows.AddRange(server); + if (custom != null) + { + foreach (var c in custom) + { + if (c.Bench != (int)bench || c.Material <= 0) continue; + var kind = c.Imbue ? TinkerKind.Imbue : c.Once ? TinkerKind.Once : TinkerKind.Tink; + rows.Add(new TinkerMaterial(c.Material, TinkerCatalog.MaterialName(c.Material), TinkerOrigin.Custom, kind, + string.IsNullOrWhiteSpace(c.Note) ? "custom" : c.Note, 900 + rows.Count, + UsesTinkSlot: c.UsesTinkSlot, NameMatch: c.NameMatch ?? string.Empty)); + } + } + return rows; + } + + /// The order a row runs in under these settings. + public static int OrderOf(TinkerMaterial row, TinkerBenchSettings s) + => row.Id == TinkerCatalog.RendId && s.RendLast ? 990 : row.Order; + + /// Why the scan leaves an item out ("" = it's eligible and the plan decides). + public static string Excluded(TinkerItemFacts item, TinkerBenchSettings s) + { + if (item.Equipped) return "equipped"; + if (item.Workmanship <= 0) return "no workmanship"; + if (item.Tinks > Math.Clamp(s.MaxTinks, 0, TinkerCatalog.MaxTinks)) return $"{item.Tinks} tinks (max {s.MaxTinks})"; + if (s.MinFreeTinks > 0 && TinkerCatalog.MaxTinks - item.Tinks < s.MinFreeTinks) return $"fewer than {s.MinFreeTinks} free tinks"; + if (s.SkipImbued && item.Imbued) return "imbued"; + return string.Empty; + } + + /// + /// The ordered steps for one item (empty when nothing ticked applies). + /// is how many times this run already tried a row key on the + /// item: the item's tinks count failures too, but no-slot server rows and the ticked counts + /// don't show on it, so a re-plan would otherwise repeat them. + /// + public static List Plan(TinkerBench bench, TinkerItemFacts item, TinkerBenchSettings s, + IReadOnlyList rows, Func? attempted = null) + { + var steps = new List(); + int free = Math.Max(0, TinkerCatalog.MaxTinks - item.Tinks); + bool imbueTaken = item.Imbued; + Dictionary? stacked = null; + List? afterCap = null; + + foreach (var row in rows.OrderBy(r => OrderOf(r, s))) + { + string key = TinkerCatalog.Key(row); + int count = s.Counts.TryGetValue(key, out int c) ? c : 0; + int tried = attempted?.Invoke(key) ?? 0; + if (row.Kind != TinkerKind.Tink) count = Math.Min(count, 1); + count -= tried; + if (count <= 0) continue; + int material = row.Id == TinkerCatalog.RendId ? TinkerCatalog.RendFor(item.DamageType, s.PierceForCombo) : row.Id; + if (material <= 0 || !Applies(row, material, item)) continue; + + int n = row.Kind == TinkerKind.Tink ? count : 1; + if (row.Kind == TinkerKind.Imbue) + { + if (imbueTaken) continue; + imbueTaken = true; + } + if (row.AppliedInt != 0 && item.FlagInt(row.AppliedInt) == 2) continue; + if (row.StackGroup.Length > 0 && row.StackCap > 0) + { + stacked ??= new Dictionary(StringComparer.OrdinalIgnoreCase); + int used = stacked.TryGetValue(row.StackGroup, out int u) ? u : 0; + n = Math.Min(n, row.StackCap - used); + stacked[row.StackGroup] = used + Math.Max(0, n); + } + if (row.AfterCap) + { + (afterCap ??= new List()).Add(new TinkerStep(row, material)); + continue; + } + if (row.UsesTinkSlot) + { + n = Math.Min(n, free); + free -= Math.Max(0, n); + } + for (int i = 0; i < n; i++) steps.Add(new TinkerStep(row, material)); + } + if (afterCap != null && free == 0) steps.AddRange(afterCap); + return steps; + } + + /// Row-level requirements the item's own properties decide. + private static bool Applies(TinkerMaterial row, int material, TinkerItemFacts item) + { + if (row.Origin != TinkerOrigin.Retail) return true; + return material switch + { + TinkerCatalog.Moonstone => item.MaxMana > 0, + TinkerCatalog.Leather => !item.Retained, + TinkerCatalog.Sandstone => item.Retained, + _ => true, + }; + } + + /// + /// Whether a salvage bag can serve a step: a full bag (100 units) of the material, server bags + /// matched by name (Abyssal-Touched Gems share Black Garnet's id, Foolproof rend bags may not + /// carry a material at all). + /// + public static bool BagMatches(TinkerStep step, string bagName, int bagMaterial, int bagUses, int trinketTier = 0) + { + if (bagUses < 100) return false; + bagName ??= string.Empty; + if (step.Row.Prepared) + return bagMaterial == step.Material && TierOf(bagName) == Math.Clamp(trinketTier, 0, TinkerCatalog.TrinketTiers.Length - 1); + bool abyssal = bagName.IndexOf("Abyssal", StringComparison.OrdinalIgnoreCase) >= 0; + if (step.Row.NameMatch.Length > 0) + return bagName.IndexOf(step.Row.NameMatch, StringComparison.OrdinalIgnoreCase) >= 0; + if (abyssal) return false; + if (bagMaterial == step.Material) return true; + return step.Row.Id == TinkerCatalog.RendId && TinkerCatalog.RendFromFoolproofName(bagName) == step.Material; + } + + /// The prepared tier a name carries (0 Minor, 1 Moderate, 2 Major), else -1. + public static int TierOf(string name) + { + name ??= string.Empty; + for (int i = 0; i < TinkerCatalog.TrinketTiers.Length; i++) + if (name.IndexOf(TinkerCatalog.TrinketTiers[i], StringComparison.OrdinalIgnoreCase) >= 0) return i; + return -1; + } + + /// A full, not yet prepared bag of a prepared row's salvage (no tier in its name). + public static bool IsRawTrinketBag(int material, string bagName, int bagMaterial, int bagUses) + => bagUses >= 100 && bagMaterial == material && TierOf(bagName) < 0; + + /// The Ammunition that prepares a raw bag into a tier bag. + public static bool IsTierAmmunition(string name, int tier) + => (name ?? string.Empty).IndexOf("Ammunition", StringComparison.OrdinalIgnoreCase) >= 0 + && TierOf(name!) == Math.Clamp(tier, 0, TinkerCatalog.TrinketTiers.Length - 1); + + /// True for a bag that can't fail ("Foolproof ..."). + public static bool IsFoolproof(string bagName) + => (bagName ?? string.Empty).IndexOf("Foolproof", StringComparison.OrdinalIgnoreCase) >= 0; + + /// + /// Picks the bag for a step (-1 = none qualifies). With a minimum percent: the lowest + /// workmanship bag that reaches it, so good bags are kept for hard tinks. Without one: the + /// best chance (lowest workmanship on a tie). A bag whose chance isn't known (server rows) + /// is the best workmanship one; the server's own percent is checked when it asks. + /// + public static int SelectBag(IReadOnlyList bags, int minPercent) + { + int best = -1; + for (int i = 0; i < bags.Count; i++) + { + var b = bags[i]; + if (b.Chance is not double c) + { + if (best < 0 || (bags[best].Chance == null && b.Workmanship > bags[best].Workmanship)) best = i; + continue; + } + if (minPercent > 0) + { + if (TinkerMath.Percent(c) < minPercent) continue; + if (best < 0 || bags[best].Chance == null || b.Workmanship < bags[best].Workmanship) best = i; + } + else + { + if (best < 0 || bags[best].Chance == null) { best = i; continue; } + double bc = bags[best].Chance!.Value; + if (c > bc + 1e-9 || (Math.Abs(c - bc) <= 1e-9 && b.Workmanship < bags[best].Workmanship)) best = i; + } + } + return best; + } + + /// "Iron x3, Brass x2" for a plan. + public static string Summary(IReadOnlyList steps) + { + if (steps.Count == 0) return "-"; + var parts = new List(); + int i = 0; + while (i < steps.Count) + { + int j = i; + while (j < steps.Count && steps[j].Material == steps[i].Material && steps[j].Row.Origin == steps[i].Row.Origin) j++; + string name = TinkerCatalog.MaterialName(steps[i].Material); + parts.Add(j - i > 1 ? $"{name} x{j - i}" : name); + i = j; + } + return string.Join(", ", parts); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerRunner.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerRunner.cs new file mode 100644 index 0000000..077421d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/TinkerRunner.cs @@ -0,0 +1,586 @@ +// TinkerRunner.cs - Scans one Crafting tab's items, plans them and applies the salvage. +// +// Pump thread only (the tab's Render reads the volatile snapshots and posts Scan/Start/Stop). +// One step at a time: +// 1. gates: peace mode (unless the server allows combat crafting), not busy, ActionPacer; +// 2. re-plan the item from fresh facts (TinkerPlanner) minus what this run already tried; +// 3. pick the bag (TinkerPlanner.SelectBag over TinkerMath's retail chance, Foolproof = 100%); +// 4. arm the engine's confirmation answer (v81: Yes only at the tab's minimum percent) and +// UseObjectOn(bag, item); +// 5. wait for the result: the craft chat line, the bag leaving the pack, a declined +// confirmation, "cannot be used on", or a WeenieError (YoureTooBusy retries). +// Without the v81 engine (or with dialog answering off) AC shows its own dialog and the player +// clicks it; the runner waits longer for that. +// Prepared rows (a server's trinket salvage): with no bag prepared at the chosen tier, a raw bag +// is first used on that tier's Ammunition (UB-IT's "prep salvage") and the step runs once the +// prepared bag shows up. +// Items a run finished are left out of later scans this session, so server rows that don't show +// on the item aren't applied twice and "auto next batch" moves on to the next items. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting; + +/// One scanned item as the tab shows it. +internal sealed class TinkerRow +{ + public int Id; + public string Name = string.Empty; + public int Tinks; + public double Workmanship; + public bool Imbued; + public string Plan = "-"; + /// Updated by the runner as it works the item. + public volatile string Status = "planned"; +} + +internal sealed class TinkerRunner +{ + private const uint IntWorkmanship = 105; + private const uint IntNumItemsInMaterial = 170; + private const uint IntDamageType = 45; + private const uint IntItemMaxMana = 108; + private const uint BoolRetained = 91; + private const uint ErrorYoureTooBusy = 0x1D; + private const long StepTimeoutMs = 15_000; + /// The player answers AC's own dialog: give them time. + private const long ManualTimeoutMs = 60_000; + private const long RetryDelayMs = 1_500; + private const long StepGapMs = 600; + private const int MaxRetries = 3; + /// Appraisal requests one scan may send (the Items tab sees the whole pack). + private const int MaxAppraisalsPerScan = 25; + /// UB-IT polls up to ~30 s for the prepared bag. + private const long PrepTimeoutMs = 30_000; + /// Auto next batch: re-scan while items are still being appraised, this often and this many times. + private const long AutoRescanDelayMs = 3_000; + private const int AutoRescanTries = 10; + + private static readonly Regex Applied = new( + @"^(?[\w\s]+) successfully applies the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Failed = new( + @"^(?[\w\s]+) fails to apply the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Foolproof = new(@"^You apply the (?.*)\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private readonly MiniRemoteContext _ctx; + private readonly Func> _rows; + private readonly Func _settings; + + // Job (pump thread) + private TinkerBench _bench; + private readonly Queue _queue = new(); + private int _itemId; + private readonly Dictionary _attempted = new(); + private readonly HashSet _skipped = new(); + private bool _waiting; + private TinkerStep _step; + private int _bagId; + private string _bagName = string.Empty; + private int _confSeq, _errSeq, _retries, _stepPercent; + private bool _manual; + private long _stepAt, _nextAt; + private Dictionary _byId = new(); + /// The wait is for a bag being prepared, not a tinker. + private bool _prep; + private int _prepsThisItem; + /// Bags this batch used up (auto next batch stops after a batch that used none). + private int _usedThisBatch; + private long _autoRescanAt; + private int _autoRescansLeft; + /// Items a run finished this session, per bench (pump thread). + private readonly Dictionary> _done = new(); + /// Per-bench copies of the done counts for the tab. + private readonly int[] _doneCounts = new int[Enum.GetValues().Length]; + + // Render snapshots + private volatile TinkerRow[] _scan = Array.Empty(); + private volatile string _status = "idle"; + private volatile int _scannedBench = -1; + + public TinkerRunner(MiniRemoteContext ctx, Func> rows, + Func settings) + { + _ctx = ctx; + _rows = rows; + _settings = settings; + } + + /// A job is on (set by Start, cleared by Stop: the queue empties before the batch-done step runs). + public bool Running => _active; + private volatile bool _active; + public TinkerBench Bench => _bench; + public string Status => _status; + /// The last scan's rows (for ). + public TinkerRow[] Rows => _scan; + public int ScannedBench => _scannedBench; + /// How many of a bench's items this session already finished (render thread safe). + public int DoneCount(TinkerBench bench) => Volatile.Read(ref _doneCounts[(int)bench]); + + private RynthCoreHost Host => _ctx.Host; + private MiniRemoteInventory Inv => _ctx.Inventory; + private CraftingTabState C => _ctx.State.Crafting; + private int Tier => Math.Clamp(C.TrinketTier, 0, TinkerCatalog.TrinketTiers.Length - 1); + + private HashSet DoneSet(TinkerBench bench) + { + if (!_done.TryGetValue(bench, out var set)) _done[bench] = set = new HashSet(); + return set; + } + + /// Lets a bench's finished items show in scans again (pump thread). + public void ForgetDone(TinkerBench bench) + { + DoneSet(bench).Clear(); + Volatile.Write(ref _doneCounts[(int)bench], 0); + _status = $"{TinkerCatalog.Label(bench)}: finished items will show in scans again"; + } + + private void MarkDone(TinkerBench bench, int id) + { + var set = DoneSet(bench); + if (set.Add(id)) Volatile.Write(ref _doneCounts[(int)bench], set.Count); + } + + // ── Scan ──────────────────────────────────────────────────────────────── + + /// Reads what the planner needs from an item. + public TinkerItemFacts Facts(WorldObject wo) => new() + { + Id = wo.Id, + Name = wo.Name ?? string.Empty, + Class = wo.ObjectClass, + Workmanship = Inv.Int(wo, IntWorkmanship), + Tinks = Inv.Int(wo, MiniRemoteInventory.IntNumTimesTinkered), + Imbued = Inv.Int(wo, MiniRemoteInventory.IntImbuedEffect) != 0, + DamageType = Inv.Int(wo, IntDamageType), + Retained = Inv.Bool(wo, BoolRetained), + MaxMana = Inv.Int(wo, IntItemMaxMana), + Equipped = Inv.IsEquipped(wo), + FlagInt = k => Inv.Int(wo, unchecked((uint)k)), + }; + + /// A thread-safe copy of a bench's settings (the tab edits Counts under its lock). + public static TinkerBenchSettings Snapshot(TinkerBenchSettings s) + { + lock (s.Counts) + { + return new TinkerBenchSettings + { + Counts = new Dictionary(s.Counts), + MinChancePercent = s.MinChancePercent, + MaxTinks = s.MaxTinks, + MinFreeTinks = s.MinFreeTinks, + SkipImbued = s.SkipImbued, + PierceForCombo = s.PierceForCombo, + RendLast = s.RendLast, + }; + } + } + + /// + /// Scans the pack for a tab: up to BatchSize items that have something to apply, leaving out + /// the ones this session already finished. Returns how many items are still being appraised. + /// + public int Scan(TinkerBench bench) + { + if (Running) { _status = "stop the running job before scanning"; return 0; } + _autoRescanAt = 0; + var s = Snapshot(_settings(bench)); + var rows = _rows(bench); + var done = DoneSet(bench); + int batch = Math.Clamp(C.BatchSize, 1, 100); + var list = new List(); + int appraising = 0, hidden = 0; + foreach (var wo in Inv.Items()) + { + if (!TinkerCatalog.Targets(bench, wo.ObjectClass)) continue; + bool trinket = TinkerCatalog.IsTrinket(wo.Name); + if (bench == TinkerBench.Jewelry && trinket) continue; + if (bench == TinkerBench.Trinkets && !trinket) continue; + if (done.Contains(wo.Id)) { hidden++; continue; } + if (!Inv.HasAppraisal(wo)) + { + if (appraising < MaxAppraisalsPerScan && Inv.RequestAppraisal(wo)) appraising++; + continue; + } + var f = Facts(wo); + if (TinkerPlanner.Excluded(f, s).Length > 0) continue; + var plan = TinkerPlanner.Plan(bench, f, s, rows); + if (plan.Count == 0) continue; + list.Add(new TinkerRow + { + Id = f.Id, Name = f.Name, Tinks = f.Tinks, Workmanship = f.Workmanship, Imbued = f.Imbued, + Plan = TinkerPlanner.Summary(plan), + }); + if (list.Count >= batch) break; + } + _scan = list.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + _scannedBench = (int)bench; + string hiddenText = hidden > 0 ? $"; {hidden} finished this session left out" : ""; + _status = (list.Count == 0 + ? (appraising > 0 ? $"nothing to do yet - appraising {appraising} item(s), scan again in a moment" : "nothing to do: no item matches the ticked salvage") + : $"{list.Count} item(s) planned" + (appraising > 0 ? $" ({appraising} still being appraised)" : "")) + hiddenText; + return appraising; + } + + // ── Job control ───────────────────────────────────────────────────────── + + /// Starts on the last scan's rows (pump thread, after the tab's confirm). + public void Start(TinkerBench bench) + { + if (Running) return; + if (_scannedBench != (int)bench || _scan.Length == 0) { _status = "scan first"; return; } + _bench = bench; + _queue.Clear(); + _byId = _scan.ToDictionary(r => r.Id); + foreach (var r in _scan) { _queue.Enqueue(r.Id); r.Status = "queued"; } + _itemId = 0; + _waiting = false; + _prep = false; + _nextAt = 0; + _usedThisBatch = 0; + _autoRescanAt = 0; + _active = true; + _status = $"working {_queue.Count} item(s)"; + RynthLog.Write(LogCat.Crafting, $"[Crafting] {TinkerCatalog.Label(bench)}: start, {_queue.Count} item(s)"); + } + + public void Stop(string why) + { + if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + if (_itemId != 0) SetRow(_itemId, "stopped"); + while (_queue.Count > 0) SetRow(_queue.Dequeue(), "not started"); + _itemId = 0; + _waiting = false; + _prep = false; + _autoRescanAt = 0; + _active = false; + _status = why; + } + + public void OnLogout() + { + Stop("idle"); + _scan = Array.Empty(); + _scannedBench = -1; + foreach (var bench in Enum.GetValues()) + { + DoneSet(bench).Clear(); + Volatile.Write(ref _doneCounts[(int)bench], 0); + } + } + + /// + /// The queue ran out. With auto next batch on, scan the next items (the finished ones are left + /// out) and start them if asked; a batch that used no bag at all ends it, so a pack of items + /// that all lack salvage isn't walked batch after batch. + /// + private void BatchDone(long nowMs) + { + var bench = _bench; + int used = _usedThisBatch; + Stop($"done - {used} bag(s) used"); + RynthLog.Write(LogCat.Crafting, $"[Crafting] {TinkerCatalog.Label(bench)}: batch done, {used} bag(s) used"); + if (!C.AutoNextBatch) return; + if (used == 0) { _status = "done - this batch used no bag, auto next batch stopped"; return; } + _autoRescansLeft = AutoRescanTries; + AutoScan(bench, nowMs); + } + + private void AutoScan(TinkerBench bench, long nowMs) + { + int appraising = Scan(bench); + if (_scan.Length == 0) + { + // The next items may only be waiting for their appraisal. + if (appraising > 0 && _autoRescansLeft-- > 0) + { + _bench = bench; + _autoRescanAt = nowMs + AutoRescanDelayMs; + } + else _status = "auto next batch: nothing left to do"; + return; + } + if (C.AutoStartNextBatch) Start(bench); + else _status = $"next batch ready: {_scan.Length} item(s) - press Start"; + } + + private void SetRow(int id, string status) + { + if (_byId.TryGetValue(id, out var r)) r.Status = status; + } + + private string AttemptKey(string rowKey) => _itemId + ":" + rowKey; + + private void NextItem(string doneStatus) + { + if (_itemId != 0) + { + SetRow(_itemId, doneStatus); + MarkDone(_bench, _itemId); + } + _itemId = 0; + _prepsThisItem = 0; + _attempted.Clear(); + _skipped.Clear(); + } + + // ── Tick (pump thread) ────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (!Running) + { + if (_autoRescanAt != 0 && nowMs >= _autoRescanAt) + { + _autoRescanAt = 0; + AutoScan(_bench, nowMs); + } + return; + } + if (_waiting) { Wait(nowMs); return; } + if (nowMs < _nextAt) return; + + if (!C.AllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; } + if (Inv.IsBusy) return; + if (!ActionPacer.MayStart(Host, "Crafting", HealNeed.None, out string why)) { _status = "waiting: " + why; return; } + + if (_itemId == 0) + { + if (_queue.Count == 0) { BatchDone(nowMs); return; } + _itemId = _queue.Dequeue(); + _retries = 0; + } + + var wo = Inv.Cache?[_itemId]; + if (wo == null) { NextItem("gone from the pack"); return; } + if (Inv.IsEquipped(wo)) { NextItem("equipped - skipped"); return; } + + var s = Snapshot(_settings(_bench)); + var facts = Facts(wo); + var plan = TinkerPlanner.Plan(_bench, facts, s, _rows(_bench), + k => _attempted.TryGetValue(k, out int n) ? n : 0) + .Where(st => !_skipped.Contains(TinkerCatalog.Key(st.Row))) + .ToList(); + if (plan.Count == 0) { NextItem($"done ({facts.Tinks} tinks)"); return; } + + var step = plan[0]; + string key = TinkerCatalog.Key(step.Row); + string matName = TinkerCatalog.MaterialName(step.Material); + + var bags = BagsFor(step); + if (bags.Count == 0) + { + if (step.Row.Prepared) Prepare(nowMs, step, key, matName); + else Skip(key, $"no full bag of {matName}"); + return; + } + + int skill = Skill(step.Row.Skill > 0 ? step.Row.Skill : TinkerCatalog.DefaultSkill(_bench)); + var choices = bags.Select(b => + { + double bagWork = TinkerMath.BagWorkmanship(Inv.Int(b, IntWorkmanship), Inv.Int(b, IntNumItemsInMaterial, 1)); + bool fool = TinkerPlanner.IsFoolproof(b.Name); + double? chance = fool ? 1.0 + : step.Row.Origin == TinkerOrigin.Retail && skill > 0 + ? TinkerMath.Chance(step.Material, skill, facts.Workmanship, bagWork, facts.Tinks, + step.Row.Kind == TinkerKind.Imbue, false) + : null; + return new TinkerBagChoice(b.Id, bagWork, chance); + }).ToList(); + + int min = Math.Clamp(s.MinChancePercent, 0, 100); + int pick = TinkerPlanner.SelectBag(choices, min); + if (pick < 0) + { + int best = choices.Max(ch => TinkerMath.Percent(ch.Chance ?? 0)); + Skip(key, $"{matName}: best chance {best}% is under {min}%"); + return; + } + + var bag = bags[pick]; + _stepPercent = choices[pick].Chance is double pc ? TinkerMath.Percent(pc) : -1; + _manual = !(C.AnswerCraftDialog && Host.HasConfirmationAnswers + && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, min, (int)StepTimeoutMs) == 1); + _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; + _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; + + string pctText = _stepPercent >= 0 ? $" ~{_stepPercent}%" : ""; + if (!Host.UseOnFor(unchecked((uint)bag.Id), unchecked((uint)_itemId), "Crafting", + $"{TinkerCatalog.Label(_bench)}: {matName} on {facts.Name}{pctText}", UseKind.Asked)) + { + if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + Retry(nowMs, "the use request didn't go out"); + return; + } + + _step = step; + _bagId = bag.Id; + _bagName = bag.Name ?? matName; + _waiting = true; + _stepAt = nowMs; + _attempted[key] = (_attempted.TryGetValue(key, out int n0) ? n0 : 0) + 1; + string ask = _manual ? " - click Yes in AC's craft dialog" : ""; + SetRow(_itemId, $"applying {matName}{pctText}{ask}"); + _status = $"{facts.Name}: applying {_bagName}{pctText}{ask}"; + } + + /// The full bags that can serve a step (prepared rows: prepared at the chosen tier). + private List BagsFor(TinkerStep step) + => Inv.Items() + .Where(b => b.ObjectClass == AcObjectClass.Salvage + && TinkerPlanner.BagMatches(step, b.Name, Inv.Int(b, MiniRemoteInventory.IntMaterialType), Inv.Uses(b), Tier)) + .ToList(); + + /// + /// No prepared bag: use a raw one on the tier's Ammunition (UB-IT's prep). The wait + /// ends when a prepared bag shows up; the next tick then applies it. + /// + private void Prepare(long nowMs, TinkerStep step, string key, string matName) + { + string tierName = TinkerCatalog.TrinketTiers[Tier]; + if (!C.TrinketPrep) { Skip(key, $"no {tierName} {matName} bag (or tick 'prepare on Ammunition')"); return; } + if (++_prepsThisItem > MaxRetries) { Skip(key, $"{matName}: no {tierName} bag came out of preparing"); return; } + var raw = Inv.Items().FirstOrDefault(b => b.ObjectClass == AcObjectClass.Salvage + && TinkerPlanner.IsRawTrinketBag(step.Material, b.Name, Inv.Int(b, MiniRemoteInventory.IntMaterialType), Inv.Uses(b))); + if (raw == null) { Skip(key, $"no full bag of {matName} to prepare"); return; } + var ammo = Inv.Items().FirstOrDefault(a => !Inv.IsEquipped(a) && TinkerPlanner.IsTierAmmunition(a.Name, Tier)); + if (ammo == null) { Skip(key, $"no {tierName} Ammunition to prepare {matName}"); return; } + + // Preparing is the player's choice (the tick box): any craft dialog it raises is a Yes. + _manual = !(C.AnswerCraftDialog && Host.HasConfirmationAnswers + && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)PrepTimeoutMs) == 1); + _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; + _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; + _step = step; + _prep = true; + if (!Host.UseOnFor(unchecked((uint)raw.Id), unchecked((uint)ammo.Id), "Crafting", + $"{TinkerCatalog.Label(_bench)}: prepare {matName} on {ammo.Name}", UseKind.Asked)) + { + if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + Retry(nowMs, "the prepare request didn't go out"); + return; + } + _bagId = raw.Id; + _bagName = raw.Name ?? matName; + _waiting = true; + _stepAt = nowMs; + SetRow(_itemId, $"preparing {tierName} {matName}"); + _status = $"preparing {_bagName} on {ammo.Name}"; + } + + /// Buffed tinkering skill (0 when the engine can't read it: the server's percent decides). + private int Skill(int skillId) + => Host.HasGetObjectSkill && Host.TryGetObjectSkill(Inv.PlayerId, unchecked((uint)skillId), out int buffed, out _) ? buffed : 0; + + private void Skip(string rowKey, string why) + { + _skipped.Add(rowKey); + SetRow(_itemId, why); + _status = why; + } + + private void Retry(long nowMs, string why) + { + _waiting = false; + string key = TinkerCatalog.Key(_step.Row); + // A preparation never counted as an attempt. + if (!_prep && _attempted.TryGetValue(key, out int n) && n > 0) _attempted[key] = n - 1; + _prep = false; + if (++_retries > MaxRetries) { NextItem("gave up: " + why); _status = why; return; } + _nextAt = nowMs + RetryDelayMs; + _status = $"{why} - retrying ({_retries}/{MaxRetries})"; + } + + private void Finish(string outcome) + { + _waiting = false; + _retries = 0; + _nextAt = Environment.TickCount64 + StepGapMs; + if (!_prep) _usedThisBatch++; + _prep = false; + SetRow(_itemId, outcome); + _status = outcome; + } + + /// The step's row was refused (No, an error, "cannot be used"): drop it for this item. + private void Refuse(string why) + { + _waiting = false; + _prep = false; + Skip(TinkerCatalog.Key(_step.Row), why); + } + + private void Wait(long nowMs) + { + // Engine answer (v81): a No ends the step without using the bag. + if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _) + && seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction) + { + _confSeq = seq; + if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) + { + Refuse($"{TinkerCatalog.MaterialName(_step.Material)}: server chance {pct}% is under the minimum"); + return; + } + if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed) + { + _manual = true; + _status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})"; + } + } + + if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq) + { + _errSeq = es; + if (error == ErrorYoureTooBusy) { Retry(nowMs, "server says busy"); return; } + Refuse($"server refused {TinkerCatalog.MaterialName(_step.Material)} (error 0x{error:X})"); + return; + } + + if (_prep) + { + // Prepared: the tier bag is in the pack (or the raw bag is gone, and the next tick looks again). + if (BagsFor(_step).Count > 0 || Inv.Cache?[_bagId] == null) + { + Finish($"{TinkerCatalog.TrinketTiers[Tier]} {TinkerCatalog.MaterialName(_step.Material)} prepared"); + return; + } + if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : PrepTimeoutMs)) + Retry(nowMs, "the bag wasn't prepared"); + return; + } + + // Every tinker consumes the bag, success or failure: covers server recipes with their own text. + if (Inv.Cache?[_bagId] == null) { Finish($"{_bagName} used"); return; } + + if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs)) + Retry(nowMs, _manual ? "no answer to AC's craft dialog" : "no result from the server"); + } + + /// The craft result lines (never hidden). + public void OnChat(string text) + { + if (!_waiting || string.IsNullOrEmpty(text)) return; + string mat = TinkerCatalog.MaterialName(_step.Material); + if (CannotUse.IsMatch(text)) + { + Refuse(_prep ? $"{mat} can't be prepared on that Ammunition" : $"{mat} can't be used on this item"); + return; + } + // A preparation ends when the prepared bag shows up (Wait), not on a craft line. + if (_prep) return; + if (Applied.IsMatch(text)) Finish($"{mat} applied"); + else if (Failed.IsMatch(text)) Finish($"{mat} failed"); + else if (Foolproof.IsMatch(text)) Finish($"{mat} applied (foolproof)"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs new file mode 100644 index 0000000..4149060 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs @@ -0,0 +1,434 @@ +// CraftingTab.cs - The Mini Remote's universal "Crafting" tab (every world, like Quests and Pets). +// +// UB-IT's crafting benches, one sub-tab each: Armor, Weapons (Melee / Missile / Caster), +// Jewelry, Trinkets and Items tinkering. (Infinite Leaftide's own crafting - chunking / clap, +// split arrows, the Rings inscription chain - belongs in RynthILT.) Every tinker tab has two +// sections: +// * Retail tinkering - stock ACE salvage (TinkerCatalog.Retail), chance from TinkerMath; +// * Server tinkering - the connected server's own salvage, from the plugin that owns it (its +// "RynthServer.Profile" JSON's "salvage" list, MiniRemoteContext.ServerSalvage; RynthILT's on +// Infinite Leaftide), then the player's own rows for this world (CraftingTabState.CustomByWorld). +// With none defined it says so. +// One TinkerRunner works one tab's scan at a time. +using System; +using System.Collections.Generic; +using System.Linq; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.MiniRemote.Crafting; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.MiniRemote; + +internal sealed class CraftingTab +{ + private readonly MiniRemoteContext _ctx; + + public TinkerRunner Runner { get; } + + // Custom-row editor (render thread only) + private int _newMaterial = TinkerCatalog.Steel; + private int _newKind; + private bool _newSlot = true; + private string _newNameMatch = string.Empty; + private string _newNote = string.Empty; + + private static readonly string[] KindLabels = { "Tink (repeatable)", "Imbue (one per item)", "Once (flag recipe)" }; + + public CraftingTab(MiniRemoteContext ctx) + { + _ctx = ctx; + Runner = new TinkerRunner(ctx, RowsFor, SettingsFor); + } + + private CraftingTabState C => _ctx.State.Crafting; + + /// The bench's settings block (created on first use). + private TinkerBenchSettings SettingsFor(TinkerBench bench) + { + var all = C.Benches; + lock (all) + { + string key = bench.ToString(); + if (!all.TryGetValue(key, out var s) || s == null) all[key] = s = new TinkerBenchSettings(); + s.Counts ??= new Dictionary(); + return s; + } + } + + /// The player's rows for the connected world (a copy). + private List CustomRows() + { + string world = _ctx.WorldName; + var map = C.CustomByWorld; + lock (map) + return map.TryGetValue(world, out var list) && list != null ? new List(list) : new List(); + } + + /// Retail + server + custom rows for a bench on this world. + private IReadOnlyList RowsFor(TinkerBench bench) + => TinkerPlanner.Rows(bench, ServerRowsFor(bench), CustomRows()); + + /// The connected server's own salvage for a bench: what its plugin's profile defines. + private IReadOnlyList ServerRowsFor(TinkerBench bench) + => TinkerCatalog.FromServerPlugin(bench, _ctx.ServerSalvage); + + /// The connected server defines salvage for at least one bench. + private bool ServerHasSalvage => _ctx.ServerSalvage.Count > 0; + + // ── Lifecycle (MiniRemoteController) ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) => Runner.Tick(nowMs); + + public void OnChat(string text) => Runner.OnChat(text); + + public void OnLogout() => Runner.OnLogout(); + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + if (!ImGui.BeginTabBar("##crafting")) return; + if (ImGui.BeginTabItem("Armor")) { RenderBench(TinkerBench.Armor); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Weapons")) + { + if (ImGui.BeginTabBar("##craftweapons")) + { + if (ImGui.BeginTabItem("Melee")) { RenderBench(TinkerBench.Melee); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Missile")) { RenderBench(TinkerBench.Missile); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Caster")) { RenderBench(TinkerBench.Caster); ImGui.EndTabItem(); } + ImGui.EndTabBar(); + } + ImGui.EndTabItem(); + } + if (ImGui.BeginTabItem("Jewelry")) { RenderBench(TinkerBench.Jewelry); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Trinkets")) { RenderBench(TinkerBench.Trinkets); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Items")) { RenderBench(TinkerBench.Items); ImGui.EndTabItem(); } + ImGui.EndTabBar(); + } + + private void RenderBench(TinkerBench bench) + { + var s = SettingsFor(bench); + string world = _ctx.WorldName; + bool weapon = bench is TinkerBench.Melee or TinkerBench.Missile or TinkerBench.Caster; + ImGui.PushID((int)bench); + + RenderFilters(s, weapon); + if (bench == TinkerBench.Trinkets) RenderTrinketOptions(); + + if (ImGui.CollapsingHeader("Retail tinkering", ImGuiTreeNodeFlags.DefaultOpen)) + { + var retail = TinkerCatalog.RetailFor(bench); + if (retail.Count == 0) ImGui.TextDisabled("Retail AC has no tinkering for this tab."); + else RenderRows(s, retail, "retail"); + } + + // The server plugin's name when RynthCore has an active server, else the world name. + string server = _ctx.ServerName.Length > 0 ? _ctx.ServerName : world.Length > 0 ? world : "this server"; + string serverTitle = $"Server tinkering - {server}###server"; + if (ImGui.CollapsingHeader(serverTitle, ImGuiTreeNodeFlags.DefaultOpen)) + { + var serverRows = ServerRowsFor(bench); + if (serverRows.Count > 0) + { + RenderRows(s, serverRows, "server"); + if (serverRows.Any(r => !r.UsesTinkSlot && r.AppliedInt == 0)) + ImGui.TextDisabled("Rows without a tink slot don't show on the item: a run applies each once, and items\n" + + "finished this session are left out of later scans (Forget brings them back)."); + } + else if (ServerHasSalvage) + ImGui.TextDisabled("This server doesn't have any dynamic salvage defined for this tab."); + else + ImGui.TextDisabled("This server doesn't have any dynamic salvage defined."); + RenderCustom(bench, s, world); + } + + RenderRun(bench, s); + ImGui.PopID(); + } + + private static void RenderFilters(TinkerBenchSettings s, bool weapon) + { + int min = s.MinChancePercent; + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("Min chance %", ref min, 5)) s.MinChancePercent = Math.Clamp(min, 0, 100); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Skip a salvage whose chance is under this (0 = any).\nRetail chances are worked out ahead; " + + "the server's own percent is checked when it asks."); + ImGui.SameLine(); + int maxT = s.MaxTinks; + ImGui.SetNextItemWidth(90); + if (ImGui.SliderInt("Max tinks", ref maxT, 0, TinkerCatalog.MaxTinks)) s.MaxTinks = maxT; + ImGui.SameLine(); + int minFree = s.MinFreeTinks; + ImGui.SetNextItemWidth(90); + if (ImGui.SliderInt("Min free", ref minFree, 0, TinkerCatalog.MaxTinks)) s.MinFreeTinks = minFree; + bool skipImbued = s.SkipImbued; + if (ImGui.Checkbox("Skip imbued", ref skipImbued)) s.SkipImbued = skipImbued; + if (weapon) + { + ImGui.SameLine(); + bool pierce = s.PierceForCombo; + if (ImGui.Checkbox("Slash/pierce: pierce rend", ref pierce)) s.PierceForCombo = pierce; + ImGui.SameLine(); + bool rendLast = s.RendLast; + if (ImGui.Checkbox("Rend last", ref rendLast)) s.RendLast = rendLast; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Apply the rend after everything else (a Foolproof rend can't fail)."); + } + } + + /// Trinkets: the prepared salvage tier and whether to prepare raw bags on the tier's Ammunition. + private void RenderTrinketOptions() + { + int tier = Math.Clamp(C.TrinketTier, 0, TinkerCatalog.TrinketTiers.Length - 1); + ImGui.SetNextItemWidth(110); + if (ImGui.Combo("Tier", ref tier, TinkerCatalog.TrinketTiers, TinkerCatalog.TrinketTiers.Length)) C.TrinketTier = tier; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Uses bags whose name has this tier (e.g. \"Major\"), made on that tier's Ammunition."); + ImGui.SameLine(); + bool prep = C.TrinketPrep; + if (ImGui.Checkbox("Prepare on Ammunition", ref prep)) C.TrinketPrep = prep; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("With no bag of the tier carried, use a full raw bag on the tier's Ammunition first,\n" + + "then apply the prepared bag."); + ImGui.TextDisabled("Trinkets: compass, goggles, scarab, watch, puzzle box, top (the Jewelry tab leaves them out)."); + } + + /// One ticked count / checkbox per row. + private static void RenderRows(TinkerBenchSettings s, IReadOnlyList rows, string id) + { + if (!ImGui.BeginTable("##rows" + id, 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) return; + ImGui.TableSetupColumn("Use", ImGuiTableColumnFlags.WidthFixed, 80); + ImGui.TableSetupColumn("Salvage", ImGuiTableColumnFlags.WidthFixed, 150); + ImGui.TableSetupColumn("Effect"); + foreach (var row in rows) + { + string key = TinkerCatalog.Key(row); + ImGui.PushID(key); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + CountControl(s, key, row.Kind); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(row.Name); + ImGui.TableNextColumn(); + string slot = row.UsesTinkSlot ? "" : " - no tink slot"; + SafeImGui.TextDisabled(row.Kind == TinkerKind.Imbue ? row.Effect + " (imbue)" : row.Effect + (row.Effect.Contains("tink slot") ? "" : slot)); + ImGui.PopID(); + } + ImGui.EndTable(); + } + + /// Tinks: how many (0-10); imbues and one-shot recipes: on/off. + private static void CountControl(TinkerBenchSettings s, string key, TinkerKind kind) + { + int count; + lock (s.Counts) count = s.Counts.TryGetValue(key, out int c) ? c : 0; + if (kind == TinkerKind.Tink) + { + ImGui.SetNextItemWidth(70); + if (ImGui.SliderInt("##n", ref count, 0, TinkerCatalog.MaxTinks)) SetCount(s, key, count); + } + else + { + bool on = count > 0; + if (ImGui.Checkbox("##on", ref on)) SetCount(s, key, on ? 1 : 0); + } + } + + private static void SetCount(TinkerBenchSettings s, string key, int count) + { + lock (s.Counts) + { + if (count <= 0) s.Counts.Remove(key); + else s.Counts[key] = count; + } + } + + /// The player's own rows for this world and bench, plus the add form. + private void RenderCustom(TinkerBench bench, TinkerBenchSettings s, string world) + { + ImGui.Spacing(); + ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Your salvage for this server"); + if (world.Length == 0) { ImGui.TextDisabled("Log in to add rows for this server."); return; } + + var mine = CustomRows().Where(c => c.Bench == (int)bench).ToList(); + var rows = TinkerPlanner.Rows(bench, null, mine).Where(r => r.Origin == TinkerOrigin.Custom).ToList(); + if (rows.Count == 0) ImGui.TextDisabled("None yet."); + for (int i = 0; i < rows.Count; i++) + { + var row = rows[i]; + var src = mine[i]; + string key = TinkerCatalog.Key(row); + ImGui.PushID("custom" + i); + CountControl(s, key, row.Kind); + ImGui.SameLine(); + string kind = row.Kind switch { TinkerKind.Imbue => "imbue", TinkerKind.Once => "once", _ => "tink" }; + string extra = (row.UsesTinkSlot ? "" : ", no tink slot") + (row.NameMatch.Length > 0 ? $", bag name has \"{row.NameMatch}\"" : ""); + ImGui.TextUnformatted($"{row.Name} ({kind}{extra}) - {row.Effect}"); + ImGui.SameLine(); + if (ImGui.SmallButton("Remove")) + { + var victim = src; + _ctx.Post(() => + { + var map = C.CustomByWorld; + lock (map) + if (map.TryGetValue(world, out var list) && list != null) list.Remove(victim); + }); + } + ImGui.PopID(); + } + + // Add form + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##newmat", TinkerCatalog.MaterialName(_newMaterial))) + { + foreach (var (mid, name) in TinkerCatalog.MaterialNames.OrderBy(m => m.Name)) + if (ImGui.Selectable(name, mid == _newMaterial)) _newMaterial = mid; + ImGui.EndCombo(); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(150); + ImGui.Combo("##newkind", ref _newKind, KindLabels, KindLabels.Length); + ImGui.SameLine(); + ImGui.Checkbox("Uses a tink slot", ref _newSlot); + ImGui.SetNextItemWidth(150); + ImGui.InputTextWithHint("##newmatch", "bag name contains (optional)", ref _newNameMatch, 64); + ImGui.SameLine(); + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint("##newnote", "effect note", ref _newNote, 96); + ImGui.SameLine(); + if (ImGui.SmallButton("Add")) + { + var add = new CustomTinker + { + Bench = (int)bench, + Material = _newMaterial, + Imbue = _newKind == 1, + Once = _newKind == 2, + UsesTinkSlot = _newSlot, + NameMatch = _newNameMatch.Trim(), + Note = _newNote.Trim(), + }; + _ctx.Post(() => + { + var map = C.CustomByWorld; + lock (map) + { + if (!map.TryGetValue(world, out var list) || list == null) map[world] = list = new List(); + list.Add(add); + } + }); + _newNote = string.Empty; + } + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Adds a row for this server only. Its chance isn't known ahead:\nthe server's own percent decides (Min chance %)."); + } + + /// Scan / Start / Stop, the shared run options and the scanned rows. + private void RenderRun(TinkerBench bench, TinkerBenchSettings s) + { + ImGui.Separator(); + bool canAnswer = _ctx.Host.HasConfirmationAnswers; + bool answer = C.AnswerCraftDialog && canAnswer; + ImGui.BeginDisabled(!canAnswer); + if (ImGui.Checkbox("Answer AC's craft dialog", ref answer)) C.AnswerCraftDialog = answer; + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip(canAnswer + ? "Says Yes for you only when the server's chance reaches Min chance %, else No." + : "Needs RynthCore engine API v81: until then click Yes in AC's dialog yourself."); + ImGui.SameLine(); + int batch = C.BatchSize; + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("Batch", ref batch, 5)) C.BatchSize = Math.Clamp(batch, 1, 100); + ImGui.SameLine(); + bool combat = C.AllowInCombat; + if (ImGui.Checkbox("Allow in combat mode", ref combat)) C.AllowInCombat = combat; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting outside peace mode."); + + bool autoNext = C.AutoNextBatch; + if (ImGui.Checkbox("Auto next batch", ref autoNext)) C.AutoNextBatch = autoNext; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("When a batch finishes, scan the next items (finished ones are left out).\n" + + "Stops after a batch that used no bag."); + ImGui.SameLine(); + ImGui.BeginDisabled(!autoNext); + bool autoStart = C.AutoStartNextBatch; + if (ImGui.Checkbox("and start it", ref autoStart)) C.AutoStartNextBatch = autoStart; + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Start the next batch without asking again (off: press Start yourself)."); + ImGui.EndDisabled(); + int doneCount = Runner.DoneCount(bench); + if (doneCount > 0) + { + ImGui.SameLine(); + SafeImGui.TextDisabled($"{doneCount} finished this session"); + ImGui.SameLine(); + ImGui.BeginDisabled(Runner.Running); + if (ImGui.SmallButton("Forget")) _ctx.Post(() => Runner.ForgetDone(bench)); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Let finished items show in scans again (server rows that don't show on the item could go on twice)."); + } + + bool running = Runner.Running; + bool mine = Runner.ScannedBench == (int)bench; + ImGui.BeginDisabled(running); + if (ImGui.Button("Scan")) _ctx.Post(() => Runner.Scan(bench)); + ImGui.SameLine(); + ImGui.BeginDisabled(!mine || Runner.Rows.Length == 0); + if (ImGui.Button("Start")) + { + int n = Runner.Rows.Length; + string answerText = C.AnswerCraftDialog && canAnswer + ? (s.MinChancePercent > 0 ? $"RynthAi answers AC's dialog: Yes at {s.MinChancePercent}% or better." : "RynthAi answers Yes to AC's dialog.") + : "AC asks you to confirm every craft."; + _ctx.Confirm($"{TinkerCatalog.Label(bench)} tinkering", + $"Apply the planned salvage to {n} item(s)?\n\nTinkering can fail, and every attempt uses the bag and a tink slot.\n{answerText}", + () => Runner.Start(bench), "Start"); + } + ImGui.EndDisabled(); + ImGui.EndDisabled(); + ImGui.SameLine(); + ImGui.BeginDisabled(!running); + if (ImGui.Button("Stop")) _ctx.Post(() => Runner.Stop("stopped by player")); + ImGui.EndDisabled(); + ImGui.SameLine(); + if (running && Runner.Bench != bench) + SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, $"{TinkerCatalog.Label(Runner.Bench)} is running"); + else + SafeImGui.TextDisabled(Runner.Status); + + if (!mine) return; + var scanned = Runner.Rows; + if (scanned.Length == 0) return; + if (!ImGui.BeginTable("##scan", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.ScrollY, + new System.Numerics.Vector2(0, 200))) + return; + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("Item"); + ImGui.TableSetupColumn("Tinks", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableSetupColumn("Work", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableSetupColumn("Plan"); + ImGui.TableSetupColumn("Status"); + ImGui.TableHeadersRow(); + foreach (var r in scanned) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Imbued ? r.Name + " *" : r.Name); + if (r.Imbued && ImGui.IsItemHovered()) ImGui.SetTooltip("Imbued"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Tinks.ToString()); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Workmanship.ToString("0")); + ImGui.TableNextColumn(); + SafeImGui.TextWrapped(r.Plan); + ImGui.TableNextColumn(); + SafeImGui.TextWrapped(r.Status); + } + ImGui.EndTable(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/IltClient.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/IltClient.cs index 6674f07..b4e55ce 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/IltClient.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/IltClient.cs @@ -28,7 +28,8 @@ internal sealed unsafe class IltClient private readonly RynthCoreHost _host; private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found - private long _checkedAt = long.MinValue; + 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(); @@ -39,8 +40,8 @@ internal sealed unsafe class IltClient { long now = Environment.TickCount64; var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table); - if (t != null && t->Version >= 1 && now - _checkedAt < RecheckMs) return; - if (t == null && now - _checkedAt < RecheckMs) return; + 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) @@ -55,7 +56,18 @@ internal sealed unsafe class IltClient public void Reset() { System.Threading.Volatile.Write(ref _table, IntPtr.Zero); - _checkedAt = long.MinValue; + _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 diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs index b47277a..532bd83 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs @@ -10,7 +10,9 @@ // confirmed action is then posted). using System; using System.Collections.Concurrent; +using System.Collections.Generic; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi.MiniRemote; @@ -59,6 +61,47 @@ internal sealed class MiniRemoteContext /// Logged-in character name (resolved at login). public string CharName = string.Empty; + /// The connected world's name ("" before login or on an engine without it); keys the Crafting tab's custom rows. + public string WorldName + => Host.HasGetWorldName && Host.TryGetWorldName(out string world) ? (world ?? string.Empty).Trim() : string.Empty; + + // ── Active server (RynthCore's verdict and its server plugin's profile) ───────────────────── + + /// What the render thread reads about the active server: replaced whole, never edited. + private sealed record ServerView(string Name, IReadOnlyList Salvage) + { + public static readonly ServerView None = new(string.Empty, Array.Empty()); + } + + private readonly ServerStateClient _server = new(); + private int _serverRevision = -1; + private volatile ServerView _serverView = ServerView.None; + + /// The active server's display name from RynthCore ("" when none is active or the engine is pre-v86). + public string ServerName => _serverView.Name; + + /// The active server plugin's own tinkering salvage (empty when it defines none). Any thread. + public IReadOnlyList ServerSalvage => _serverView.Salvage; + + /// Pump thread: polls RynthCore's server state (cheap until due) and rebuilds the view when it changed. + public void PollServer(long now) + { + _server.Poll(Host, now); + if (_server.Revision == _serverRevision) return; + _serverRevision = _server.Revision; + EngineServerState? st = _server.State; + string name = st != null && st.HasActive ? st.ActiveName : string.Empty; + _serverView = new ServerView(name, ServerSalvageView.ParseList(_server.ProfileJson)); + } + + /// Logout: forget the server; the next login polls fresh. + public void ClearServer() + { + _server.Clear(); + _serverRevision = -1; + _serverView = ServerView.None; + } + /// /// Shows the Mini Remote on one of its tabs (tab id; set by the controller). Any thread: it /// only records the tab and the show request, which the next frame applies. @@ -115,32 +158,35 @@ internal static class MiniRemoteTabs { /// The Remote tab (the remote itself). public const string Remote = ""; - public const string Quests = "quests"; public const string Pets = "pets"; + public const string Crafting = "crafting"; - /// The universal tabs in tab-bar order (after Remote, before RynthILT's tabs). - public static readonly string[] Universal = { Quests, Pets }; + /// + /// The universal tabs in tab-bar order (after Remote, before RynthILT's tabs). The Quests tab + /// moved to RynthOracle on 2026-10-13 (MiniRemoteController.QuestsMovedText). + /// + public static readonly string[] Universal = { Pets, Crafting }; public static string Label(string id) => id switch { - Quests => "Quests", Pets => "Pets", + Crafting => "Crafting", _ => "Remote", }; - /// "quests" / "quest" / "pets" / "pet" → the tab id; null for anything else. + /// "pets" / "crafting" (and their short forms) to the tab id; null for anything else. public static string? Parse(string? text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch { - "quests" or "quest" => Quests, "pets" or "pet" => Pets, + "crafting" or "craft" or "tinker" or "tinkering" => Crafting, _ => null, }; /// Size of a universal tab's body (the old section window's default size). public static System.Numerics.Vector2 Size(string id) => id switch { - Quests => new System.Numerics.Vector2(700, 500), Pets => new System.Numerics.Vector2(560, 580), + Crafting => new System.Numerics.Vector2(680, 600), _ => new System.Numerics.Vector2(520, 440), }; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs index a5f1b7f..919e7cf 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs @@ -1,15 +1,17 @@ -// MiniRemoteController.cs — The Mini Remote's universal tabs (Quests, Pets), the VTank .usd +// MiniRemoteController.cs — The Mini Remote's universal tabs (Pets, Crafting), the VTank .usd // importer and the "/ra hub|quests|pets" commands. The universal half of the ILT Hub's // IltHubController (SilentKelpie's ILT Hub; its Infinite Leaftide half went to the RynthILT plugin -// 2026-10-13). +// 2026-10-13). The Quests tab and its favorites HUD moved to RynthOracle (Quests tab, Quest Timers +// window) on 2026-10-13; "/ra quests [refresh]" (the meta tracker's quiet /myquests, which +// RynthILT's Temple tracker also asks for through RynthAi.Hub QuestRefresh) stays here. // // RynthAiPlugin creates one controller per login session and forwards: // OnTick → Tick() (pump thread) // OnChatWindowText → OnChat() (pump thread) -// OnRender → Render() (render thread: quest favorites HUD, confirmations) +// OnRender → Render() (render thread: confirmations) // /ra hub ..., /ra quests ..., /ra pets ..., /ra guardian ..., /ra bounty ... → HandleCommand() // OnLogout / teardown → OnLogout() -// The Mini Remote's tab bar (MiniRemoteHud) shows Remote, then Quests and Pets (here, every +// The Mini Remote's tab bar (MiniRemoteHud) shows Remote, then Pets and Crafting (here, every // world), then RynthILT's Infinite Leaftide tabs (IltClient). The ILT verbs ("/ra hub bank", // "/ra hub attr ...", "/ra guardian ...", "/ra bounty", "/ra hub open banking", ...) are forwarded // to RynthILT (RynthILT.Hub Command); without RynthILT they say so. @@ -28,14 +30,23 @@ internal sealed class MiniRemoteController { private const long SaveIntervalMs = 5000; private const string ConfirmPopupId = "Confirm##mrconfirm"; + /// The server answers one /myquests a minute; quiet refreshes keep to that. + private const long QuestRefreshCooldownMs = 60_000; + + /// Where the quest UI went (chat reply for the retired "/ra quests" verbs and tab names). + public const string QuestsMovedText = + "[Mini Remote] Quests moved to RynthOracle: /ro (Quests tab: timers, tracking, rewards), /ro timers (Quest Timers window)."; private readonly MiniRemoteContext _ctx; + private readonly Func _quests; private long _lastSaveAt; + private long _lastQuestRefreshAt = -QuestRefreshCooldownMs; private MiniRemoteConfirm? _confirm; // render thread private bool _confirmOpened; - public QuestsTab Quests { get; } public PetsTab Pets { get; } + /// The Crafting tab (tinker benches and server salvage; any world). SilentKelpie's. + public CraftingTab Crafting { get; } public VTankUsdImporter Usd { get; } public MiniRemoteController(RynthCoreHost host, string charFolder, Func cache, @@ -45,8 +56,9 @@ internal sealed class MiniRemoteController var state = store.Load(); var inventory = new MiniRemoteInventory(host, cache); _ctx = new MiniRemoteContext(host, state, store, inventory, ilt, settings) { SaveCombatSettings = saveCombatSettings }; - Quests = new QuestsTab(_ctx, quests); + _quests = quests; Pets = new PetsTab(_ctx); + Crafting = new CraftingTab(_ctx); Usd = new VTankUsdImporter(_ctx); _ctx.ShowTab = tab => MiniRemoteTabCommand?.Invoke(tab, "show"); } @@ -88,8 +100,12 @@ internal sealed class MiniRemoteController { long now = MiniRemoteContext.NowMs; _ctx.DrainPosted(); + try { _ctx.PollServer(now); } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "MiniRemoteContext.PollServer"); } try { Pets.Tick(now); } catch (Exception ex) { RynthLog.Exception(LogCat.Pets, ex, "PetsTab.Tick"); } + try { Crafting.Tick(now); } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "CraftingTab.Tick"); } if (now - _lastSaveAt >= SaveIntervalMs) { _lastSaveAt = now; @@ -103,6 +119,8 @@ internal sealed class MiniRemoteController if (string.IsNullOrEmpty(text)) return; try { Pets.OnChat(text.TrimEnd('\r', '\n')); } catch (Exception ex) { RynthLog.Exception(LogCat.Pets, ex, "PetsTab.OnChat"); } + try { Crafting.OnChat(text.TrimEnd('\r', '\n')); } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "CraftingTab.OnChat"); } } /// Logout / teardown: stop the pet automation and flush to disk. @@ -110,29 +128,47 @@ internal sealed class MiniRemoteController { try { Pets.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Pets, ex, "PetsTab.OnLogout"); } + try { Crafting.OnLogout(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "CraftingTab.OnLogout"); } + _ctx.ClearServer(); _ctx.Store.SaveIfDirty(_ctx.State); } - /// "Refresh /myquests" for RynthILT's Temple tracker (RynthAi.Hub QuestRefresh). Pump thread. - public string RefreshQuests() => Quests.RefreshQuests(); + /// + /// A quiet /myquests refresh of the meta tracker with a 60 s client-side cooldown (the server's + /// throttle): "/ra quests refresh" and RynthILT's Temple tracker (RynthAi.Hub QuestRefresh). + /// Pump thread. Returns the chat reply. + /// + public string RefreshQuests() + { + 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."; + long now = MiniRemoteContext.NowMs; + if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs) + return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute)."; + _lastQuestRefreshAt = now; + t.Refresh(quiet: true); + return "Refreshing quests..."; + } // ── Rendering (render thread) ─────────────────────────────────────────── - /// One of the Mini Remote's own tabs ("quests", "pets"); false for anything else. + /// One of the Mini Remote's own tabs ("pets", "crafting"); false for anything else. public bool RenderTab(string id) { switch (id) { - case MiniRemoteTabs.Quests: Quests.RenderTab(); return true; case MiniRemoteTabs.Pets: Pets.Render(); return true; + case MiniRemoteTabs.Crafting: Crafting.Render(); return true; default: return false; } } - /// The floating extras: the quest favorites HUD and the confirmation modal. + /// The floating extras: the confirmation modal. public void Render() { - Quests.RenderFloatingWindows(); RenderConfirm(); } @@ -154,9 +190,9 @@ internal sealed class MiniRemoteController bool keepOpen = true; if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize)) { - ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _confirm.Title); + SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, _confirm.Title); ImGui.Separator(); - ImGui.TextWrapped(_confirm.Message); + SafeImGui.TextWrapped(_confirm.Message); ImGui.Spacing(); if (ImGui.Button(_confirm.YesLabel + "##mryes", new Vector2(120, 0))) { @@ -184,35 +220,20 @@ internal sealed class MiniRemoteController // ── Commands ──────────────────────────────────────────────────────────── /// - /// "/ra hub [show|hide|toggle|open quests|pets [show|hide|toggle]|tab quests|pets|remote]", - /// "/ra quests [refresh|check <regex>|window|favhud]", "/ra pets [show|hide|toggle]"; every - /// other "/ra hub ..." verb, "/ra guardian ..." and "/ra bounty|bounties|bountys ..." go to - /// RynthILT. Returns false if not handled. + /// "/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. /// public bool HandleCommand(string verb, string[] args) { if (verb.Equals("quests", StringComparison.OrdinalIgnoreCase)) { string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "refresh"; - string mode = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle"; - var qs = _ctx.State.Quests; - switch (sub) - { - case "check" when args.Length > 1: - Quests.CheckCommand(string.Join(" ", args.Skip(1))); - break; - case "window": - OpenTab(MiniRemoteTabs.Quests, mode); - break; - case "favhud": - case "favorites": - qs.ShowQuestFavoritesHud = ResolveToggle(mode, qs.ShowQuestFavoritesHud); - _ctx.Chat(qs.ShowQuestFavoritesHud ? "[Mini Remote] Quest favorites HUD shown." : "[Mini Remote] Quest favorites HUD hidden."); - break; - default: - _ctx.Chat("[Mini Remote] " + Quests.RefreshQuests()); - break; - } + if (sub == "refresh") _ctx.Chat("[Mini Remote] " + RefreshQuests()); + else _ctx.Chat(QuestsMovedText); return true; } if (verb.Equals("pets", StringComparison.OrdinalIgnoreCase)) @@ -227,6 +248,20 @@ internal sealed class MiniRemoteController if (!ilt) { string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "toggle"; + // "/ra hub open|tab quests": the tab is RynthOracle's window now. + if (cmd is "open" or "tab" && args.Length > 1 && IsQuestsName(args[1])) + { + _ctx.Chat(QuestsMovedText); + return true; + } + // "/ra hub open|tab character": the Character tab left the Mini Remote (2026-10-13); + // HudController.HandleTabCommand opens RynthOracle's Character tab. + if (cmd is "open" or "tab" && args.Length > 1 && Huds.MovedTabs.CommandFor(args[1]) != null) + { + string? reply = MiniRemoteTabCommand?.Invoke(args[1].Trim().ToLowerInvariant(), "show"); + if (cmd == "open" && reply != null) _ctx.Chat("[Mini Remote] " + reply); + return true; + } switch (cmd) { case "show": @@ -235,6 +270,9 @@ 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); + return true; case "open" when args.Length > 1 && MiniRemoteTabs.Parse(args[1]) is { } openTab: OpenTab(openTab, args.Length > 2 ? args[2] : "toggle"); return true; @@ -261,14 +299,46 @@ internal sealed class MiniRemoteController private void PrintHelp() { - _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open quests|pets [show|hide|toggle]"); - _ctx.Chat("[Mini Remote] /ra quests [refresh|check |window [show|hide]|favhud [show|hide]] /ra pets [show|hide]"); + _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 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] 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. + /// + private void OpenBreeding(string cmd) + { + bool offered = Pets.BreedingOffered; + if (offered) Pets.SelectBreeding(); + 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"); } private static bool IsRemoteTabName(string text) => text.Equals("remote", StringComparison.OrdinalIgnoreCase) || text.Length == 0; + /// "quests" / "quest": the retired Quests tab's names. + 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) @@ -281,12 +351,4 @@ internal sealed class MiniRemoteController string reply = MiniRemoteTabCommand?.Invoke(tab, mode) ?? "The Mini Remote is not available yet."; _ctx.Chat("[Mini Remote] " + reply); } - - /// "show"/"on" → true, "hide"/"off" → false, anything else flips . - private static bool ResolveToggle(string mode, bool current) => mode switch - { - "show" or "on" or "true" or "1" => true, - "hide" or "off" or "false" or "0" => false, - _ => !current, - }; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs index ff02812..a155f28 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs @@ -28,6 +28,10 @@ internal sealed class MiniRemoteInventory // ── Property ids ──────────────────────────────────────────────────────── public const uint IntStackSize = 12; public const uint IntStructure = 92; + // Crafting tab (tinker runs): how often an item was tinkered, its imbue, a salvage bag's material. + 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; @@ -91,6 +95,17 @@ internal sealed class MiniRemoteInventory /// Remaining uses on a structure item (essences, kits, salvage bags). public int Uses(WorldObject wo) => Int(wo, IntStructure, 0); + /// A bool property of an object (false when unknown or the engine can't read it). + public bool Bool(WorldObject wo, uint stype) + => _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v; + + /// Stack size (1 for a non-stack). + public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1)); + + /// Worn or wielded by the player. + public bool IsEquipped(WorldObject wo) + => wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId); + public bool HasAppraisal(WorldObject wo) => !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs index 69ce339..3aa80c7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs @@ -21,10 +21,70 @@ public sealed class MiniRemoteState public int SchemaVersion = 1; public PetTabState Pet = new(); public QuestsTabState Quests = new(); + /// The Crafting tab (tinker benches); the ILT Hub's Crafting before. + public CraftingTabState Crafting = new(); /// Last VTank .usd file the importer read (the ILT Hub's Gear.LastUsdPath before). public string LastUsdPath = string.Empty; } +/// The Crafting tab: one settings block per tinker bench, plus per-server custom salvage. +public sealed class CraftingTabState +{ + /// Bench settings keyed by the bench name (TinkerBench: Armor, Melee, Missile, Caster, Jewelry, Items, Trinkets). + public Dictionary Benches = new(); + /// The player's extra salvage rows, keyed by world name (custom shards' own recipes). + public Dictionary> CustomByWorld = new(); + /// Answer the server's craft-chance dialog for the runner (engine API v85). + public bool AnswerCraftDialog = true; + /// Items per scan (UB-IT's 20). + public int BatchSize = 20; + /// Apply even in combat mode (servers with allow_combat_mode_crafting). + public bool AllowInCombat; + /// When a batch finishes, scan the next one (items finished this session are left out). + public bool AutoNextBatch; + /// ...and start it without asking again. + public bool AutoStartNextBatch; + /// Prepared salvage tier: 0 Minor, 1 Moderate, 2 Major (TinkerCatalog.TrinketTiers). + public int TrinketTier; + /// Prepare a raw bag on the tier's Ammunition when no prepared bag is carried. + public bool TrinketPrep; + // "RingRuns" (the Rings chain, now left to RynthILT) may still be in older files: it is ignored. +} + +/// One tinker bench's choices. +public sealed class TinkerBenchSettings +{ + /// Row key (TinkerCatalog.Key: r/p/c + material id) to how many times (imbues and flags: 0 or 1). + public Dictionary Counts = new(); + /// Skip a step whose chance is under this percent (0 = any chance). + public int MinChancePercent; + /// Only items with at most this many tinks. + public int MaxTinks = 9; + /// Only items with at least this many free tink slots (0 = no filter). + public int MinFreeTinks; + public bool SkipImbued; + /// Slash/pierce weapons take the pierce rend (Black Garnet) instead of slash (Imperial Topaz). + public bool PierceForCombo; + /// The damage-type rend goes after every other step (UB-IT's "Foolproof rend last"). + public bool RendLast; +} + +/// A salvage row the player added for one server. +public sealed class CustomTinker +{ + /// TinkerBench as an int. + public int Bench; + /// MaterialType of the salvage. + public int Material; + public bool Imbue; + /// Once per item (a flag-style recipe) rather than a repeatable tink. + public bool Once; + public bool UsesTinkSlot = true; + /// The bag's name must contain this (bags that share another salvage's material id). + public string NameMatch = string.Empty; + public string Note = string.Empty; +} + /// The Pets tab's settings (the ILT Hub's IltPetState, without the ILT /pets and /shinies logs). public sealed class PetTabState { @@ -69,7 +129,11 @@ public sealed class PetAssignment public int Kind; } -/// The Quests tab's settings (the quest fields of the ILT Hub's IltCharacterState). +/// +/// The retired Quests tab's settings (the quest fields of the ILT Hub's IltCharacterState). The tab +/// moved to RynthOracle on 2026-10-13 (tracking and rewards live in its per-character quest book); +/// the fields stay so existing miniremote.json files load and keep what they recorded. +/// public sealed class QuestsTabState { /// Quest Tracker search box contents. @@ -90,6 +154,8 @@ public sealed class LegacyIltHubFile /// The ILT Hub's IltCharacterState: its quest fields have QuestsTabState's names. public QuestsTabState? Character; public LegacyIltGear? Gear; + /// The ILT Hub's Crafting tab (build-comp-10-11 hosted it in RynthAi): same field names. + public CraftingTabState? Crafting; } public sealed class LegacyIltGear @@ -149,6 +215,7 @@ internal sealed class MiniRemoteStore { Pet = old.Pet ?? new PetTabState(), Quests = old.Character ?? new QuestsTabState(), + Crafting = old.Crafting ?? new CraftingTabState(), LastUsdPath = old.Gear?.LastUsdPath ?? string.Empty, }; Normalize(s); @@ -187,6 +254,11 @@ internal sealed class MiniRemoteStore s.Quests.QuestFilter ??= string.Empty; s.Quests.QuestFavorites ??= new(); s.Quests.QuestFavorites.RemoveAll(string.IsNullOrWhiteSpace); + s.Crafting ??= new CraftingTabState(); + s.Crafting.Benches ??= new(); + s.Crafting.CustomByWorld ??= new(); + s.Crafting.BatchSize = Math.Clamp(s.Crafting.BatchSize, 1, 200); + s.Crafting.TrinketTier = Math.Clamp(s.Crafting.TrinketTier, 0, 2); s.LastUsdPath ??= string.Empty; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs index 4c108b2..da328a7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs @@ -24,6 +24,9 @@ // * 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. // * /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. using System; using System.Collections.Generic; using System.Linq; @@ -694,11 +697,65 @@ 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; + + /// Shows the Breeding sub-tab on the next frame (any thread). + public void SelectBreeding() => _selectBreeding = true; + + /// + /// 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. + /// + public bool BreedingOffered => _ctx.Ilt.IsIltWorld && !_ctx.Ilt.IsOff(RynthIltHub.FeaturePetBreeding); + + /// + /// The Pets tab: the universal roster, and on Infinite Leaftide the Roster | Breeding sub-tabs + /// (Breeding is drawn by RynthILT). + /// public void Render() { var settings = _ctx.Settings; if (settings == null) { ImGui.TextDisabled("Not logged in."); return; } + if (!BreedingOffered) + { + RenderRoster(settings); + return; + } + if (!ImGui.BeginTabBar("##petsub")) return; + if (ImGui.BeginTabItem("Roster##petroster")) + { + RenderRoster(settings); + ImGui.EndTabItem(); + } + ImGuiTabItemFlags breedFlags = _selectBreeding ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None; + _selectBreeding = false; + if (BeginTab(BreedingTabLabel, breedFlags)) + { + // 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."); + ImGui.EndTabItem(); + } + ImGui.EndTabBar(); + } + + private static readonly byte[] BreedingTabLabel = System.Text.Encoding.UTF8.GetBytes("Breeding##petbreeding\0"); + + /// + /// BeginTabItem with flags but no close button (ImGui.NET pairs the flags overload with p_open, + /// which draws an X on the tab). + /// + private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags) + { + fixed (byte* label = labelUtf8Z) + return ImGuiNative.igBeginTabItem(label, null, flags) != 0; + } + + /// The universal roster: types, summons, ILT charms, healing pets and RynthILT's /pets logs. + 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). @@ -742,10 +799,10 @@ internal sealed class PetsTab if (ImGui.IsItemHovered()) ImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device)."); ImGui.SameLine(); if (ImGui.Button("Add sel.")) _ctx.Post(() => AddSelectedAs(summonKind)); - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet."); string active = _uiActivePet; - if (active.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Active summon: " + active); + if (active.Length > 0) SafeImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Active summon: " + active); else ImGui.TextDisabled("Active summon: none"); switch (kind) @@ -775,7 +832,7 @@ internal sealed class PetsTab int resp = S.CosmeticRespawnSeconds; ImGui.SetNextItemWidth(90); if (ImGui.InputInt("Respawn (s)", ref resp)) S.CosmeticRespawnSeconds = Math.Clamp(resp, 5, 600); - ImGui.TextDisabled("Tick one cosmetic pet. Status: " + _cosmeticStatus); + SafeImGui.TextDisabled("Tick one cosmetic pet. Status: " + _cosmeticStatus); break; } } @@ -806,7 +863,7 @@ internal sealed class PetsTab if (rows.Length == 0) { - ImGui.TextDisabled(kind == PetKind.Cosmetic + SafeImGui.TextDisabled(kind == PetKind.Cosmetic ? "No cosmetic pets yet — select an essence in your pack and press Add sel., or right-click a pet in another type." : $"No {KindNames[(int)kind].ToLowerInvariant()} pet essences carried."); return; @@ -837,10 +894,10 @@ internal sealed class PetsTab _highlightId = _highlightId == r.Id ? 0 : r.Id; RenderRowContextMenu(r); ImGui.SetCursorPos(start); - ImGui.TextColored(DamageColor(r.DamageType), r.Line1); - ImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2); - if (r.UsesMax > 0 && r.UsesCur == 0) ImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3); - else ImGui.TextDisabled(" " + r.Line3); + SafeImGui.TextColored(DamageColor(r.DamageType), r.Line1); + SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2); + if (r.UsesMax > 0 && r.UsesCur == 0) SafeImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3); + else SafeImGui.TextDisabled(" " + r.Line3); ImGui.TableNextColumn(); if (showArrows && r.Selected) @@ -905,7 +962,7 @@ internal sealed class PetsTab bool en = S.HealingEnabled; if (ImGui.Checkbox("Summon heal pet when health is low", ref en)) S.HealingEnabled = en; string healPet = S.HealPetName; - ImGui.TextDisabled("Heal pet: " + (string.IsNullOrWhiteSpace(healPet) ? "auto (Healing Buddy / Dule box)" : healPet) + SafeImGui.TextDisabled("Heal pet: " + (string.IsNullOrWhiteSpace(healPet) ? "auto (Healing Buddy / Dule box)" : healPet) + " — tick one under Type = Healing."); int thr = S.HealthThresholdPercent; ImGui.SetNextItemWidth(160); @@ -921,6 +978,6 @@ internal sealed class PetsTab int to = S.PetTimeoutSeconds; ImGui.SetNextItemWidth(100); if (ImGui.InputInt("Heal timeout (s)", ref to)) S.PetTimeoutSeconds = Math.Max(5, to); - ImGui.TextDisabled("Status: " + _healStatus); + SafeImGui.TextDisabled("Status: " + _healStatus); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/QuestsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/QuestsTab.cs deleted file mode 100644 index 63fd746..0000000 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/QuestsTab.cs +++ /dev/null @@ -1,301 +0,0 @@ -// QuestsTab.cs — The Mini Remote's Quests tab: the /myquests tracker and the floating favorites HUD. -// Originally SilentKelpie's IltQuests (ILT Hub). The tab is universal (every server has /myquests), -// so it stayed in RynthAi when the ILT Hub went to the RynthILT plugin (2026-10-13); its Quest bonus -// (/qb) list is ACECustom's and moved with RynthILT, which draws it at the top of this tab -// (RynthILT.Hub section "quests-qb") on Infinite Leaftide. -// -// Quest Tracker reuses the meta QuestTracker (the same /myquests cache the meta -// expression engine reads) — it never runs a second parser. Friendly names come from: -// 1. an optional user-supplied quests.xml (\RynthAi\quests.xml), -// 2. the description the server prints in /myquests, -// 3. the raw flag key. -// UB's bundled quests.xml is NOT embedded (no license on UB content). -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Text.RegularExpressions; -using System.Xml; -using ImGuiNET; -using RynthCore.Plugin.RynthAi.LegacyUi; -using RynthCore.Plugin.RynthAi.Meta; -using RynthCore.Install; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthAi.MiniRemote; - -internal sealed class QuestsTab -{ - /// Optional user quest-name file (UB-style or simple key/name XML). - public static readonly string QuestsXmlPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"quests.xml"); - - private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - private const long QuestRefreshCooldownMs = 60_000; - - private readonly MiniRemoteContext _ctx; - private readonly Func _tracker; - private Dictionary _friendlyNames = new(StringComparer.OrdinalIgnoreCase); - private long _lastQuestRefreshAt = -QuestRefreshCooldownMs; - // Render-thread UI state. - private int _questView; // 0 timed, 1 kill tasks, 2 once, 3 all - - public QuestsTab(MiniRemoteContext ctx, Func tracker) - { - _ctx = ctx; - _tracker = tracker; - LoadFriendlyNames(); - } - - public enum QuestKind { Timed, KillTask, Once } - - public static QuestKind Classify(QuestRecord r) - { - if (KillTaskRegex.IsMatch(r.Key) && r.MaxSolves >= 0) return QuestKind.KillTask; - if (r.MaxSolves == 1 && r.Solves <= 1) return QuestKind.Once; - return QuestKind.Timed; - } - - public string FriendlyName(QuestRecord r) - { - if (_friendlyNames.TryGetValue(r.Key, out string? n) && !string.IsNullOrWhiteSpace(n)) return n; - if (!string.IsNullOrWhiteSpace(r.Description)) return r.Description; - return r.Key; - } - - // ── quests.xml (optional) ─────────────────────────────────────────────── - - /// Reads any element carrying a key/flag attribute plus a name/description. - public void LoadFriendlyNames() - { - var map = new Dictionary(StringComparer.OrdinalIgnoreCase); - try - { - if (File.Exists(QuestsXmlPath)) - { - using var reader = XmlReader.Create(QuestsXmlPath, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true }); - while (reader.Read()) - { - if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes) continue; - string? key = null, name = null; - while (reader.MoveToNextAttribute()) - { - string a = reader.Name.ToLowerInvariant(); - if (a is "key" or "flag" or "questflag" or "id") key = reader.Value; - else if (a is "name" or "description" or "title" or "friendlyname") name ??= reader.Value; - } - reader.MoveToElement(); - if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(name)) - map[key.Trim().ToLowerInvariant()] = name.Trim(); - } - } - } - catch (Exception ex) { RynthLog.Exception(LogCat.Quests, ex, "quests.xml load"); } - _friendlyNames = map; - } - - // ── Commands ──────────────────────────────────────────────────────────── - - /// Quiet /myquests refresh with a 60 s client-side cooldown (server throttle). - public string RefreshQuests() - { - RynthLog.Trace(LogCat.Quests, $"RefreshQuests()"); - var t = _tracker(); - if (t == null) return "Quest tracker not ready."; - if (_ctx.Ilt.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)."; - _lastQuestRefreshAt = now; - t.Refresh(quiet: true); - return "Refreshing quests..."; - } - - /// "/ra quests check <regex>" — lists up to 5 matching flags in chat. - public void CheckCommand(string pattern) - { - var t = _tracker(); - if (t == null) { _ctx.Chat("[Mini Remote] Quest tracker not ready."); return; } - Regex rx; - try { rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(200)); } - catch (ArgumentException ex) { _ctx.Chat("[Mini Remote] Bad pattern: " + ex.Message); return; } - - var hits = t.Snapshot().Where(r => rx.IsMatch(r.Key) || rx.IsMatch(FriendlyName(r))).OrderBy(r => r.Key).ToList(); - if (hits.Count == 0) { _ctx.Chat($"[Mini Remote] No quest flags match '{pattern}' ({t.Count} cached)."); return; } - foreach (var r in hits.Take(5)) - _ctx.Chat($"[Mini Remote] {FriendlyName(r)} [{r.Key}] solves {r.Solves}{(r.MaxSolves > 0 ? "/" + r.MaxSolves : "")} - {MiniRemoteText.Duration(r.TimeUntilReady())}"); - if (hits.Count > 5) _ctx.Chat($"[Mini Remote] ...and {hits.Count - 5} more."); - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - /// Quest tracker body, filling the Mini Remote's Quests tab (the table uses the remaining height). - public void RenderQuestTracker() - { - var t = _tracker(); - if (t == null) { ImGui.TextDisabled("Quest tracker not ready."); return; } - if (_ctx.Ilt.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) - { - ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/myquests is disabled on this server."); - return; - } - var cs = _ctx.State.Quests; - - if (ImGui.SmallButton("Refresh##quests")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQuests())); - ImGui.SameLine(); - if (ImGui.SmallButton("Reload quests.xml")) _ctx.Post(LoadFriendlyNames); - ImGui.SameLine(); - ImGui.TextDisabled(t.IsRefreshing ? "refreshing..." : t.LastStatus - + (t.LastRefreshUtc == DateTime.MinValue ? "" : " @ " + t.LastRefreshUtc.ToLocalTime().ToString("t"))); - - string filter = cs.QuestFilter; - ImGui.SetNextItemWidth(220); - if (ImGui.InputTextWithHint("##qfilter", "filter by name or key", ref filter, 64u)) - cs.QuestFilter = filter; - ImGui.SameLine(); - ImGui.RadioButton("Timed", ref _questView, 0); ImGui.SameLine(); - ImGui.RadioButton("Kill tasks", ref _questView, 1); ImGui.SameLine(); - ImGui.RadioButton("Once", ref _questView, 2); ImGui.SameLine(); - ImGui.RadioButton("All", ref _questView, 3); - - bool favOnly = cs.QuestFavoritesOnly; - if (ImGui.Checkbox("Favorites only", ref favOnly)) cs.QuestFavoritesOnly = favOnly; - ImGui.SameLine(); - bool favHud = cs.ShowQuestFavoritesHud; - if (ImGui.Checkbox("Show floating favorites HUD", ref favHud)) cs.ShowQuestFavoritesHud = favHud; - ImGui.SameLine(); - ImGui.TextDisabled("(click * to star a quest)"); - - var favorites = FavoriteSet(); - var rows = t.Snapshot() - .Where(r => favOnly ? favorites.Contains(r.Key) : _questView == 3 || (int)Classify(r) == ViewToKind(_questView)) - .Where(r => filter.Length == 0 || r.Key.Contains(filter, StringComparison.OrdinalIgnoreCase) - || FriendlyName(r).Contains(filter, StringComparison.OrdinalIgnoreCase)) - .OrderBy(r => r.TimeUntilReady()) - .ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase) - .ToArray(); - - if (ImGui.BeginTable("##iltquests", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable, - new Vector2(0, -1))) - { - ImGui.TableSetupScrollFreeze(0, 1); - ImGui.TableSetupColumn("*", ImGuiTableColumnFlags.WidthFixed, 18); - ImGui.TableSetupColumn("Quest"); - ImGui.TableSetupColumn("Solves", ImGuiTableColumnFlags.WidthFixed, 70); - ImGui.TableSetupColumn("Ready", ImGuiTableColumnFlags.WidthFixed, 110); - ImGui.TableSetupColumn("Key"); - ImGui.TableHeadersRow(); - foreach (var r in rows) - { - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - bool starred = favorites.Contains(r.Key); - ImGui.PushStyleColor(ImGuiCol.Text, starred ? FavStarOn : FavStarOff); - if (ImGui.Selectable($"*##fav{r.Key}", false)) - { - string key = r.Key; - _ctx.Post(() => ToggleFavorite(key)); - } - ImGui.PopStyleColor(); - if (ImGui.IsItemHovered()) ImGui.SetTooltip(starred ? "Remove from favorites" : "Add to favorites"); - ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r)); - ImGui.TableNextColumn(); ImGui.TextUnformatted(r.MaxSolves > 0 ? $"{r.Solves}/{r.MaxSolves}" : r.Solves.ToString()); - ImGui.TableNextColumn(); - var left = r.TimeUntilReady(); - if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done"); - else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready"); - else ImGui.TextUnformatted(MiniRemoteText.Duration(left)); - ImGui.TableNextColumn(); ImGui.TextDisabled(r.Key); - } - ImGui.EndTable(); - } - } - - private static int ViewToKind(int view) => view switch { 0 => (int)QuestKind.Timed, 1 => (int)QuestKind.KillTask, _ => (int)QuestKind.Once }; - - // ── Favorites / the Quests tab ────────────────────────────────────────── - - private static readonly Vector4 FavStarOn = new(1.00f, 0.82f, 0.25f, 1f); - private static readonly Vector4 FavStarOff = new(0.45f, 0.48f, 0.52f, 1f); - private const string FavHudPopup = "##questfavhudopts"; - - /// Starred keys as a set (render thread; the list itself is only edited on the pump thread). - private HashSet FavoriteSet() - => new(_ctx.State.Quests.QuestFavorites.ToArray(), StringComparer.OrdinalIgnoreCase); - - /// Stars / unstars a quest flag (pump thread). - private void ToggleFavorite(string key) - { - var list = _ctx.State.Quests.QuestFavorites; - if (list.RemoveAll(k => k.Equals(key, StringComparison.OrdinalIgnoreCase)) == 0) - list.Add(key.ToLowerInvariant()); - } - - /// The floating favorites HUD (the tracker itself is the Mini Remote's Quests tab). Called every frame. - public void RenderFloatingWindows() - { - var cs = _ctx.State.Quests; - if (cs.ShowQuestFavoritesHud) RenderFavoritesHud(cs); - } - - /// The Mini Remote's Quests tab: the quest bonus (collapsed; RynthILT's, ILT only), then the tracker filling the rest. - public void RenderTab() - { - // The tab is universal (/myquests); the quest bonus list (/qb) is ILT's and RynthILT's. - _ctx.Ilt.RenderSection(RynthIltHub.SectionQuestBonus); - RenderQuestTracker(); - } - - /// Compact always-on list of starred quests and when each is ready. - private void RenderFavoritesHud(QuestsTabState cs) - { - var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar - | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav; - if (cs.QuestFavoritesHudLocked) flags |= ImGuiWindowFlags.NoMove; - ImGui.SetNextWindowPos(new Vector2(260, 120), ImGuiCond.FirstUseEver); - ImGui.SetNextWindowBgAlpha(0.55f); - if (!ImGui.Begin("Quest favorites##iltquestfavhud", flags)) { ImGui.End(); return; } - - ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Quest favorites"); - var t = _tracker(); - var favorites = FavoriteSet(); - if (t == null || favorites.Count == 0) - { - ImGui.TextDisabled(t == null ? "Quest tracker not ready." : "No favorites yet - star quests in the tracker."); - } - else - { - var rows = t.Snapshot().Where(r => favorites.Contains(r.Key)) - .OrderBy(r => r.TimeUntilReady()).ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase).ToArray(); - if (rows.Length == 0) ImGui.TextDisabled("Starred quests not in /myquests yet."); - if (ImGui.BeginTable("##questfavrows", 2, ImGuiTableFlags.SizingFixedFit)) - { - foreach (var r in rows) - { - ImGui.TableNextRow(); - ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r)); - ImGui.TableNextColumn(); - var left = r.TimeUntilReady(); - if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done"); - else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready"); - else ImGui.TextUnformatted(MiniRemoteText.Duration(left)); - } - ImGui.EndTable(); - } - } - - if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(FavHudPopup); - if (ImGui.BeginPopup(FavHudPopup)) - { - bool locked = cs.QuestFavoritesHudLocked; - if (ImGui.Checkbox("Lock position", ref locked)) cs.QuestFavoritesHudLocked = locked; - if (ImGui.MenuItem("Open quest tracker")) _ctx.ShowTab?.Invoke(MiniRemoteTabs.Quests); - if (ImGui.MenuItem("Refresh /myquests")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQuests())); - if (ImGui.MenuItem("Hide favorites HUD")) cs.ShowQuestFavoritesHud = false; - ImGui.EndPopup(); - } - ImGui.End(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs index 24c645f..2fd8e2a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/VTankUsdImporter.cs @@ -23,6 +23,7 @@ using System.Linq; using ImGuiNET; using RynthCore.Loot; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.MiniRemote; @@ -338,10 +339,10 @@ internal sealed class VTankUsdImporter ImGui.TextUnformatted($"{plan.Monsters.Count} monster rules, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables"); if (ImGui.TreeNode("Preview details")) { - foreach (var m in plan.Monsters.Take(50)) ImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}"); - foreach (var w in plan.Weapons) ImGui.BulletText($"Weapon {w.Name} [{w.Element}]"); - foreach (var c in plan.Consumables) ImGui.BulletText($"{c.Type}: {c.Name}"); - foreach (var n in plan.Notes.Take(30)) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, n); + foreach (var m in plan.Monsters.Take(50)) SafeImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}"); + foreach (var w in plan.Weapons) SafeImGui.BulletText($"Weapon {w.Name} [{w.Element}]"); + foreach (var c in plan.Consumables) SafeImGui.BulletText($"{c.Type}: {c.Name}"); + foreach (var n in plan.Notes.Take(30)) SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, n); ImGui.TreePop(); } if (ImGui.Button("Apply import...")) @@ -349,6 +350,6 @@ internal sealed class VTankUsdImporter $"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced.", Apply, "Import"); } - if (_status.Length > 0) ImGui.TextWrapped(_status); + if (_status.Length > 0) SafeImGui.TextWrapped(_status); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs index 8b98a0c..b5dd1b5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs @@ -16,6 +16,7 @@ using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; @@ -245,11 +246,11 @@ internal sealed class NavOverlayRenderer var route = _settings.CurrentRoute; var pts = route.Points; string name = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "(unsaved)" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath); - ImGui.TextColored(new Vector4(1f, 0.85f, 0.3f, 1f), $"{name} [{route.RouteType}]"); + SafeImGui.TextColored(new Vector4(1f, 0.85f, 0.3f, 1f), $"{name} [{route.RouteType}]"); if (_settings.IsRecordingNav) { ImGui.SameLine(); - ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 1f), $"REC +{_trail.RecordedCount}"); + SafeImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 1f), $"REC +{_trail.RecordedCount}"); } int idx = _settings.ActiveNavIndex; @@ -258,21 +259,21 @@ internal sealed class NavOverlayRenderer var p = pts[idx]; bool travel = p.Type == NavPointType.Point; ImGui.BeginGroup(); - ImGui.Text($"WP {idx}/{pts.Count - 1} {TypeLabel(p)}"); + SafeImGui.Text($"WP {idx}/{pts.Count - 1} {TypeLabel(p)}"); if (travel) { double yd = NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW); double dz = (p.Z * NavCoordinateHelper.NavZScale) - f.Pz; - ImGui.Text(Math.Abs(dz) >= 3 ? $"{yd:F1} yd ({(dz > 0 ? "up" : "down")} {Math.Abs(dz):F0})" : $"{yd:F1} yd"); + SafeImGui.Text(Math.Abs(dz) >= 3 ? $"{yd:F1} yd ({(dz > 0 ? "up" : "down")} {Math.Abs(dz):F0})" : $"{yd:F1} yd"); } else { - ImGui.TextDisabled(p.ToString()); + SafeImGui.TextDisabled(p.ToString()); } int ni = NextIndex(route, idx); - if (ni >= 0) ImGui.TextDisabled($"Next: [{ni}] {pts[ni]}"); + if (ni >= 0) SafeImGui.TextDisabled($"Next: [{ni}] {pts[ni]}"); double remain = RemainingYards(route, idx, f); - if (remain > 0) ImGui.TextDisabled(route.RouteType == NavRouteType.Circular ? $"Loop: {remain:F0} yd" : $"Remaining: ~{remain:F0} yd"); + if (remain > 0) SafeImGui.TextDisabled(route.RouteType == NavRouteType.Circular ? $"Loop: {remain:F0} yd" : $"Remaining: ~{remain:F0} yd"); ImGui.EndGroup(); if (travel) @@ -288,10 +289,10 @@ internal sealed class NavOverlayRenderer } if (!string.IsNullOrEmpty(_settings.NavStatusLine)) - ImGui.TextColored(_settings.NavIsStuck ? new Vector4(0.91f, 0.70f, 0.20f, 1f) : new Vector4(0.6f, 0.75f, 0.6f, 1f), + SafeImGui.TextColored(_settings.NavIsStuck ? new Vector4(0.91f, 0.70f, 0.20f, 1f) : new Vector4(0.6f, 0.75f, 0.6f, 1f), _settings.NavStatusLine); if (o.TrackBreadcrumbs) - ImGui.TextDisabled($"Trail: {_trail.Trail.Length} pts, {_trail.TrailYards:F0} yd"); + SafeImGui.TextDisabled($"Trail: {_trail.Trail.Length} pts, {_trail.TrailYards:F0} yd"); ImGui.End(); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 31308d5..5be3c7b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -59,10 +59,13 @@ public static unsafe class PluginExports catch (Exception ex) { LogShutdownError(plugin, "CombatHookInterface.Shutdown", ex); } try { - // The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload. + // The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a + // reload. The sections manifest goes too. foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero), - Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) }) + Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero), + Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) }) if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); + _sectionsJson = null; } catch (Exception ex) { LogShutdownError(plugin, "loot buffers", ex); } } @@ -124,6 +127,10 @@ public static unsafe class PluginExports /// RynthCore 2026.10.5.30+ adds ":popout" to the name when the panel is popped out into its /// own window, whose ImGui context is not the one in Host.ImGuiContext; the surfaces draw /// in the engine's current context either way (RenderEmbedded*). + /// RynthCore 2026.10.5.46+ (Mini Remote sections): "miniremote-remote" (the remote without its + /// tab bar, the engine's section rail replaces it), "miniremote-host" (the engine's Mini Remote + /// is open on another section; draws nothing) and "section:<name>" (the views + /// RynthPluginGetSectionsJson lists). /// 1 = drawn, 0 = not ready / unknown (nothing drawn). /// [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] @@ -136,9 +143,26 @@ public static unsafe class PluginExports if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length]; var plugin = Runtime.Plugin; if (plugin == null) return 0; - bool window = name.SequenceEqual("miniremote-window"u8); - if (!window && !name.SequenceEqual("miniremote"u8)) return 0; - if (!plugin.RenderEmbeddedMiniRemote(window, out System.Numerics.Vector2 want)) return 0; + System.Numerics.Vector2 want; + var size = new System.Numerics.Vector2(width, height); + if (name.SequenceEqual("miniremote-host"u8)) + { + return plugin.MarkEngineMiniRemote() ? 1 : 0; + } + else if (name.StartsWith("section:"u8)) + { + // Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours. + if (name.Length > 64) return 0; + if (!plugin.RenderEmbeddedSection(System.Text.Encoding.UTF8.GetString(name), size, out want)) return 0; + } + else + { + // "guardian" is RynthILT's (since 2026-10-13): not answered here. + bool remote = name.SequenceEqual("miniremote-remote"u8); + bool window = remote || name.SequenceEqual("miniremote-window"u8); + if (!window && !name.SequenceEqual("miniremote"u8)) return 0; + if (!plugin.RenderEmbeddedMiniRemote(window, out want, tabs: !remote)) return 0; + } if (wantWidth != null) *wantWidth = want.X; if (wantHeight != null) *wantHeight = want.Y; return 1; @@ -843,6 +867,29 @@ public static unsafe class PluginExports return newPtr; } + private static IntPtr _sectionsPtr = IntPtr.Zero; + private static string? _sectionsJson; + + /// + /// RynthCore 2026.10.5.46+ (optional): what RynthAi adds to the Mini Remote's sections, as + /// UTF-8 JSON (schema 1, Huds/SectionsManifest.cs). Null before login. The engine polls it on + /// the render thread every couple of seconds; an unchanged manifest keeps the same buffer, a + /// changed one frees the previous buffer (the engine copies the text before its next call). + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + string? json = Runtime.Plugin?.BuildSectionsJson(); + if (json == null) return IntPtr.Zero; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + return Utf8Swap(ref _sectionsPtr, json); + } + catch { return IntPtr.Zero; } + } + /// Changes whenever the editor's state does; 0 before RynthAi is ready. [UnmanagedCallersOnly(EntryPoint = "RynthPluginLootEditRevision", CallConvs = new[] { typeof(CallConvCdecl) })] public static int LootEditRevision() diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 02b4591..8becd87 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -31,6 +31,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra fellow — fellowship diagnostics and queries"); ChatLine("[RynthAi] /ra help — show this list"); ChatLine("[RynthAi] /ra version — RynthAi version and build date, and the engine it runs on"); + ChatLine("[RynthAi] /ra server - which server RynthCore says this is, its overrides, and the server plugin's settings"); ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)"); ChatLine("[RynthAi] /ra cast — cast spell on current target"); ChatLine("[RynthAi] /ra buffs — show active buff timers"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs index 21ba353..cd95cb9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -16,7 +16,8 @@ namespace RynthCore.Plugin.RynthAi; /// /// /ra iteminfo describe the selected item (IDs it first when needed) /// /ra iteminfo <item name> describe an inventory item by name (exact, else partial) -/// /ra iteminfo on|off describe every item you select +/// /ra iteminfo me your own ratings (also on selecting / clicking yourself) +/// /ra iteminfo on|off describe every item you select (yourself: your ratings) /// /ra iteminfo settings open/close the Item Info settings window /// /ra iteminfo fields list fields and ratings with their on/off state /// /ra iteminfo field <name> on|off show/hide one field (ratings, slayer, spells, …) @@ -72,6 +73,12 @@ public sealed partial class RynthAiPlugin switch (sub) { + case "me": + case "self": + case "ratings": + QueueSelfRatings(auto: false); + return; + case "settings": case "gui": case "window": @@ -163,7 +170,7 @@ public sealed partial class RynthAiPlugin if (found != 0) { QueueItemInfo(unchecked((int)found), requestId: true); return; } ChatLine($"[RynthAi] Item info: no \"{name}\" in your inventory."); } - ChatLine("[RynthAi] Usage: /ra iteminfo [|on|off|settings|fields|field on|off|rating on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]"); + ChatLine("[RynthAi] Usage: /ra iteminfo [|me|on|off|settings|fields|field on|off|rating on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]"); } /// @@ -240,6 +247,7 @@ public sealed partial class RynthAiPlugin if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; } uint selected = Host.GetSelectedItemId(); if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; } + if (IsSelf(selected)) { QueueSelfRatings(auto: false); return; } QueueItemInfo(unchecked((int)selected), requestId: true); } @@ -351,6 +359,12 @@ public sealed partial class RynthAiPlugin string button = MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]; uint selected = Host.GetSelectedItemId(); if (selected == 0) { ItemInfoLog($"{button}: nothing selected"); return; } + if (IsSelf(selected)) + { + ItemInfoLog($"{button}: 0x{selected:X8} (yourself): ratings queue"); + QueueSelfRatings(auto: true); + return; + } int id = unchecked((int)selected); WorldObject? obj = _objectCache?[id]; @@ -368,6 +382,7 @@ public sealed partial class RynthAiPlugin private void TickItemInfo() { ResolveItemInfoClick(); + TickSelfRatings(); int id = _itemInfoPendingId; if (id == 0) return; @@ -438,6 +453,14 @@ public sealed partial class RynthAiPlugin uint selected = Host.GetSelectedItemId(); if (selected == 0) return null; int id = unchecked((int)selected); + if (IsSelf(selected)) + { + // Cache only: the window redraws every frame, so it never asks for an identify. + bool known = !Host.HasHasAppraisalData || Host.HasAppraisalData(selected); + List self = ItemInfo.SelfRatings.Build(_objectCache?[id]?.Name ?? string.Empty, + stype => ReadSelfInt(id, stype), known, oneLine: false); + return string.Join("\n ", self); + } List? lines = BuildItemInfoLines(id, out string? error); if (lines == null || lines.Count == 0) return error; if (Host.HasHasAppraisalData && !Host.HasAppraisalData(selected)) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.EngineServers.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.EngineServers.cs new file mode 100644 index 0000000..896141d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.EngineServers.cs @@ -0,0 +1,33 @@ +// RynthAiPlugin.EngineServers.cs - server chat commands from RynthAi's views in RynthCore's sections. +// +// The Fellowship view RynthCore's Fellowship section draws ("section:fellowship", +// Huds/FellowshipSectionUi.cs) has buttons that run a chat command (a server plugin's /fship ...). +// They are clicked on the render thread; the command is queued here and run on the plugin tick +// through the engine's chat parser. +// +// The Infinite Leaftide world list and the "Treat this world as ILT" override are RynthILT's +// (since 2026-10-13), and RynthCore adds RynthILT's verdict to its own detection, so nothing of +// RynthAi's is copied to RynthCore (the feat/dynamic-sections copy of RynthAi's old settings was +// dropped in the merge). +using System; +using System.Collections.Concurrent; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// At most this many commands wait for the tick (a stuck button can't flood chat). + private const int MaxQueuedEngineCommands = 32; + + private readonly ConcurrentQueue _engineCommands = new(); + + /// Plugin tick: the queued chat commands, through the engine's chat parser. + private void DrainEngineCommands() + { + while (_engineCommands.TryDequeue(out string? command)) + { + if (Host.HasInvokeChatParser && Host.InvokeChatParser(command)) continue; + Log($"[RynthAi] RynthCore didn't take: {command}"); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 6631259..12145cd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using ImGuiNET; using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.MiniRemote; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi; @@ -206,6 +207,7 @@ public sealed partial class RynthAiPlugin try { _huds?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); } _huds = null; + Huds.ServerCommandModel.Clear(); _itemInfoUi = null; _spellsUi = null; ResetGroundLoot(clearCaches: true); @@ -334,7 +336,7 @@ public sealed partial class RynthAiPlugin /// context, see ). False (nothing drawn) until login and the HUDs /// exist. Render thread. /// - public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want) + public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want, bool tabs = true) { want = default; var huds = _huds; @@ -345,7 +347,7 @@ public sealed partial class RynthAiPlugin ImGui.SetCurrentContext(EmbedContext()); try { - want = huds.RenderEmbedded(window); + want = huds.RenderEmbedded(window, tabs); return true; } catch (Exception ex) @@ -359,6 +361,120 @@ public sealed partial class RynthAiPlugin } } + /// + /// RynthPluginRenderEmbed "miniremote-host": RynthCore's Mini Remote window is open on one of + /// its sections, so it is still the one Mini Remote (the floating copy stays hidden). Draws + /// nothing. Render thread. + /// + public bool MarkEngineMiniRemote() + { + var huds = _huds; + if (!_initialized || !_loginComplete || huds == null) return false; + huds.MarkEngineWindow(); + return true; + } + + private Huds.FellowshipSectionUi? _fellowshipUi; + + /// + /// The fellowship view RynthCore's Fellowship section draws ("section:fellowship"); the + /// player's main fellowship window is RynthOracle's Fellowship tab. Render thread. + /// + private Huds.FellowshipSectionUi FellowshipUi() => + _fellowshipUi ??= new Huds.FellowshipSectionUi(() => _fellowshipTracker, + () => Host.HasGetPlayerId ? Host.GetPlayerId() : 0, + QueueServerCommand); + + /// Render thread: queues a server chat command (a fellowship button) for the plugin tick. + private bool QueueServerCommand(string command) + { + if (!Host.HasInvokeChatParser || _engineCommands.Count >= MaxQueuedEngineCommands) return false; + _engineCommands.Enqueue(command); + return true; + } + + /// + /// RynthPluginRenderEmbed "section:<name>": one of RynthAi's views in RynthCore's Mini + /// 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. + /// + public bool RenderEmbeddedSection(string surface, System.Numerics.Vector2 size, out System.Numerics.Vector2 want) + { + want = size; + var huds = _huds; + var remote = _miniRemote; + if (!_initialized || !_loginComplete || Host.ImGuiContext == IntPtr.Zero) return false; + + Func? draw = null; + if (surface == Huds.SectionsManifest.SessionSurface) + { + // The one session (RynthCore's Session Stats section). + if (huds == null) return false; + draw = () => { huds.RenderSessionSection(); return true; }; + } + else if (surface == Huds.SectionsManifest.FellowshipSurface) + { + // RynthILT's own pane carries ILT's /fship commands in RynthCore's section. + draw = () => { FellowshipUi().Render(withServerCommands: false); return true; }; + } + else if (Huds.SectionsManifest.TryOwnTabOf(surface, out string ownTab)) + { + if (remote == null) return false; + 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(); + var spells = _spellsUi; + if (spells == null) return false; + draw = () => { spells.RenderEmbedded(); return true; }; + } + if (draw == null) return false; + + // The engine's Mini Remote window shows this section: it is still the one Mini Remote. + huds?.MarkEngineWindow(); + IntPtr previousContext = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(EmbedContext()); + int pushedColors = LegacyDashboardRenderer.PushDashboardStyle(); + try + { + return draw(); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.UI, ex, "RenderEmbeddedSection " + surface); + return false; + } + finally + { + ImGui.PopStyleColor(pushedColors); + ImGui.SetCurrentContext(previousContext); + } + } + + /// + /// 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. + /// + 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); + } /// Chat Translate window in the dashboard colours (no-op while hidden). private void RenderTranslateWindow() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index ce42892..cb3c181 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -395,6 +395,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private void TeardownSession() { ObjectChangeTracker.Clear(); + while (_engineCommands.TryDequeue(out _)) { } // a fellowship button's command is for this character only // The server drops whatever it was doing for this character at logout. RynthCore.Plugin.Shared.ActionPacer.Forget("logout"); _navigationEngine?.Stop(); @@ -689,6 +690,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.SetWeaponSwapGate(_weaponSwapGate); _combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals _combatManager.HoldIdlePeace = LootHoldsIdlePeace; + _combatManager.HoldNewTarget = BoostLootHoldsNewTarget; // Boost Loot Priority: one kill, one loot _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); @@ -904,6 +906,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase Huds.ServerMenuModel.Apply(value); return; } + // A server plugin's commands for one of RynthAi's section views (RynthILT's /fship for Fellowship). + if (action.Equals(ServerCommandShare.Action, StringComparison.OrdinalIgnoreCase)) + { + Huds.ServerCommandModel.Apply(value); + return; + } var dash = _dashboard; if (dash == null) return; bool on = value is "1" or "true" or "on" or "True" or "TRUE" @@ -949,7 +957,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "itemhud": case "remote": case "miniremote": - // Dashboard Hub launcher: left-click remote=toggle, right-click huds=show. + // RynthCore's Mini Remote commands ("remote","toggle"; "huds","show"). HandleHudCommand(action.ToLowerInvariant(), value); break; case "itemhudadd": @@ -1010,6 +1018,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100), ["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100), ["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2), + ["WeaponSwapSettleMs"] = (0, 3000), ["WeaponSwapMinHealthPct"] = (0, 100), ["WeaponSwapMinGainPct"] = (0, 200), ["PetMinMonsters"] = (1, 20), ["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100), ["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500), @@ -1379,6 +1388,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 + 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 @@ -2180,6 +2190,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // unguarded appraisal + health query here sent 4-6 identifies per corpse. RequestTargetVitals(currentTargetId, obj); + // Yourself: with Item Info on select, your ratings (RynthAiSelfRatings). + if (IsSelf(currentTargetId)) + { + var selfInfo = _dashboard?.Settings.ItemInfoSettings; + if (selfInfo != null && selfInfo.OnSelect && !ItemInfo.SelfSelect.IsOurs(currentTargetId)) + { + ItemInfoLog($"select 0x{currentTargetId:X8} (yourself): ratings queue"); + QueueSelfRatings(auto: true); + } + return; + } + // Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.) if (obj != null && IsLootableClass(obj.ObjectClass)) { @@ -2278,7 +2300,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _petManager?.OnChatWindowText(text); _combatManager?.TraceCastChat(text, chatType); _combatManager?.HandleChatForDebuffs(text); - _combatManager?.HandleChatForDamage(text); + _combatManager?.HandleChatForDamage(text, chatType); _missileCraftingManager?.HandleChat(text); _scrollLearner?.OnChat(text); _metaManager?.HandleChat(text, chatType); @@ -2301,6 +2323,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats kill"); } if (string.IsNullOrEmpty(deathMessage)) return; _killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone + NoteBoostLootKill(); // before combat sees the kill: its next target waits for the corpse _combatManager?.OnKillNotification(deathMessage); _dashboard?.RecordKill(); // feeds the kills/hour session stat } @@ -3481,6 +3504,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "listgvars": HandleListGvarsCommand(); break; 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; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs new file mode 100644 index 0000000..7039806 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiSelfRatings.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.ItemInfo; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Item Info on yourself: with "Describe items when selected" (or the click trigger) on, selecting +/// your own character prints your ratings (SelfRatings) instead of skipping you as a non-item. +/// "/ra iteminfo me" prints them on demand. Client-side only: it identifies the player, whose +/// identify reply carries the server's resolved rating totals, and reads them from the property +/// cache. Partial class of RynthAiPlugin. +/// +public sealed partial class RynthAiPlugin +{ + /// + /// Wait at least this long after asking for the self-identify. There is no "identify arrived" + /// event and the player may already have an older identify cached, so printing at once could + /// show stale totals; one round trip is well under this. + /// + private const long SelfRatingsSettleMs = 700; + + /// TickCount64 of the pending self-identify; 0 = nothing pending (tick thread). + private long _selfRatingsRequestedAt; + + /// The player's object id, or 0 before login / on a host without it. + private uint SelfId() => Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + + /// True when is this character. + private bool IsSelf(uint id) => id != 0 && id == SelfId(); + + /// + /// Asks the server to identify the player and prints the ratings from . + /// (select / click triggers) shares Item Info's de-duplication, so one + /// click that raises both triggers prints once. + /// + internal void QueueSelfRatings(bool auto) + { + uint me = SelfId(); + if (me == 0) + { + if (!auto) ChatLine("[RynthAi] Ratings: not logged in yet."); + return; + } + int sid = unchecked((int)me); + long now = Environment.TickCount64; + if (auto) + { + if (sid == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) + { + ItemInfoLog("self: already queued by the other trigger"); + return; + } + _itemInfoLastAutoId = sid; + _itemInfoLastAutoAt = now; + } + + if (!Host.HasRequestId) + { + // Nothing to ask with: print what the cache has (the lum augs at least). + PrintSelfRatings(me, identified: Host.HasHasAppraisalData && Host.HasAppraisalData(me)); + return; + } + Host.RequestId(me); + _selfRatingsRequestedAt = now; + ItemInfoLog($"self 0x{me:X8}: identify requested for the ratings"); + } + + /// Plugin-tick half: prints once the identify is in (after the settle time) or timed out. + private void TickSelfRatings() + { + long at = _selfRatingsRequestedAt; + if (at == 0) return; + long since = Environment.TickCount64 - at; + if (since < SelfRatingsSettleMs) return; + + uint me = SelfId(); + if (me == 0) { _selfRatingsRequestedAt = 0; return; } + bool ready = !Host.HasHasAppraisalData || Host.HasAppraisalData(me); + long timeoutMs = (long)((ItemInfoSettings?.IdTimeoutSec ?? 3f) * 1000f); + if (!ready && since < timeoutMs) return; + + _selfRatingsRequestedAt = 0; + PrintSelfRatings(me, ready); + } + + /// Writes the ratings in Item Info's prefix, layout and chat colours. + private void PrintSelfRatings(uint me, bool identified) + { + int id = unchecked((int)me); + var s = ItemInfoSettings; + bool oneLine = (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine; + string name = _objectCache?[id]?.Name ?? string.Empty; + List lines = SelfRatings.Build(name, stype => ReadSelfInt(id, stype), identified, oneLine); + ItemInfoLog($"self 0x{me:X8}: printed {lines.Count} line(s), identified={identified}: {lines[0]}"); + + string prefix = s?.Prefix ?? "[RynthAi Item] "; + int headerType = s?.ChatType ?? 1; + int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType; + Host.WriteToChat(prefix + lines[0], headerType); + for (int i = 1; i < lines.Count; i++) + Host.WriteToChat(prefix + " " + lines[i], detailType); + } + + /// One of the player's int properties from the cache (PlayerDescription, else the last identify); 0 when absent. + private int ReadSelfInt(int id, uint stype) + { + if (_objectCache != null) return _objectCache.GetIntProperty(id, stype, 0); + return Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(unchecked((uint)id), stype, out int v) ? v : 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs new file mode 100644 index 0000000..1aaa8e4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs @@ -0,0 +1,52 @@ +using System; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// RynthCore's server list and the active server owner's profile, read on demand for /ra server. + private readonly ServerStateClient _serverState = new(); + + /// + /// /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 + /// plugin is reading the same server identity. Plain ASCII (the AC chat can't draw more). + /// + private void HandleServerCommand() + { + _serverState.Poll(Host, Environment.TickCount64, force: true); + EngineServerState? st = _serverState.State; + string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w.Trim() : ""; + if (st == null) + { + ChatLine(_serverState.Supported + ? "[RynthAi] Server: RynthCore didn't answer GetServerStateJson." + : $"[RynthAi] Server: this engine (plugin API v{Host.Version}) doesn't report its server list (v86 does). World name: '{world}'."); + return; + } + + ChatLine(st.HasActive + ? $"[RynthAi] Server: {st.ActiveName} ({st.Active}), {(st.Picked ? "picked by hand" : "detected or per-server override")}; settings from {(st.ActivePlugin.Length > 0 ? st.ActivePlugin : "no loaded plugin")}." + : $"[RynthAi] Server: none active (retail features only){(st.Picked ? ", picked by hand" : "")}."); + ChatLine($"[RynthAi] Host '{st.Host}', announced world '{st.World}', client world name '{world}', pick '{st.Pick}'."); + foreach (EngineServer s in st.Servers) + { + string flags = (s.Active ? "ACTIVE" : "off") + (s.Detected ? ", detected" : "") + (s.Force != "auto" ? ", forced " + s.Force : ""); + ChatLine($"[RynthAi] {s.Id} ({s.Name}): {flags}; owner {(s.Plugin.Length > 0 ? s.Plugin : "-")}{(s.Reason.Length > 0 ? "; " + s.Reason : "")}"); + } + + if (st.ActivePlugin.Length > 0) + { + ServerProfileView? p = ServerProfileView.Parse(_serverState.ProfileJson); + ChatLine(p != null + ? $"[RynthAi] {_serverState.ProfilePlugin} {RynthServerProfileApiV1.InterfaceName}: {p.Summary()}" + : $"[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")}."); + ChatLine("[RynthAi] Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick |auto."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 60c2d9c..2eeaf02 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -53,6 +53,11 @@ + + + + + @@ -60,11 +65,18 @@ + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs index 1265c6b..1c61923 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs @@ -2,6 +2,7 @@ // Providers that use other codes (DeepL upper-case, LibreTranslate "zh") are mapped in TranslateClient. using System; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.Translate; @@ -86,7 +87,7 @@ internal static class TranslateLanguages } ImGui.EndCombo(); } - if (ImGui.IsItemHovered() && current > 0) ImGui.SetTooltip(Names[current]); + if (ImGui.IsItemHovered() && current > 0) SafeImGui.SetTooltip(Names[current]); return changed; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs index c2c8e4f..9fbf69a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs @@ -9,6 +9,7 @@ using System; using System.Numerics; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.Translate; @@ -71,15 +72,15 @@ internal sealed class TranslateUi ImGui.SameLine(); ImGui.Checkbox("Outgoing##trout", ref s.EnableOutbound); if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Translate what you type on the ticked Send channels before it goes out.\n" + SafeImGui.SetTooltip("Translate what you type on the ticked Send channels before it goes out.\n" + $"Start a line with '{s.RawPrefix}' to send it untranslated."); ImGui.SameLine(); - ImGui.TextColored(ColDim, $"| {_tr.Translated} done, {_tr.CharsSent:N0} chars, {_tr.Pending} queued"); + SafeImGui.TextColored(ColDim, $"| {_tr.Translated} done, {_tr.CharsSent:N0} chars, {_tr.Pending} queued"); if (s.ApiKey.Length == 0 && s.Provider != TranslateSettings.ProviderLibre) ImGui.TextColored(ColError, "No API key: open the Settings tab to add one."); else if (_tr.LastError.Length > 0) - ImGui.TextColored(ColError, "Last error: " + _tr.LastError); + SafeImGui.TextColored(ColError, "Last error: " + _tr.LastError); } /// Receive / swap / send / reset-to-default row (window and Advanced page). @@ -100,14 +101,14 @@ internal sealed class TranslateUi ImGui.SameLine(); string send = s.CurrentSendLanguage; if (TranslateLanguages.Combo("##send" + id, ref send, allowAuto: false, comboWidth)) s.CurrentSendLanguage = send; - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"What you type is translated into this language.\nDefault: {TranslateLanguages.Label(s.DefaultSendLanguage)}"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"What you type is translated into this language.\nDefault: {TranslateLanguages.Label(s.DefaultSendLanguage)}"); ImGui.SameLine(); bool atDefault = s.CurrentSendLanguage == s.DefaultSendLanguage; if (atDefault) ImGui.BeginDisabled(); if (ImGui.Button("Default##senddef" + id)) s.CurrentSendLanguage = s.DefaultSendLanguage; if (atDefault) ImGui.EndDisabled(); if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); + SafeImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); } private void RenderLog() @@ -115,7 +116,7 @@ internal sealed class TranslateUi var log = _tr.LogSnapshot(); if (ImGui.SmallButton("Clear")) _tr.ClearLog(); ImGui.SameLine(); - ImGui.TextColored(ColDim, $"{log.Length} entries (hover a line for the original)"); + SafeImGui.TextColored(ColDim, $"{log.Length} entries (hover a line for the original)"); if (!ImGui.BeginChild("##trlog", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGui.EndChild(); return; } foreach (var e in log) @@ -126,18 +127,18 @@ internal sealed class TranslateUi TranslateDirection.Out => ("OUT", ColOut), _ => ("TST", ColTest), }; - ImGui.TextColored(ColDim, e.Time.ToString("HH:mm:ss")); + SafeImGui.TextColored(ColDim, e.Time.ToString("HH:mm:ss")); ImGui.SameLine(); - ImGui.TextColored(e.Error.Length > 0 && e.Translated.Length == 0 ? ColError : col, tag); + SafeImGui.TextColored(e.Error.Length > 0 && e.Translated.Length == 0 ? ColError : col, tag); ImGui.SameLine(); string ch = e.Channel is { } c ? $"[{TranslateChannels.Name(c)}] " : string.Empty; string who = e.Speaker.Length > 0 ? e.Speaker + ": " : string.Empty; string body = e.Translated.Length > 0 ? e.Translated : e.Original; - ImGui.TextWrapped($"{ch}{who}{body}"); + SafeImGui.TextWrapped($"{ch}{who}{body}"); if (ImGui.IsItemHovered()) { string langs = e.From.Length > 0 || e.To.Length > 0 ? $"\n{(e.From.Length > 0 ? e.From : "?")} -> {e.To}" : string.Empty; - ImGui.SetTooltip($"Original: {e.Original}{langs}{(e.Error.Length > 0 ? "\n" + e.Error : string.Empty)}"); + SafeImGui.SetTooltip($"Original: {e.Original}{langs}{(e.Error.Length > 0 ? "\n" + e.Error : string.Empty)}"); } } // Follow new lines unless the user scrolled up. @@ -150,7 +151,7 @@ internal sealed class TranslateUi private void RenderCompose() { var s = S; - ImGui.TextWrapped($"Type in any language; it is translated into {TranslateLanguages.Label(s.CurrentSendLanguage)} and sent on the chosen channel."); + SafeImGui.TextWrapped($"Type in any language; it is translated into {TranslateLanguages.Label(s.CurrentSendLanguage)} and sent on the chosen channel."); ImGui.Spacing(); ImGui.SetNextItemWidth(140f); @@ -251,7 +252,7 @@ internal sealed class TranslateUi ImGui.SetNextItemWidth(220f); if (ImGui.Combo("Provider" + id, ref provider, TranslateSettings.ProviderNames, TranslateSettings.ProviderNames.Length)) s.Provider = TranslateSettings.Providers[provider]; - ImGui.TextColored(ColDim, ProviderHint(s.Provider)); + SafeImGui.TextColored(ColDim, ProviderHint(s.Provider)); var keyFlags = _showKey ? ImGuiInputTextFlags.None : ImGuiInputTextFlags.Password; ImGui.SetNextItemWidth(300f); @@ -322,26 +323,26 @@ internal sealed class TranslateUi var s = S; ImGui.PushID("##mrtranslate"); ImGui.Checkbox("Translate", ref s.Enabled); - if (ImGui.IsItemHovered()) ImGui.SetTooltip(_tr.StatusLine() + (_tr.LastError.Length > 0 ? "\nLast error: " + _tr.LastError : string.Empty)); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(_tr.StatusLine() + (_tr.LastError.Length > 0 ? "\nLast error: " + _tr.LastError : string.Empty)); ImGui.SameLine(); if (ImGui.SmallButton("Window")) s.ShowWindow = !s.ShowWindow; string recv = s.MyLanguage; if (TranslateLanguages.Combo("##mrrecv", ref recv, allowAuto: false, 62f)) s.MyLanguage = recv; - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Receive: {TranslateLanguages.Label(s.MyLanguage)}"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Receive: {TranslateLanguages.Label(s.MyLanguage)}"); ImGui.SameLine(); if (ImGui.Button("<->")) _tr.SwapLanguages(); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Swap receive and send languages."); ImGui.SameLine(); string send = s.CurrentSendLanguage; if (TranslateLanguages.Combo("##mrsend", ref send, allowAuto: false, 62f)) s.CurrentSendLanguage = send; - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Send: {TranslateLanguages.Label(s.CurrentSendLanguage)}"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Send: {TranslateLanguages.Label(s.CurrentSendLanguage)}"); // Right-click belongs to the Mini Remote options menu, so the reset is a button. if (s.CurrentSendLanguage != s.DefaultSendLanguage) { ImGui.SameLine(); if (ImGui.SmallButton("def")) s.CurrentSendLanguage = s.DefaultSendLanguage; - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); } ImGui.PopID(); } diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj b/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj new file mode 100644 index 0000000..551ffc8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthColdeve + 0.1.0 + coldeve + Coldeve + play.coldeve.ac + Coldeve + Coldeve only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs b/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs new file mode 100644 index 0000000..ba07823 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs @@ -0,0 +1,18 @@ +// ServerData.cs - What is known about Coldeve (RynthColdeve). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE AC Server evolving to provide a end of retail experience running ACEmulator.", + Facts = new[] { "End-of-retail experience on ACEmulator." }, + Discord = "https://discord.gg/nUR4PHe", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj new file mode 100644 index 0000000..2415f4d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthConquest + 0.1.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. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs new file mode 100644 index 0000000..9f5cfcb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Conquest (RynthConquest). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "Custom PvE server with live events, deep crafting, active development, and PK system.", + Facts = new[] + { + "Live events and deep crafting.", + "Has a PK system on a PvE server.", + "RynthOracle has a Conquest quest pack (quests.conquest.csv).", + }, + Discord = "https://discord.gg/Gsadhhv72S", + Website = "https://dsc.gg/conquerac", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj b/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj new file mode 100644 index 0000000..b1e82e5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthDerptide + 0.1.0 + derptide + Derptide + ac.derptide.net + Derptide + Derptide only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs new file mode 100644 index 0000000..6ef4066 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about Derptide (RynthDerptide). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "EOR server that pushes custom content and Qol changes, All quest weapons have been upgraded to be useful, " + + "and usable. No quest item will EVER be better than lootgen, Live events, Ongoing story arcs. and TONS of tailoring options.", + Facts = new[] + { + "Quest weapons are upgraded to be useful, but never better than loot-generated items.", + "Live events and ongoing story arcs.", + "Many tailoring options.", + }, + Discord = "https://discord.gg/3gDTBVtfAg", + Website = "https://derptide.net", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj new file mode 100644 index 0000000..5082e4a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthDreamWeave + 0.1.0 + dreamweave + DreamWeave + play.acdreamweave.com + DreamWeave|Dream Weave + DreamWeave only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs new file mode 100644 index 0000000..83422c8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about DreamWeave (RynthDreamWeave). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "PvE server pushing unmodified end-of-retail ToD to the limit. Lore driven, new class abilities, " + + "new crafting system, tons of QOL, up-to-date wiki.", + Facts = new[] + { + "Lore driven, built on end-of-retail Throne of Destiny.", + "New class abilities and a new crafting system.", + "Its wiki is kept up to date.", + }, + Discord = "https://discord.gg/p2h3yca4BD", + Wiki = "https://wiki.acdreamweave.com", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj b/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj new file mode 100644 index 0000000..b972d60 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthEversong + 0.1.0 + eversong + Eversong + eversong.abrdns.com + Eversong + Eversong only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs b/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs new file mode 100644 index 0000000..916e5d6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Eversong (RynthEversong). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "Five difficulty worlds, quest bonuses, enlightenment & milestones, banking & lockboxes, invasions, optional classes.", + Facts = new[] + { + "Five difficulty worlds.", + "Quest bonuses, enlightenment and milestones.", + "Banking and lockboxes.", + "Invasions and optional classes.", + }, + Discord = "https://discord.gg/9eHxTb7p2J", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj b/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj new file mode 100644 index 0000000..4baa0d6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthFrostACE + 0.1.0 + frostace + FrostACE + 172.111.230.127 + FrostACE|FrostfACE + FrostACE only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs new file mode 100644 index 0000000..d103925 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs @@ -0,0 +1,22 @@ +// ServerData.cs - What is known about FrostACE (RynthFrostACE). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "New accounts include lvl 275 starter characters. Retail character restoration also supported.", + Facts = new[] + { + "New accounts get level 275 starter characters.", + "Retail character restoration is supported.", + "Listed as \"FrostfACE\" in the public server list; it connects by IP address.", + }, + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj b/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj new file mode 100644 index 0000000..04f81e2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthFrostcull + 0.1.0 + frostcull + Frostcull + frostcull.ddns.net + Frostcull + Frostcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs new file mode 100644 index 0000000..d0e8e87 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Frostcull (RynthFrostcull). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "NO LEVEL/ATTRIBUTE CAP! 10x XP/Luminance, 25x Drop Rate, Quest Timers Reduced By 90%!", + Facts = new[] + { + "No level or attribute cap.", + "10x experience and luminance.", + "25x drop rate.", + "Quest timers 90% shorter.", + }, + Discord = "https://discord.gg/RQF7HgEZn4", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs new file mode 100644 index 0000000..05e9619 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs @@ -0,0 +1,143 @@ +// 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 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 +// is no controller: the JSON getters answer 0 (nothing to report) and the actions are refused. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class DataInterface +{ + /// Longest bank / breeding verb line taken (a transfer with a long character name fits easily). + private const int MaxVerbBytes = 256; + + private static RynthIltDataApiV1* _table; + private static volatile bool _released; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthIltDataApiV1.InterfaceName || version < 1 || version > RynthIltDataApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthIltDataApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltDataApiV1)); + t->StructSize = (uint)sizeof(RynthIltDataApiV1); + t->GetCharmsJson = &GetCharmsJson; + t->GetBankJson = &GetBankJson; + t->ToggleCharm = &ToggleCharm; + t->BankCommand = &BankCommand; + t->GetPetBreedingJson = &GetPetBreedingJson; + t->PetBreedingCommand = &PetBreedingCommand; + t->Version = RynthIltDataApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: readers see Version 0 and re-query; every function answers 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetCharmsJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.CharmsJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetBankJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.BankJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int ToggleCharm(uint objectId) + { + try + { + IltHubController? hub = Hub; + if (hub == null || objectId == 0) return 0; + hub.RequestCharmToggle(objectId); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int BankCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestBankVerb(line); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetPetBreedingJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.PetBreedingJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int PetBreedingCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestBreedingVerb(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) + { + if (utf8 == null) return null; + int len = 0; + while (len < MaxVerbBytes && utf8[len] != 0) len++; + if (len == 0 || len >= MaxVerbBytes) return null; + string line = System.Text.Encoding.UTF8.GetString(utf8, len); + foreach (char c in line) + if (c < 0x20 || c > 0x7E) return null; + return line; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs index bb4752e..e4782e2 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs @@ -1,50 +1,69 @@ // IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects. // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // -// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 2026-10-11): +// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 976606695): // /b d [code] deposit everything (no code) or one kind; "Deposited N ", // "No found to deposit", "Deposited all !". // /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x " // a kind, "Ending Banked Lum"; "No luminance tokens found to deposit". // /b w withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...". // /b w n [n] trade notes by denomination (i v x l c d m md mm mmd). -// /b t transfer (IltBanking); Prestige Coins can't be transferred. -// Deposit, withdraw and transfer share one server throttle (bank_command_limit); a plain -// /bank balance doesn't touch it. Pure: no host calls, so the host tests cover it. +// /b t transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]". +// /b t n trade notes' pyreal value, then "(Equivalent to Nx DENOM notes)". +// The recipient is one argument: a name with a space has to be in "quotes". +// Prestige Coins are bound to the character: "[BANK] Prestige Coins are bound to you and +// cannot be transferred." Pyreal peas and luminance tokens are deposit only. +// Items is the one table of what the server allows; the deposit, withdraw and transfer lists +// are built from it. Deposit, withdraw and transfer share one server throttle +// (bank_command_limit); a plain /bank balance doesn't touch it. Pure: no host calls, so the +// host tests cover it. using System; +using System.Linq; namespace RynthCore.Plugin.RynthILT.Hub; internal static class IltBankCommands { + /// + /// One bank item: label, server code, and what the server allows for it. For trade notes + /// ("n") a withdrawal or transfer is by denomination and note count. + /// + internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer); + + /// The trade-notes code: withdrawn and transferred by denomination. + public const string NotesCode = "n"; + + /// The luminance-tokens deposit: its own command, "/b lum". + public const string LuminanceTokensCode = "lum"; + + /// Everything the bank holds, in the server's order, with what it allows. + public static readonly BankItem[] Items = + { + new("Pyreals", "p", Deposit: true, Withdraw: true, Transfer: true), + new("Pyreal peas", "ps", Deposit: true, Withdraw: false, Transfer: false), + new("Luminance", "l", Deposit: true, Withdraw: true, Transfer: true), + new("Luminance tokens", LuminanceTokensCode, Deposit: true, Withdraw: false, Transfer: false), + new("Legendary keys", "k", Deposit: true, Withdraw: true, Transfer: true), + new("Mythical keys", "mk", Deposit: true, Withdraw: true, Transfer: true), + new("Enlightened coins", "e", Deposit: true, Withdraw: true, Transfer: true), + new("Weakly enlightened coins", "we", Deposit: true, Withdraw: true, Transfer: true), + new("Prestige coins", "pc", Deposit: true, Withdraw: true, Transfer: false), + new("Trade notes", NotesCode, Deposit: true, Withdraw: true, Transfer: true), + }; + /// A deposit choice: label, and the command's argument after "/b d" ("" = all). public static readonly (string Label, string Args)[] Deposits = - { - ("Everything", ""), - ("Pyreals", "p"), - ("Pyreal peas", "ps"), - ("Luminance", "l"), - ("Luminance tokens", "lum"), - ("Legendary keys", "k"), - ("Mythical keys", "mk"), - ("Enlightened coins", "e"), - ("Weakly enlightened coins", "we"), - ("Prestige coins", "pc"), - ("Trade notes", "n"), - }; + new[] { ("Everything", string.Empty) } + .Concat(Items.Where(i => i.Deposit).Select(i => (i.Label, i.Code))) + .ToArray(); /// A withdraw choice: label and the server code; "n" is trade notes (by denomination). public static readonly (string Label, string Code)[] Withdrawals = - { - ("Pyreals", "p"), - ("Luminance", "l"), - ("Legendary keys", "k"), - ("Mythical keys", "mk"), - ("Enlightened coins", "e"), - ("Weakly enlightened coins", "we"), - ("Prestige coins", "pc"), - ("Trade notes", "n"), - }; + Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray(); + + /// A transfer choice: label and the server code; "n" moves trade notes' pyreal value. + public static readonly (string Label, string Code)[] Transfers = + Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray(); /// Trade note denominations: label and code, in the server's order. public static readonly (string Label, string Code, long Value)[] NoteDenominations = @@ -54,7 +73,7 @@ internal static class IltBankCommands ("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000), }; - /// The server refuses a trade-note withdrawal of more than this many notes. + /// The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap. public const int MaxNoteCount = 50_000; /// "/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index. @@ -63,7 +82,7 @@ internal static class IltBankCommands if (index < 0 || index >= Deposits.Length) return string.Empty; string args = Deposits[index].Args; if (args.Length == 0) return "/b d"; - return args == "lum" ? "/b lum" : "/b d " + args; + return args == LuminanceTokensCode ? "/b lum" : "/b d " + args; } /// @@ -76,10 +95,47 @@ internal static class IltBankCommands if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; } if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } string code = Withdrawals[index].Code; - if (code != "n") return $"/b w {code} {amount}"; - if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return string.Empty; } - if (amount > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return string.Empty; } - return $"/b w n {NoteDenominations[denomination].Code} {amount}"; + if (code != NotesCode) return $"/b w {code} {amount}"; + if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; + return $"/b w n {denom} {amount}"; + } + + /// + /// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes ( + /// is then the note count). must already be a checked character name + /// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument. + /// Empty (with ) when the input can't be sent. + /// + public static string Transfer(int index, long amount, int denomination, string target, out string error) + { + error = string.Empty; + if (index < 0 || index >= Transfers.Length) { error = "Pick a currency."; return string.Empty; } + if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } + target = (target ?? string.Empty).Trim(); + if (target.Length == 0) { error = "Enter a recipient."; return string.Empty; } + if (target.IndexOf('"') >= 0) { error = "Recipient must be a character name."; return string.Empty; } + string who = target.IndexOf(' ') >= 0 ? "\"" + target + "\"" : target; + string code = Transfers[index].Code; + if (code != NotesCode) return $"/bank t {code} {amount} {who}"; + if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; + return $"/bank t n {denom} {amount} {who}"; + } + + /// True when is the trade-notes transfer (denomination and count). + public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode; + + /// The pyreal value of notes of (0 if unknown). + public static long NoteValue(int denomination, long count) => + denomination >= 0 && denomination < NoteDenominations.Length && count > 0 ? NoteDenominations[denomination].Value * count : 0; + + private static bool TryNote(int denomination, long count, out string code, out string error) + { + code = string.Empty; + error = string.Empty; + if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return false; } + if (count > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return false; } + code = NoteDenominations[denomination].Code; + return true; } /// @@ -110,4 +166,23 @@ internal static class IltBankCommands || line.StartsWith("Count cannot exceed", StringComparison.Ordinal) || line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal); } + + /// + /// True for a line the server sends in reply to a transfer: the result, the trade-note + /// equivalent, the throttle, or a refusal (unknown player, bound prestige coins, bad input). + /// + public static bool IsTransferReply(string line) + { + if (string.IsNullOrEmpty(line)) return false; + return line.StartsWith("Transferred ", StringComparison.Ordinal) + || line.StartsWith("(Equivalent to ", StringComparison.Ordinal) + || line.StartsWith("Character '", StringComparison.Ordinal) + || line.StartsWith("You cannot transfer", StringComparison.Ordinal) + || line.StartsWith("You don't have enough", StringComparison.Ordinal) + || line.StartsWith("[Transfer]", StringComparison.Ordinal) + || line.StartsWith("[BANK] Too many parameters", StringComparison.Ordinal) + || line.StartsWith("[BANK] Prestige Coins are bound", StringComparison.Ordinal) + || line.StartsWith("Invalid count", StringComparison.Ordinal) + || line.StartsWith("Invalid denomination", StringComparison.Ordinal); + } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs new file mode 100644 index 0000000..65b3949 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs @@ -0,0 +1,151 @@ +// IltBankExport.cs - The bank JSON of "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the +// Banking tab's balances, form choices and log for another plugin's view (every character here). +// +// Every character RynthILT has run on this server keeps its balances in its own hub.json +// (\\\hub.json, IltHubStore); the export lists them all, the +// logged-in character from its live state and the rest from their saved files (read on the pump +// at most every SiblingReadMs, so a reader polling every couple of seconds costs one directory +// listing now and then). Plus the form choices (IltBankCommands), the last action's reply and +// the recent transfers. Build is pure: the tests feed it rows. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltBankExport +{ + /// How many recent transfers the JSON carries (newest first). + public const int MaxTransactions = 50; + + /// One character's balances as exported. + internal sealed record Row(string Name, bool Current, IltBankState Bank); + + /// + /// The bank JSON. : 1 the server has /bank, 0 not, -1 not known yet. + /// Rows are listed current character first, then by name. Plain ASCII. + /// + public static string Build(bool available, int enabled, string world, string character, IReadOnlyList rows, + string result, IReadOnlyList transactions) + { + var sb = new StringBuilder(4096); + sb.Append("{\"available\":").Append(available ? "true" : "false"); + sb.Append(",\"enabled\":").Append(Math.Clamp(enabled, -1, 1).ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(world ?? string.Empty)).Append('"'); + sb.Append(",\"character\":\"").Append(IltStyle.JsonEscape(character ?? string.Empty)).Append('"'); + + var ordered = new List(rows); + ordered.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + sb.Append(",\"characters\":["); + for (int i = 0; i < ordered.Count; i++) + { + Row r = ordered[i]; + IltBankState b = r.Bank; + if (i > 0) sb.Append(','); + sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Name)).Append('"'); + sb.Append(",\"current\":").Append(r.Current ? "true" : "false"); + Num(sb, "pyreals", b.Pyreals); + Num(sb, "luminance", b.Luminance); + Num(sb, "legendaryKeys", b.LegendaryKeys); + Num(sb, "mythicalKeys", b.MythicalKeys); + Num(sb, "enlightenedCoins", b.EnlightenedCoins); + Num(sb, "weaklyEnlightenedCoins", b.WeaklyEnlightenedCoins); + Num(sb, "prestigeCoins", b.PrestigeCoins); + sb.Append(",\"updated\":\"").Append(Utc(b.LastUpdated)).Append("\"}"); + } + sb.Append(']'); + + sb.Append(",\"deposits\":["); + for (int i = 0; i < IltBankCommands.Deposits.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(IltStyle.JsonEscape(IltBankCommands.Deposits[i].Label)).Append('"'); + } + sb.Append(']'); + Choices(sb, "withdrawals", IltBankCommands.Withdrawals, w => w.Code == IltBankCommands.NotesCode); + Choices(sb, "transfers", IltBankCommands.Transfers, t => t.Code == IltBankCommands.NotesCode); + sb.Append(",\"notes\":["); + for (int i = 0; i < IltBankCommands.NoteDenominations.Length; i++) + { + var n = IltBankCommands.NoteDenominations[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(n.Label)).Append('"'); + Num(sb, "value", n.Value); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"result\":\"").Append(IltStyle.JsonEscape(result ?? string.Empty)).Append('"'); + sb.Append(",\"transactions\":["); + int written = 0; + for (int i = transactions.Count - 1; i >= 0 && written < MaxTransactions; i--, written++) + { + IltBankTransaction t = transactions[i]; + if (written > 0) sb.Append(','); + sb.Append("{\"when\":\"").Append(t.Timestamp == default ? "" : t.Timestamp.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append('"'); + sb.Append(",\"type\":\"").Append(IltStyle.JsonEscape(t.Type)).Append('"'); + Num(sb, "amount", t.Amount); + sb.Append(",\"currency\":\"").Append(IltStyle.JsonEscape(t.Currency)).Append('"'); + sb.Append(",\"player\":\"").Append(IltStyle.JsonEscape(t.OtherPlayer)).Append("\"}"); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void Num(StringBuilder sb, string name, long value) + => sb.Append(",\"").Append(name).Append("\":").Append(value.ToString(CultureInfo.InvariantCulture)); + + private static void Choices(StringBuilder sb, string name, (string Label, string Code)[] items, Func<(string Label, string Code), bool> notes) + { + sb.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < items.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(items[i].Label)).Append("\",\"notes\":") + .Append(notes(items[i]) ? "true" : "false").Append('}'); + } + sb.Append(']'); + } + + /// A local DateTime as ISO UTC ("" = never). + private static string Utc(DateTime local) => local == DateTime.MinValue || local == default + ? "" + : local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); + + /// + /// The other characters' saved balances: every <world folder>\*\hub.json except + /// . A file that can't be read is skipped (its character just + /// isn't listed). Characters never banked (no LastUpdated) are left out. + /// + public static List ReadSiblings(string currentFolder) + { + var rows = new List(); + if (string.IsNullOrEmpty(currentFolder)) return rows; + string? worldDir = Path.GetDirectoryName(currentFolder.TrimEnd('\\', '/')); + if (string.IsNullOrEmpty(worldDir) || !Directory.Exists(worldDir)) return rows; + string self = Path.GetFullPath(currentFolder).TrimEnd('\\', '/'); + foreach (string dir in Directory.EnumerateDirectories(worldDir)) + { + if (string.Equals(Path.GetFullPath(dir).TrimEnd('\\', '/'), self, StringComparison.OrdinalIgnoreCase)) continue; + string file = Path.Combine(dir, IltHubStore.StateFile); + if (!File.Exists(file)) continue; + try + { + using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var state = JsonSerializer.Deserialize(fs, IltHubJsonContext.Default.IltHubState); + IltBankState? bank = state?.Bank; + if (bank == null || bank.LastUpdated == DateTime.MinValue) continue; + rows.Add(new Row(Path.GetFileName(dir), false, bank)); + } + catch (Exception ex) + { + RynthLog.Trace(LogCat.IltBanking, $"bank export: skipped {file} ({ex.Message})"); + } + } + return rows; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs index 77be5e2..54b3076 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs @@ -1,6 +1,7 @@ -// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, deposits, withdrawals, confirmed -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// transfers, transaction log. +// IltBanking.cs — ILT banking: /bank balances, deposits, withdrawals, confirmed transfers, +// transaction log. Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// Render is the Mini Remote's "Banking" tab. The balances and log are also exported to other +// plugins through "RynthILT.Data" (IltBankExport; their verbs come back through RunVerb). // // Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11): // /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:", @@ -9,8 +10,9 @@ // /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies). // /bank t → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error; // the recipient sees "Received {N0} {currency} from {Name}". -// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins. -// Prestige Coins (pc) are bound: deposit and withdraw only. +// /bank t n → trade notes' pyreal value, then "(Equivalent to ...)". +// What each item allows is IltBankCommands.Items (the server's table): Prestige Coins (pc) +// are bound (deposit and withdraw only); pyreal peas and luminance tokens deposit only. // Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance // refresh doesn't, so it has its own (client-side) spacing. // Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN @@ -20,21 +22,14 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; internal sealed class IltBanking : IIltFeature { - /// Transfer currency table: display name, /bank t code. - public static readonly (string Name, string Code)[] Currencies = - { - ("Pyreals", "p"), - ("Luminance", "l"), - ("Legendary Keys", "k"), - ("Mythical Keys", "mk"), - ("Enlightened Coins", "e"), - ("Weakly Enlightened Coins", "we"), - }; + /// Transfer currencies: display name, /bank t code (IltBankCommands.Transfers). + public static readonly (string Name, string Code)[] Currencies = IltBankCommands.Transfers; private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray(); private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray(); private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray(); @@ -69,6 +64,23 @@ internal sealed class IltBanking : IIltFeature private string _txFilter = string.Empty; private string _lastResult = string.Empty; private volatile string _actionResult = string.Empty; + /// The newest action reply or error (deposit, withdrawal or transfer), for the bank export. + private volatile string _latestResult = string.Empty; + + /// + /// Another plugin is showing the balances (a "RynthILT.Data" reader): + /// the periodic quiet refresh runs as it does while the Mini Remote is open. Pump thread. + /// + public bool ReaderWatching; + + /// The newest action reply or error (any thread). + public string LatestResult => _latestResult; + + /// The transaction log as last published (any thread; oldest first). + public IReadOnlyList Transactions => _txSnapshot; + + /// The bank state (pump thread). + public IltBankState State => Bank; /// Raised (pump thread) after a balance line updates the state; Character rates use the deltas. public event Action? BalanceChanged; @@ -128,40 +140,36 @@ internal sealed class IltBanking : IIltFeature } /// - /// Validates and (after the UI confirm) sends a transfer. Pump thread. + /// Validates and (after the UI confirm) sends a transfer. For trade notes + /// is the note count of . Pump thread. /// Returns an error message, or empty when the command was queued. /// - public string SendTransfer(int currencyIndex, long amount, string target) + public string SendTransfer(int currencyIndex, long amount, string target, int denomination = -1) { - RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')"); + RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, denom={denomination}, target='{target}')"); if (!Enabled) return "Bank is not available on this server."; - if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency."; - if (amount <= 0) return "Amount must be positive."; target = (target ?? string.Empty).Trim(); - if (target.Length == 0) return "Enter a recipient."; // The recipient is spliced into a chat command, so only character-name characters are - // allowed: no '/', control characters or line breaks that could start a second command. - if (!IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only)."; + // allowed: no '/', quotes, control characters or line breaks that could start a second command. + if (target.Length > 0 && !IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only)."; if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself."; + string cmd = IltBankCommands.Transfer(currencyIndex, amount, denomination, target, out string error); + if (cmd.Length == 0) return error; long now = IltHubContext.NowMs; if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds."; _lastBankCommandAt = now; - string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}"; _ctx.Capture.Enqueue(new IltChatRequest { Command = cmd, - IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal) - || t.StartsWith("Character '", StringComparison.Ordinal) - || t.StartsWith("You cannot transfer", StringComparison.Ordinal) - || t.StartsWith("You don't have enough", StringComparison.Ordinal) - || t.StartsWith("[Transfer]", StringComparison.Ordinal), + IsResponseLine = IltBankCommands.IsTransferReply, IdleEndMs = 500, FirstLineTimeoutMs = 8000, Eat = false, OnComplete = r => { _lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty); + _latestResult = _lastResult; // Balances changed: read them again shortly. _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; }, @@ -212,19 +220,51 @@ internal sealed class IltBanking : IIltFeature { _actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6)) : r.TimedOut ? "No reply from the server." : string.Empty; + _latestResult = _actionResult; _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; }, }); return string.Empty; } + /// + /// A bank verb line from "RynthILT.Data" BankCommand (Plugins/Shared/RynthIltDataApi.cs): + /// "refresh", "deposit i", "withdraw i amount note", "transfer i amount note name". The reader + /// has already confirmed a transfer with the player. Pump thread. Returns an error, or empty + /// when it was queued; either way the outcome shows in . + /// + public string RunVerb(string line) + { + string[] p = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + string err; + if (p.Length == 0) err = "Empty bank command."; + else if (p[0] == "refresh" && p.Length == 1) { RequestRefresh(quiet: true); return string.Empty; } + else if (p[0] == "deposit" && p.Length == 2 && int.TryParse(p[1], out int d)) err = SendDeposit(d); + else if (p[0] == "withdraw" && p.Length == 4 && int.TryParse(p[1], out int w) && long.TryParse(p[2], out long wa) + && int.TryParse(p[3], out int wn)) + err = SendWithdraw(w, wa, wn); + else if (p[0] == "transfer" && p.Length >= 5 && int.TryParse(p[1], out int c) && long.TryParse(p[2], out long ta) + && int.TryParse(p[3], out int tn)) + { + // The name may hold spaces; SendTransfer checks it is a character name. + string who = string.Join(' ', p, 4, p.Length - 4); + err = SendTransfer(c, ta, who, IltBankCommands.IsNoteTransfer(c) ? tn : -1); + if (err.Length == 0) _latestResult = "Transfer sent..."; + } + else err = "Unknown bank command."; + if (err.Length > 0) _latestResult = err; + RynthLog.Trace(LogCat.IltBanking, $"reader verb '{line}' -> {(err.Length > 0 ? err : "queued")}"); + return err; + } + // ── IIltFeature ───────────────────────────────────────────────────────── public void Tick(long nowMs) { - // Periodic quiet refresh only while the Hub is open and the server has /bank. + // Periodic quiet refresh only while the balances are on screen (the Hub, or a reader's + // Banking tab) and the server has /bank. int every = Bank.AutoRefreshSeconds; - if (Enabled && _ctx.WindowOpen && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L + if (Enabled && (_ctx.WindowOpen || ReaderWatching) && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L && nowMs - _lastBalanceAt >= BalanceSpacingMs) { _lastAutoRefreshAt = nowMs; @@ -369,7 +409,7 @@ internal sealed class IltBanking : IIltFeature { if (!Enabled) { - ImGui.TextColored(IltStyle.ColTextMute, + SafeImGui.TextColored(IltStyle.ColTextMute, _ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check..."); return; } @@ -381,7 +421,7 @@ internal sealed class IltBanking : IIltFeature ImGui.SameLine(); if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine()); ImGui.SameLine(); - ImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g")); + SafeImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g")); if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV)) { @@ -432,7 +472,7 @@ internal sealed class IltBanking : IIltFeature _ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; }); } if (ImGui.IsItemHovered()) - ImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens." + SafeImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens." + "\nThe server refuses while you are busy or moving."); ImGui.TextColored(IltStyle.ColTeal, "Withdraw"); @@ -463,12 +503,12 @@ internal sealed class IltBanking : IIltFeature { ImGui.SameLine(); if (!ok) ImGui.TextColored(IltStyle.ColHp, "invalid amount"); - else if (notes) ImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals"); - else ImGui.TextDisabled("= " + IltParse.N0(amount)); + else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals"); + else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); } string result = _actionResult; - if (result.Length > 0) ImGui.TextWrapped(result); + if (result.Length > 0) SafeImGui.TextWrapped(result); } private void RenderTransferForm() @@ -478,9 +518,18 @@ internal sealed class IltBanking : IIltFeature ImGui.SetNextItemWidth(200); if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length)) Bank.TransferCurrencyIndex = idx; + bool notes = IltBankCommands.IsNoteTransfer(idx); + int denom = Math.Clamp(Bank.TransferNoteIndex, 0, NoteNames.Length - 1); + if (notes) + { + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Denomination##xfer", ref denom, NoteNames, NoteNames.Length)) Bank.TransferNoteIndex = denom; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The server moves the notes' pyreal value from your bank (/b t n )."); + } ImGui.SetNextItemWidth(200); - ImGui.InputTextWithHint("Amount##xfer", "e.g. 250000, 1.5m, 2b", ref _amountText, 32u); + ImGui.InputTextWithHint("Amount##xfer", notes ? "how many notes" : "e.g. 250000, 1.5m, 2b", ref _amountText, 32u); string target = Bank.TransferTarget; ImGui.SetNextItemWidth(200); if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u)) @@ -490,33 +539,37 @@ internal sealed class IltBanking : IIltFeature if (_amountText.Length > 0) { ImGui.SameLine(); - if (amountOk) ImGui.TextDisabled("= " + IltParse.N0(amount)); - else ImGui.TextColored(IltStyle.ColHp, "invalid amount"); + if (!amountOk) ImGui.TextColored(IltStyle.ColHp, "invalid amount"); + else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(IltBankCommands.NoteValue(denom, amount)) + " pyreals"); + else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); } ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget)); if (ImGui.Button("Send transfer...")) { - int cur = idx; + int cur = idx, note = notes ? denom : -1; long amt = amount; string who = Bank.TransferTarget.Trim(); + string what = notes + ? $"{IltParse.N0(amt)} {IltBankCommands.NoteDenominations[denom].Label} trade notes ({IltParse.N0(IltBankCommands.NoteValue(denom, amt))} pyreals)" + : $"{IltParse.N0(amt)} {Currencies[cur].Name}"; _ctx.Confirm("Confirm bank transfer", - $"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.", + $"Send {what} to {who}?\n\nThis cannot be undone.", () => { - string err = SendTransfer(cur, amt, who); + string err = SendTransfer(cur, amt, who, note); _lastResult = err.Length > 0 ? err : "Transfer sent..."; }, "Send"); } ImGui.EndDisabled(); - if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult); + if (_lastResult.Length > 0) SafeImGui.TextWrapped(_lastResult); } private void RenderTransactionLog() { var snap = _txSnapshot; - ImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})"); + SafeImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})"); ImGui.SameLine(); ImGui.SetNextItemWidth(180); ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u); @@ -543,7 +596,7 @@ internal sealed class IltBanking : IIltFeature ImGui.TableNextRow(); ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g")); ImGui.TableNextColumn(); - ImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type); + SafeImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type); ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount)); ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency); ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs new file mode 100644 index 0000000..a708eb3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs @@ -0,0 +1,316 @@ +// IltBreedingEssence.cs - One carried combat pet essence, as the breeding tracker sees it. +// +// The facts come from the essence's appraisal (ACECustom [AssessmentProperty] qualities: bond 9053, +// male charges 9057, next breeding time float 9056, incense float 9058, neutered bool 9051, the +// male override 50053, juvenile 50054, Chromatic Catalyst 50055, the guardian's Offering 50056, +// maturity kills 9077, the mutation lines 9070..9075) and its LongDesc breeding block ("Sex: ...", +// "Growth: ...", "(shiny - cannot breed)"). Evaluate turns them into what the player needs to know: +// stud or dam, every breeding gate that fails, when it clears, growth, and the boosters applied. +// The gates are ACE PetDevice_Breeding's, with the thresholds from IltBreedingRules. +// +// Pure: no host calls (IltPetBreeding reads the host), so RynthILT.Tests checks it offline. +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// A gate's outcome for one essence. +internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId } + +/// What was read for one essence (host values; pump thread fills it). +internal sealed class BreedEssenceFacts +{ + public int Id; + public string Name = string.Empty; + public uint Wcid; + public bool HasId; + /// The essence's level requirement (a tier fallback for WCIDs outside the table). + public int UseLevel; + public int Bond; + /// The server's explicit sex (Tailoring Kit), or null to derive it from the object id. + public bool? MaleOverride; + public bool Neutered; + public bool JuvenileFlag; + /// PetMaturityKills: -1 when absent (the essence was never bred). + public int MaturityKills = -1; + /// PetMaleBreedingCharges: -1 when absent (a full stud). + public int MaleCharges = -1; + public double MaleRefreshUnix; + public double NextBreedUnix; + public double Incense; + public bool Catalyst; + public bool Offering; + public double MaturityXpMult; + public int MutDamage, MutDamageResist, MutCrit, MutVitality, MutPotency, MutationCount; + public int PotencyStored; + public bool Attuned; + public string LongDesc = string.Empty; +} + +/// One essence evaluated for breeding. Immutable; the UI and the reader JSON read it. +internal sealed record BreedEssence( + int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status, + IReadOnlyList Problems, double ReadyAtUnix, int Charges, int ChargesMax, double RefillAtUnix, + bool Bred, bool Juvenile, int Stage, int Stages, string StageName, int Kills, int KillsRequired, int KillsToNext, + double Incense, bool Catalyst, bool Offering, bool Draught, IReadOnlyList Boosters, + int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency) +{ + /// Every gate passes now. + public bool Ready => Gate == BreedGate.Ready; + /// The stat mutation lines (damage, damage resist, crit, vitality) summed. + public int StatMutations => MutD + MutDR + MutC + MutV; + /// "Stud" or "Dam". + public string Role => Male ? "Stud" : "Dam"; +} + +internal static class IltBreedingEssence +{ + /// Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes). + public static readonly int[] Tiers = { 50, 80, 100, 125, 150, 180, 200, 250, 300 }; + + // ACECustom PetDeviceWcids: one row per combat pet family, tiers 50 .. 300 in order. "a-b" is a + // run of consecutive WCIDs. Rows copied from Source/ACE.Server/Factories/Tables/Wcids/PetDeviceWcids.cs. + private static readonly string[] FamilyRows = + { + "48942,48944,48945,48946,48947,48948,48956,787801001,787801037", + "49213-49219,787801002,787801038", + "49220-49226,787801003,787801039", + "49227-49232,49212,787801004,787801040", + "48972,49234-49239,787801005,787801041", + "49240-49246,787801006,787801042", + "49247-49253,787801007,787801043", + "49254-49259,49233,787801008,787801044", + "49421-49427,787801009,787801045", + "49428-49434,787801010,787801046", + "49435-49441,787801011,787801047", + "49442-49448,787801012,787801048", + "48959,48961,48963,48965,48967,48969,48957,787801013,787801049", + "49261-49267,787801014,787801050", + "49268-49274,787801015,787801051", + "49275-49280,49260,787801016,787801052", + "49282-49287,49281,787801017,787801053", + "49289-49294,49288,787801018,787801054", + "49296-49301,49295,787801019,787801055", + "49303-49308,49302,787801020,787801056", + "49310-49316,787801021,787801057", + "49317-49323,787801022,787801058", + "49324-49330,787801023,787801059", + "49331-49336,49309,787801024,787801060", + "49338-49344,787801025,787801061", + "49345-49351,787801026,787801062", + "49352-49358,787801027,787801063", + "49359-49364,49337,787801028,787801064", + "49366-49372,787801029,787801065", + "49373-49379,787801030,787801066", + "49380-49386,787801031,787801067", + "49387-49392,49365,787801032,787801068", + "49524-49530,787801033,787801069", + "49531-49537,787801034,787801070", + "49538-49544,787801035,787801071", + "49545-49551,787801036,787801072", + }; + + /// Each family row expanded (tests check every row has one WCID per tier). + internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow); + + private static readonly Dictionary TierByWcid = BuildTiers(); + + private static uint[] ExpandRow(string row) + { + var list = new List(9); + foreach (string token in row.Split(',')) + { + int dash = token.IndexOf('-'); + if (dash < 0) { list.Add(uint.Parse(token, CultureInfo.InvariantCulture)); continue; } + uint a = uint.Parse(token.AsSpan(0, dash), NumberStyles.Integer, CultureInfo.InvariantCulture); + uint b = uint.Parse(token.AsSpan(dash + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + for (uint w = a; w <= b; w++) list.Add(w); + } + return list.ToArray(); + } + + private static Dictionary BuildTiers() + { + var d = new Dictionary(); + foreach (uint[] row in Families) + for (int i = 0; i < row.Length && i < Tiers.Length; i++) + d[row[i]] = Tiers[i]; + return d; + } + + /// True for a combat pet essence WCID (the only kind that breeds). + public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid); + + /// The essence tier for a WCID, else the level requirement when it is a tier, else 0. + public static int TierOf(uint wcid, int useLevel = 0) + { + if (TierByWcid.TryGetValue(wcid, out int t)) return t; + return Array.IndexOf(Tiers, useLevel) >= 0 ? useLevel : 0; + } + + /// ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male. + public static bool DeriveIsMale(int objectId) + { + uint h = unchecked((uint)objectId); + h ^= h >> 16; + h = unchecked(h * 0x7feb352d); + h ^= h >> 15; + h = unchecked(h * 0x846ca68b); + h ^= h >> 16; + return (h & 1) == 0; + } + + /// "3h 05m", "42m", "20s" (0 or less = "now"). + public static string Duration(double seconds) + { + if (seconds <= 0) return "now"; + long s = (long)Math.Ceiling(seconds); + if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m"; + if (s >= 60) return $"{s / 60}m"; + return $"{s}s"; + } + + /// + /// Evaluates one essence: role, every failing gate (the first is the headline), the ready time, + /// growth and boosters. is unix seconds. + /// + public static BreedEssence Evaluate(BreedEssenceFacts f, IltBreedingRules r, double nowUnix) + { + string desc = f.LongDesc ?? string.Empty; + bool male = f.MaleOverride ?? DeriveIsMale(f.Id); + int tier = TierOf(f.Wcid, f.UseLevel); + int bond = Math.Max(1, f.Bond); + bool shiny = desc.Contains("(shiny - cannot breed)", StringComparison.OrdinalIgnoreCase); + bool bred = f.MaturityKills >= 0; + bool juvenile = f.JuvenileFlag || desc.Contains("cannot breed yet", StringComparison.OrdinalIgnoreCase); + + // Stud charges refill lazily on the server: full again once the refill time has passed. + int max = Math.Max(0, r.GetInt(IltBreedingRules.MaleCharges)); + int charges = f.MaleCharges < 0 ? max : Math.Min(f.MaleCharges, max); + double refillAt = 0; + double refillH = r.Get(IltBreedingRules.MaleRefillHours); + if (male && f.MaleRefreshUnix > 0 && refillH > 0) + { + refillAt = f.MaleRefreshUnix + refillH * 3600.0; + if (nowUnix >= refillAt) { charges = max; refillAt = 0; } + } + if (male && charges >= max) refillAt = 0; + + // Growth (bred essences only): stage from credited kills, as ACE PetDevice_Maturity. + int required = Math.Max(1, r.GetInt(IltBreedingRules.MaturityKills)); + int stages = Math.Max(1, r.GetInt(IltBreedingRules.MaturityStages)); + int kills = Math.Max(0, f.MaturityKills); + int perStage = Math.Max(1, (int)Math.Ceiling(required / (double)stages)); + int stage = juvenile ? Math.Min(stages, kills / perStage + 1) : stages + 1; + int toNext = juvenile ? Math.Max(0, Math.Min(required, stage * perStage) - kills) : 0; + string stageName = juvenile ? r.StageName(stage) : bred ? "Adult" : string.Empty; + if (juvenile && IltBreedingRules.TryParseGrowth(desc, out string seenName, out int seenStage, out _, out int seenNext, out _, out int seenAdult)) + { + // The appraisal line is the server's own math: prefer it when it is there. + stage = seenStage; + stageName = seenName; + toNext = seenNext; + kills = Math.Max(kills, required - seenAdult); + } + + // Every failing gate, in the order the server checks them. + var problems = new List(); + BreedGate gate = BreedGate.Ready; + void Fail(BreedGate g, string text) + { + if (gate == BreedGate.Ready) gate = g; + problems.Add(text); + } + double readyAt = 0; + if (!f.HasId) Fail(BreedGate.NeedsId, "not appraised yet"); + if (f.Neutered) Fail(BreedGate.Neutered, "neutered (permanent)"); + if (shiny) Fail(BreedGate.Shiny, "shiny essences can't breed"); + if (juvenile) Fail(BreedGate.Growing, $"still growing: {stageName} ({Math.Max(0, required - kills)} kills to Adult)"); + int minTier = r.GetInt(IltBreedingRules.MinTier); + if (tier > 0 && tier < minTier) Fail(BreedGate.LowTier, $"tier {tier} (needs {minTier}+)"); + int minBond = r.GetInt(IltBreedingRules.MinBond); + if (f.HasId && bond < minBond) Fail(BreedGate.LowBond, $"bond {bond}/{minBond}"); + if (male && charges <= 0) + { + Fail(BreedGate.NoCharges, refillAt > 0 ? $"no charges (refill in {Duration(refillAt - nowUnix)})" : "no charges left"); + readyAt = Math.Max(readyAt, refillAt); + } + if (!male && f.NextBreedUnix > nowUnix) + { + Fail(BreedGate.Resting, $"resting ({Duration(f.NextBreedUnix - nowUnix)})"); + readyAt = Math.Max(readyAt, f.NextBreedUnix); + } + + string status = gate switch + { + BreedGate.Ready => male ? $"Ready ({charges}/{max})" : "Ready", + BreedGate.Resting => "Rest " + Duration(f.NextBreedUnix - nowUnix), + BreedGate.NoCharges => refillAt > 0 ? "0/" + max + " refill " + Duration(refillAt - nowUnix) : "0/" + max, + BreedGate.Growing => $"{stageName} {Math.Min(stage, stages)}/{stages}", + BreedGate.Neutered => "Neutered", + BreedGate.Shiny => "Shiny", + BreedGate.LowBond => $"Bond {bond}/{minBond}", + BreedGate.LowTier => $"Tier {tier}", + _ => "ID needed", + }; + + bool draught = f.MaturityXpMult > 1.0001; + var boosters = new List(4); + if (f.Incense > 0) boosters.Add(IltBreedingSupplies.IncenseName(f.Incense)); + if (f.Catalyst) boosters.Add("Chromatic Catalyst"); + if (f.Offering) boosters.Add("Offering of Subjugation"); + if (draught) boosters.Add("Nurturing Draught x" + f.MaturityXpMult.ToString("0.#", CultureInfo.InvariantCulture)); + + return new BreedEssence( + f.Id, f.Name, f.Wcid, f.HasId, tier, bond, male, gate, status, problems, readyAt, + male ? charges : 0, male ? max : 0, male ? refillAt : 0, + bred, juvenile, juvenile ? stage : 0, stages, stageName, kills, required, toNext, + Math.Max(0, f.Incense), f.Catalyst, f.Offering, draught, boosters, + Math.Max(0, f.MutDamage), Math.Max(0, f.MutDamageResist), Math.Max(0, f.MutCrit), Math.Max(0, f.MutVitality), + Math.Max(0, f.MutPotency), shiny, bred && !f.Attuned && desc.Contains("Bond: Unbound", StringComparison.OrdinalIgnoreCase), + Math.Max(0, f.PotencyStored)); + } +} + +/// What a stud + dam pairing would do: the gates both must pass, and the baby's odds. +internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList Blockers, double Incense, double ChanceBest, double ChanceWorst, + double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList Notes); + +internal static class IltBreedingPlanner +{ + /// + /// Plans one pairing. Each stat line comes from one parent, so the baby inherits between the + /// sum of the lower lines and the sum of the higher lines; more inherited mutations lower the + /// stat mutation chance (the decay), so the best case is the fewest. + /// + public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r) + { + var blockers = new List(); + if (!stud.Male) blockers.Add($"{stud.Name} is female: the stud must be male."); + if (dam.Male) blockers.Add($"{dam.Name} is male: the dam must be female."); + if (stud.Id == dam.Id) blockers.Add("Pick two different essences."); + foreach (string p in stud.Problems) blockers.Add($"{stud.Name}: {p}"); + foreach (string p in dam.Problems) blockers.Add($"{dam.Name}: {p}"); + + int lo = Math.Min(stud.MutD, dam.MutD) + Math.Min(stud.MutDR, dam.MutDR) + Math.Min(stud.MutC, dam.MutC) + Math.Min(stud.MutV, dam.MutV); + int hi = Math.Max(stud.MutD, dam.MutD) + Math.Max(stud.MutDR, dam.MutDR) + Math.Max(stud.MutC, dam.MutC) + Math.Max(stud.MutV, dam.MutV); + double incense = r.CombinedIncense(stud.Incense, dam.Incense); + + var notes = new List + { + "The baby goes to the dam's owner: they need a free main-pack slot and burden room.", + $"Both pets in the same room of the breeding area ({r.RoomText()}); both owners *dance* within {r.Get(IltBreedingRules.DanceWindow):0.#}s.", + }; + if (stud.Catalyst || dam.Catalyst) notes.Add("Chromatic Catalyst: the baby rolls a fresh colour."); + if (r.Get(IltBreedingRules.GuardianEnabled) >= 0.5) + notes.Add(stud.Offering || dam.Offering + ? "Offering of Subjugation applied: the mating guardian comes weakened." + : $"A mating guardian rises: kill it within {r.Get(IltBreedingRules.GuardianSeconds):0}s for an Awakened Blessing mutation."); + if (incense > 0) notes.Add($"Incense +{incense * 100:0.#}% is used up by this breed."); + + return new BreedPairPlan(blockers.Count == 0, blockers, incense, + r.StatMutationChance(lo, incense), r.StatMutationChance(hi, incense), + Math.Clamp(r.Get(IltBreedingRules.PotencyMutation), 0, 1), lo, hi, notes); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs new file mode 100644 index 0000000..6ed05f8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs @@ -0,0 +1,445 @@ +// IltBreedingRules.cs - Infinite Leaftide's pet breeding rules as RynthILT knows them. +// +// ACECustom's breeding (Source/ACE.Server/WorldObjects/PetDevice_Breeding.cs, docs/PET_BREEDING_*.md) +// is driven by ServerConfig values the client is never sent. Each rule here therefore has three +// possible sources, best last: +// * ACE default - the ServerConfig default in ACECustom; +// * ILT profile - what Infinite Leaftide runs (deploy/PROD_DEPLOY_PLAN.md: decay 0.1, the +// mating guardian on, pet bond on, the Seedy Motel room); +// * seen on server - read back from this server's own text: the appraisal breeding block +// ("Sex: Male (9/10 breeding charges today) - refills in 3h 10m", "Growth: ..."), +// "@breed-debug" ("Allowed Target: whole landblock 0x106, Variant=2"), and +// breeding chat ("spent a breeding charge: 9/10 left today", "They have 90s ..."). +// A value seen on the server is saved with the character (IltPetState.Breeding) and wins from then on. +// +// Pure: no host calls, so RynthILT.Tests checks every parser offline. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Where a breeding rule's value came from (later = more trusted). +internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 } + +/// One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE). +internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help); + +/// A rule's effective value and where it came from. +internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc); + +/// A value this server showed, saved with the character. +public sealed class IltLearnedRule +{ + public string Key = string.Empty; + public double Value; + public DateTime SeenUtc; +} + +/// One breeding event from chat (ritual, birth, growth, ...), newest last. +public sealed class IltBreedingEvent +{ + public DateTime Utc; + /// ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug. + public string Kind = string.Empty; + public string Text = string.Empty; +} + +/// The breeding tracker's saved part (IltPetState.Breeding). +public sealed class IltBreedingState +{ + /// Rules read back from this server (see IltBreedingRules). + public List Rules = new(); + /// Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet. + public List StageNames = new(); + /// Recent breeding events (capped at IltBreedingRules.MaxEvents). + public List Log = new(); + /// The last "@breed-debug" reply's lines and when it came. + public List LastDebug = new(); + public DateTime LastDebugUtc; +} + +/// What one "@breed-debug" reply said. +internal sealed record BreedDebugInfo(bool? Enabled, string Location, uint AllowedLandblock, int AllowedVariant, string AllowedKind, + bool? LocationOk, string ActivePet, string PetSex, int Partners); + +internal sealed class IltBreedingRules +{ + // ── Rule keys ─────────────────────────────────────────────────────────── + public const string Landblock = "landblock"; + public const string Variant = "variant"; + public const string DanceWindow = "dance_window_s"; + public const string MinTier = "min_tier"; + public const string MinBond = "min_bond"; + public const string MaleCharges = "male_charges"; + public const string MaleRefillHours = "male_refill_h"; + public const string FemaleRestHours = "female_rest_h"; + public const string BaseMutation = "base_mutation"; + public const string MutationDecay = "mutation_decay"; + public const string MutationFloor = "mutation_floor"; + public const string PotencyMutation = "potency_mutation"; + public const string IncenseCap = "incense_cap"; + public const string Inheritance = "inheritance"; + public const string GuardianEnabled = "guardian_enabled"; + public const string GuardianSeconds = "guardian_s"; + public const string MaturityKills = "maturity_kills"; + public const string MaturityStages = "maturity_stages"; + public const string MaturityShare = "maturity_share"; + + /// Breeding events kept with the character. + public const int MaxEvents = 60; + + /// ACECustom's default growth stage names (pet_maturity_stage_names). + public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" }; + + /// Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan. + public static readonly BreedRuleDef[] Defs = + { + new(Landblock, "Breeding room landblock", "hex", 0x0106, null, + "pet_breeding_allowed_landblock: the Seedy Motel (Ruggan's Annex, portal by Prof. Ruggan in Lin 54.7S 73.5E)."), + new(Variant, "Breeding room variant", "", 2, null, "pet_breeding_allowed_variant: the landblock variant the room is in."), + new(DanceWindow, "Dance window", "s", 5, null, "Both owners must *dance* (or @dance) within this many seconds."), + new(MinTier, "Minimum essence tier", "", 100, null, "Both parents must be at least this tier (50, 80, 100, ... 300)."), + new(MinBond, "Minimum bond", "", 100, null, "Both parents need this bond level (bond grows from kills; pet_bond must be on)."), + new(MaleCharges, "Stud charges", "", 10, null, "pet_breeding_male_max_charges: breeds a male can sire per refill."), + new(MaleRefillHours, "Stud refill", "h", 24, null, "pet_breeding_male_charge_reset_hours: charges refill this long after the last refill."), + new(FemaleRestHours, "Dam rest", "h", 4, null, "A female rests this long after each breed before she can breed again."), + new(BaseMutation, "Stat mutation chance", "%", 0.05, null, "pet_breeding_mutation_chance: the base chance of a stat mutation."), + new(MutationDecay, "Mutation decay", "", 0.0, 0.1, + "pet_breeding_mutation_decay: each stat mutation the baby inherits divides the chance by (1 + decay x mutations)."), + new(MutationFloor, "Mutation floor", "%", 0.02, null, "The stat mutation chance never drops below this."), + new(PotencyMutation, "Potency mutation chance", "%", 0.03, null, "An independent roll for a potency mutation."), + new(IncenseCap, "Incense cap", "%", 0.50, null, "Both parents' incense together adds at most this much."), + new(Inheritance, "Dominant line weight", "%", 0.55, null, "Each stat line comes from one parent, 55 / 45."), + new(GuardianEnabled, "Mating guardian", "on/off", 0, 1, + "pet_breeding_guardian_enabled: a spirit rises after the ritual; killing it in time grants an Awakened Blessing mutation."), + new(GuardianSeconds, "Guardian timer", "s", 90, null, "How long the two parents have to kill the guardian."), + new(MaturityKills, "Kills to adulthood", "", 300, null, "pet_maturity_kills_required: a bred baby grows up with this many credited kills."), + new(MaturityStages, "Growth stages", "", 5, null, "pet_maturity_stages: the growth stages before Adult."), + new(MaturityShare, "Kill credit share", "%", 0.10, null, + "A kill counts when the pet dealt this share of the victim's health and the victim's level is at least the essence tier."), + }; + + private static readonly Dictionary DefByKey = BuildIndex(); + + private static Dictionary BuildIndex() + { + var d = new Dictionary(StringComparer.Ordinal); + foreach (BreedRuleDef def in Defs) d[def.Key] = def; + return d; + } + + private readonly IltBreedingState _state; + + /// The saved breeding state; learned values are read from and written to it. + public IltBreedingRules(IltBreedingState state) => _state = state; + + /// The saved state these rules read and update. + public IltBreedingState State => _state; + + /// A copy that never changes (the render thread reads it while the pump learns). + public IltBreedingRules Frozen() + { + var copy = new IltBreedingState { StageNames = new List(_state.StageNames) }; + foreach (IltLearnedRule l in _state.Rules) + copy.Rules.Add(new IltLearnedRule { Key = l.Key, Value = l.Value, SeenUtc = l.SeenUtc }); + return new IltBreedingRules(copy); + } + + /// The effective value of rule (0 for an unknown key). + public double Get(string key) => Value(key).Value; + + /// A whole-number rule (charges, kills, tiers). + public int GetInt(string key) => (int)Math.Round(Get(key)); + + /// The effective value and its source. + public BreedRuleValue Value(string key) + { + if (!DefByKey.TryGetValue(key, out BreedRuleDef? def)) + return new BreedRuleValue(new BreedRuleDef(key, key, "", 0, null, ""), 0, BreedRuleSource.AceDefault, default); + foreach (IltLearnedRule l in _state.Rules) + if (l.Key == key) return new BreedRuleValue(def, l.Value, BreedRuleSource.Server, l.SeenUtc); + return def.IltProfile.HasValue + ? new BreedRuleValue(def, def.IltProfile.Value, BreedRuleSource.IltProfile, default) + : new BreedRuleValue(def, def.AceDefault, BreedRuleSource.AceDefault, default); + } + + /// Every rule's effective value, in display order. + public List All() + { + var list = new List(Defs.Length); + foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key)); + return list; + } + + /// Records a value the server showed. True when it changed what RynthILT knew. + public bool Learn(string key, double value, DateTime utc) + { + if (!DefByKey.ContainsKey(key) || double.IsNaN(value) || double.IsInfinity(value)) return false; + foreach (IltLearnedRule l in _state.Rules) + { + if (l.Key != key) continue; + bool changed = Math.Abs(l.Value - value) > 1e-9; + l.Value = value; + l.SeenUtc = utc; + return changed; + } + _state.Rules.Add(new IltLearnedRule { Key = key, Value = value, SeenUtc = utc }); + return true; + } + + /// Applies every (key, value) an observer returned. True when anything changed. + public bool LearnAll(IEnumerable<(string Key, double Value)> seen, DateTime utc) + { + bool changed = false; + foreach ((string k, double v) in seen) changed |= Learn(k, v, utc); + return changed; + } + + /// Records a growth stage's name (1-based) as the server spelled it. + public bool LearnStageName(int stage, string name) + { + name = (name ?? string.Empty).Trim(); + if (stage < 1 || stage > 50 || name.Length == 0 || name.Length > 40) return false; + while (_state.StageNames.Count < stage) _state.StageNames.Add(string.Empty); + if (_state.StageNames[stage - 1] == name) return false; + _state.StageNames[stage - 1] = name; + return true; + } + + /// The name of growth stage (1-based): seen on the server, else ACE's default, else "Stage N". + public string StageName(int stage) + { + if (stage >= 1 && stage <= _state.StageNames.Count && _state.StageNames[stage - 1].Length > 0) + return _state.StageNames[stage - 1]; + if (stage >= 1 && stage <= DefaultStageNames.Length && GetInt(MaturityStages) == DefaultStageNames.Length) + return DefaultStageNames[stage - 1]; + return "Stage " + stage.ToString(CultureInfo.InvariantCulture); + } + + /// Appends an event, dropping the oldest past . + public void AddEvent(string kind, string text, DateTime utc) + { + _state.Log.Add(new IltBreedingEvent { Utc = utc, Kind = kind, Text = text }); + if (_state.Log.Count > MaxEvents) _state.Log.RemoveRange(0, _state.Log.Count - MaxEvents); + } + + // ── Mutation odds (ACE PetDevice_Breeding) ────────────────────────────── + + /// + /// The chance of a stat mutation for a baby that inherits + /// stat mutations, with from both parents (already capped): + /// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1). + /// + public double StatMutationChance(int babyStatMutations, double incense) + { + double decay = Math.Max(0, Get(MutationDecay)); + double raw = (Get(BaseMutation) + Math.Max(0, incense)) / (1.0 + decay * Math.Max(0, babyStatMutations)); + return Math.Clamp(Math.Max(Get(MutationFloor), raw), 0.0, 1.0); + } + + /// Both parents' incense together, capped at the incense cap. + public double CombinedIncense(double a, double b) => Math.Clamp(Math.Max(0, a) + Math.Max(0, b), 0.0, Math.Max(0, Get(IncenseCap))); + + // ── Observers: what the server's own text says about its rules ────────── + + private const RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + + private static readonly Regex MaleLine = new(@"Sex:\s*Male\s*\((\d+)\s*/\s*(\d+) breeding charges today\)(?:\s*-\s*refills in (?:(\d+)h\s*)?(?:(\d+)m)?)?", Rx); + private static readonly Regex GrowthLine = new(@"Growth:\s*(.+?)\s+(\d+)\s*/\s*(\d+)\s*-\s*(\d+) kills to (.+?)(?:,\s*(\d+) to Adult)?\s*$", Rx | RegexOptions.Multiline); + private static readonly Regex ChargeSpent = new(@"spent a breeding charge:\s*(\d+)\s*/\s*(\d+) left today", Rx); + private static readonly Regex GuardianRise = new(@"They have (\d+)s to bring it down together", Rx); + private static readonly Regex GrownInto = new(@"has grown into an? (.+?)!.*\((\d+)\s*/\s*(\d+)\)", Rx); + private static readonly Regex DanceWindowLine = new(@"\*dance\* within (\d+(?:\.\d+)?) seconds", Rx); + private static readonly Regex DebugEnabled = new(@"Breeding System Enabled:\s*(True|False)", Rx); + private static readonly Regex DebugLocation = new(@"Your Location:\s*(.+)$", Rx); + private static readonly Regex DebugAllowed = new(@"Allowed Target:\s*(anywhere|whole landblock|exact cell)\s*0x([0-9A-F]+),\s*Variant=(-?\d+)\s*=>\s*Location Match:\s*(VALID|INVALID)", Rx); + private static readonly Regex DebugPet = new(@"Your Active Pet:\s*(.+)$", Rx); + private static readonly Regex DebugSex = new(@"^\s*Sex:\s*(.+)$", Rx); + private static readonly Regex DebugPartners = new(@"(?:Eligible breeding partners nearby|Valid Partner Candidates within 30m):\s*(\d+)", Rx); + + /// + /// What an essence's appraisal text says: the stud's charge max and refill window (from the + /// "refills in" countdown against the essence's last refill time), and the growth stage count. + /// + /// The appraisal LongDesc (string 16). + /// The essence's PetMaleChargesRefreshTime (0 = not sent). + /// Now, unix seconds. + public static List<(string Key, double Value)> FromAppraisal(string longDesc, double maleRefreshUnix, double nowUnix) + { + var seen = new List<(string, double)>(); + if (string.IsNullOrEmpty(longDesc)) return seen; + + Match m = MaleLine.Match(longDesc); + if (m.Success) + { + if (int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) + seen.Add((MaleCharges, max)); + if ((m.Groups[3].Success || m.Groups[4].Success) && maleRefreshUnix > 0) + { + int h = m.Groups[3].Success ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) : 0; + int min = m.Groups[4].Success ? int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture) : 0; + double refillAt = nowUnix + h * 3600.0 + min * 60.0; + double hours = Math.Round((refillAt - maleRefreshUnix) / 3600.0); + // The countdown is minute-rounded; only a whole-hour window that makes sense is taken. + if (hours >= 1 && hours <= 24 * 14) seen.Add((MaleRefillHours, hours)); + } + } + + Match g = GrowthLine.Match(longDesc); + if (g.Success && int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) + seen.Add((MaturityStages, stages)); + return seen; + } + + /// + /// The growth line of an appraisal: current stage name, stage, stages, kills to the next stage + /// and to adulthood (-1 when the line has no "to Adult" part, i.e. the last stage). + /// + public static bool TryParseGrowth(string longDesc, out string stageName, out int stage, out int stages, out int toNext, out string nextName, out int toAdult) + { + stageName = nextName = string.Empty; + stage = stages = toNext = toAdult = 0; + if (string.IsNullOrEmpty(longDesc)) return false; + Match g = GrowthLine.Match(longDesc); + if (!g.Success) return false; + stageName = g.Groups[1].Value.Trim(); + int.TryParse(g.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage); + int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stages); + int.TryParse(g.Groups[4].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toNext); + nextName = g.Groups[5].Value.Trim(); + if (g.Groups[6].Success) int.TryParse(g.Groups[6].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toAdult); + else { toAdult = toNext; nextName = "Adult"; } + return true; + } + + /// What one chat line says about the rules (a line can say nothing). + public static List<(string Key, double Value)> FromChat(string line) + { + var seen = new List<(string, double)>(); + if (string.IsNullOrEmpty(line)) return seen; + + Match m = ChargeSpent.Match(line); + if (m.Success && int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) + seen.Add((MaleCharges, max)); + + m = GuardianRise.Match(line); + if (m.Success) + { + seen.Add((GuardianEnabled, 1)); + if (int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0 && s < 3600) + seen.Add((GuardianSeconds, s)); + } + else if (line.Contains("The union stirs something", StringComparison.OrdinalIgnoreCase)) + seen.Add((GuardianEnabled, 1)); + + m = GrownInto.Match(line); + if (m.Success && int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) + seen.Add((MaturityStages, stages)); + + m = DanceWindowLine.Match(line); + if (m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double w) && w > 0 && w < 600) + seen.Add((DanceWindow, w)); + + foreach (string part in line.Split('\n')) + { + m = DebugAllowed.Match(part); + if (!m.Success) continue; + if (uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb)) + seen.Add((Landblock, lb)); + if (int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) + seen.Add((Variant, v)); + } + return seen; + } + + /// The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line. + public static bool TryParseGrownInto(string line, out int stage, out string name) + { + stage = 0; + name = string.Empty; + Match m = GrownInto.Match(line ?? string.Empty); + if (!m.Success || !int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage)) return false; + name = m.Groups[1].Value.Trim(); + return name.Length > 0; + } + + /// True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one). + public static bool IsDebugLine(string text) + { + if (string.IsNullOrEmpty(text)) return false; + return text.Contains("PET BREEDING DIAGNOSTICS", StringComparison.OrdinalIgnoreCase) + || DebugEnabled.IsMatch(text) || DebugLocation.IsMatch(text) || DebugAllowed.IsMatch(text) + || DebugPet.IsMatch(text) || DebugPartners.IsMatch(text) + || text.TrimStart().StartsWith("Sex:", StringComparison.OrdinalIgnoreCase) + || text.Contains("Ensure your partner has their pet summoned", StringComparison.OrdinalIgnoreCase) + || IsDebugEnd(text); + } + + /// The reply's closing rule of '=' (alone, or ending the whole message). + public static bool IsDebugEnd(string text) + => !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal); + + /// Parses an "@breed-debug" reply (any mix of whole messages and single lines). + public static BreedDebugInfo ParseDebug(IEnumerable lines) + { + bool? enabled = null, ok = null; + string location = string.Empty, kind = string.Empty, pet = string.Empty, sex = string.Empty; + uint lb = 0; + int variant = -1, partners = -1; + foreach (string text in lines) + { + foreach (string raw in (text ?? string.Empty).Split('\n')) + { + string l = raw.TrimEnd('\r'); + Match m; + if ((m = DebugEnabled.Match(l)).Success) enabled = m.Groups[1].Value.Equals("True", StringComparison.OrdinalIgnoreCase); + else if ((m = DebugAllowed.Match(l)).Success) + { + kind = m.Groups[1].Value.ToLowerInvariant(); + uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb); + int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out variant); + ok = m.Groups[4].Value.Equals("VALID", StringComparison.OrdinalIgnoreCase); + } + else if ((m = DebugLocation.Match(l)).Success) location = m.Groups[1].Value.Trim(); + else if ((m = DebugPet.Match(l)).Success) pet = m.Groups[1].Value.Trim(); + else if ((m = DebugPartners.Match(l)).Success) int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out partners); + else if ((m = DebugSex.Match(l)).Success) sex = m.Groups[1].Value.Trim(); + } + } + return new BreedDebugInfo(enabled, location, lb, variant, kind, ok, pet, sex, partners); + } + + /// "0x0106 variant 2" (or "anywhere") for the rules list. + public string RoomText() + { + uint lb = (uint)Math.Max(0, Get(Landblock)); + int variant = GetInt(Variant); + if (lb == 0) return "anywhere"; + string place = lb > 0xFFFF ? "cell 0x" + lb.ToString("X8", CultureInfo.InvariantCulture) : "landblock 0x" + lb.ToString("X4", CultureInfo.InvariantCulture); + return variant >= 0 ? place + " variant " + variant.ToString(CultureInfo.InvariantCulture) : place; + } + + /// A rule value for display: "5%", "24h", "0x0106", "on", "10". + public static string Format(BreedRuleValue v) + { + switch (v.Def.Unit) + { + case "%": return (v.Value * 100.0).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + case "h": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "h"; + case "s": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "s"; + case "hex": return "0x" + ((uint)Math.Max(0, v.Value)).ToString("X4", CultureInfo.InvariantCulture); + case "on/off": return v.Value >= 0.5 ? "on" : "off"; + default: return v.Value.ToString("0.##", CultureInfo.InvariantCulture); + } + } + + /// "ACE default", "ILT profile" or "seen on server". + public static string SourceText(BreedRuleSource s) => s switch + { + BreedRuleSource.Server => "seen on server", + BreedRuleSource.IltProfile => "ILT profile", + _ => "ACE default", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs new file mode 100644 index 0000000..33381d0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs @@ -0,0 +1,112 @@ +// IltBreedingSupplies.cs - Ivo's breeding supplies (ACECustom, Seedy Motel vendor) and when each can +// be used on an essence. +// +// WCIDs, prices and refusals copied from ACECustom (Player_Use.cs HandleActionUseOnTarget, the +// PetDevice.BreedingMath incense constants, docs/PET_BREEDING_PLAYER_GUIDE.md). RynthILT applies +// only the breeding boosters (incense, Nurturing Draught, Chromatic Catalyst, Offering of +// Subjugation), and only after the player confirms; the Neutering Kit is permanent and the kits, +// serum and tinctures are cosmetic, so those are counted, never used from here. +// +// Pure: RynthILT.Tests checks the refusals offline. +using System; +using System.Globalization; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it. +internal sealed record BreedSupplyDef(string Key, uint Wcid, string Name, string Effect, long Price, bool Apply); + +internal static class IltBreedingSupplies +{ + public const string LesserIncense = "incense1"; + public const string RefinedIncense = "incense2"; + public const string ExquisiteIncense = "incense3"; + public const string Draught = "draught"; + public const string Catalyst = "catalyst"; + public const string Offering = "offering"; + public const string NeuteringKit = "neuter"; + public const string TailoringKit = "tailor"; + public const string FilledTailoringKit = "tailor_filled"; + public const string Serum = "serum"; + public const string Solidifying = "solidify"; + public const string Fading = "fade"; + + /// Every supply, boosters first. + public static readonly BreedSupplyDef[] All = + { + new(LesserIncense, 78780250, "Lesser Courtship Incense", "+2.5% stat mutation chance on the next breed.", 1_250_000, true), + new(RefinedIncense, 78780251, "Refined Courtship Incense", "+5% stat mutation chance on the next breed.", 2_500_000, true), + new(ExquisiteIncense, 78780252, "Exquisite Courtship Incense", "+10% stat mutation chance on the next breed.", 5_000_000, true), + new(Draught, 78780253, "Nurturing Draught", "A juvenile earns 2x maturity kill credit until adulthood.", 2_500_000, true), + new(Catalyst, 78780254, "Chromatic Catalyst", "The next baby rolls a fresh colour.", 2_500_000, true), + new(Offering, 78780255, "Offering of Subjugation", "The next mating guardian comes weakened.", 2_500_000, true), + new(NeuteringKit, 78780258, "Neutering Kit", "Permanently stops an essence from breeding.", 2_500_000, false), + new(TailoringKit, 78780259, "Tailoring Kit", "Extracts an essence's appearance.", 125_000_000, false), + new(FilledTailoringKit, 78780260, "Filled Tailoring Kit", "Applies an extracted appearance.", 0, false), + new(Serum, 78780257, "Mutagenic Serum", "Re-rolls an essence's colour.", 25_000_000, false), + new(Solidifying, 78780262, "Solidifying Tincture", "Makes the summoned pet less translucent.", 12_500_000, false), + new(Fading, 78780263, "Fading Tincture", "Makes the summoned pet more translucent.", 12_500_000, false), + }; + + /// The supply with this key, or null. + public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key); + + /// The incense bonus a supply gives (0 for anything else). + public static double IncenseBonus(string key) => key switch + { + LesserIncense => 0.025, + RefinedIncense => 0.05, + ExquisiteIncense => 0.10, + _ => 0, + }; + + /// "Refined incense +5%" for an applied bonus. + public static string IncenseName(double bonus) + { + string grade = bonus >= 0.0999 ? "Exquisite" : bonus >= 0.0499 ? "Refined" : "Lesser"; + return $"{grade} incense +{(bonus * 100).ToString("0.#", CultureInfo.InvariantCulture)}%"; + } + + /// + /// Why the server would refuse on (the server's own + /// checks, so nothing is spent on a refusal), or null when it would take it. + /// + public static string? RefuseReason(BreedSupplyDef s, BreedEssence e, IltBreedingRules r) + { + if (!s.Apply) return "Not applied from here."; + double incense = IncenseBonus(s.Key); + if (incense > 0) + { + if (e.Gate == BreedGate.Neutered) return "A neutered essence can't take incense."; + if (e.Incense >= incense - 1e-6) return $"Already primed with equal or stronger incense (+{e.Incense * 100:0.#}%)."; + return null; + } + return s.Key switch + { + Draught when !e.Juvenile => "Only a juvenile (still growing) can take a Nurturing Draught.", + Draught when e.Draught => "Already under a Nurturing Draught.", + Catalyst when e.Catalyst => "Already infused with a Chromatic Catalyst.", + Offering when r.Get(IltBreedingRules.GuardianEnabled) < 0.5 => "Mating guardians are off on this server.", + Offering when e.Offering => "Already under an Offering of Subjugation.", + _ => null, + }; + } + + /// A warning to show in the confirmation (a weaker incense being replaced), or "". + public static string Warning(BreedSupplyDef s, BreedEssence e) + { + double incense = IncenseBonus(s.Key); + if (incense > 0 && e.Incense > 0 && e.Incense < incense) + return $" It replaces the +{e.Incense * 100:0.#}% incense already on it (that one is lost)."; + return string.Empty; + } + + /// "1.25M", "125M", "-" for a price. + public static string PriceText(long price) + { + if (price <= 0) return "-"; + if (price >= 1_000_000) return (price / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M"; + if (price >= 1_000) return (price / 1_000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; + return price.ToString(CultureInfo.InvariantCulture); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs index 2dd64a8..8380011 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs @@ -15,6 +15,7 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -214,9 +215,9 @@ internal sealed class IltBuffKeepers : IIltFeature int cd = G.DispelCooldownSeconds; ImGui.SetNextItemWidth(100); if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd); - ImGui.TextDisabled("Status: " + _dispelStatus); + SafeImGui.TextDisabled("Status: " + _dispelStatus); var harm = _harmfulNow; - if (harm.Length > 0) ImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm)); + if (harm.Length > 0) SafeImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm)); if (ImGui.TreeNode("Always / never dispel lists")) { EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc"); @@ -228,7 +229,7 @@ internal sealed class IltBuffKeepers : IIltFeature ImGui.TextColored(IltStyle.ColTeal, "Surging Strength"); bool ss = G.SurgingStrength; if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss; - ImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus)); + SafeImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus)); } private void EditList(string label, List list, ref string buffer, string id) @@ -237,7 +238,7 @@ internal sealed class IltBuffKeepers : IIltFeature var snap = list.ToArray(); for (int i = 0; i < snap.Length; i++) { - ImGui.BulletText(snap[i]); + SafeImGui.BulletText(snap[i]); ImGui.SameLine(); string victim = snap[i]; if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim)); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs index dd1f13e..4581c2a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs @@ -132,7 +132,9 @@ internal sealed class IltCharmTracker sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"'); sb.Append(",\"lastSeen\":\"") .Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd")) - .Append("\"}"); + .Append('"'); + // The carried copy a reader's Toggle uses ("RynthILT.Data" ToggleCharm); 0 = none carried. + sb.Append(",\"toggleId\":").Append(unchecked((uint)r.ToggleId)).Append('}'); } sb.Append("]}"); return sb.ToString(); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs index c1ff337..fe85b08 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs @@ -1,4 +1,6 @@ -// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm in one table. +// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm and the +// Guardian Hand, with their toggles. Other plugins read the same list and toggle through +// "RynthILT.Data" (BuildReaderJson / ToggleFromReader). // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // // Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered @@ -14,6 +16,7 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -68,6 +71,52 @@ internal sealed class IltCharms : IIltFeature _lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item) } + /// + /// A Toggle from another plugin ("RynthILT.Data" ToggleCharm). Only + /// a registry charm or Guardian Hand the player carries is used, so a reader can't make the + /// client use anything else. Pump thread. True when it was used. + /// + public bool ToggleFromReader(uint id) + { + if (id == 0 || id > int.MaxValue) return false; + var inv = _ctx.Inventory; + foreach (var wo in inv.Items()) + { + if (wo.Id != (int)id) continue; + if (inv.CharmDefFor(wo) == null && !IsGuardianHand(wo)) return false; + Toggle(wo.Id); + return true; + } + return false; + } + + /// + /// The "RynthILT.Data" charms JSON: the registry charms + /// (IltCharmTracker.BuildJson) plus a "hands" array, every Guardian Hand carried now with its + /// object id (the Toggle's id), status and the server's switch. Pump thread. + /// + public string BuildReaderJson() + { + string json = _tracker.BuildJson(); + if (!_ctx.Options.IsIltLikeWorld || !json.EndsWith("]}", StringComparison.Ordinal)) return json; + var inv = _ctx.Inventory; + string server = _ctx.Options.Get(IltFeature.Charm("Guardian Hand")) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + var sb = new System.Text.StringBuilder(json, 0, json.Length - 1, json.Length + 256); + sb.Append(",\"hands\":["); + bool first = true; + foreach (var wo in inv.Items().Where(IsGuardianHand)) + { + if (!first) sb.Append(','); + first = false; + string active = inv.CharmStatus(wo) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + sb.Append("{\"id\":").Append(unchecked((uint)wo.Id)); + sb.Append(",\"name\":\"").Append(IltStyle.JsonEscape(wo.Name)).Append('"'); + sb.Append(",\"active\":\"").Append(active).Append('"'); + sb.Append(",\"server\":\"").Append(server).Append("\"}"); + } + return sb.Append("]}").ToString(); + } + // ── IIltFeature ───────────────────────────────────────────────────────── public void Tick(long nowMs) @@ -93,13 +142,13 @@ internal sealed class IltCharms : IIltFeature var rows = _rows; if (rows.Length == 0) { - ImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms."); + SafeImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms."); RenderGuardianHand(); return; } int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On); - ImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active"); + SafeImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active"); ImGui.SameLine(); if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; }); @@ -133,16 +182,16 @@ internal sealed class IltCharms : IIltFeature ImGui.TableNextColumn(); bool carried = r.Acquired == "carried"; if (carried) ImGui.TextUnformatted(r.Def.Name); - else ImGui.TextColored(IltStyle.ColTextMute, r.Def.Name); - if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) ImGui.SetTooltip(r.Def.Effect); + else SafeImGui.TextColored(IltStyle.ColTextMute, r.Def.Name); + if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) SafeImGui.SetTooltip(r.Def.Effect); ImGui.TableNextColumn(); - if (carried) ImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried"); + if (carried) SafeImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried"); else if (r.Acquired == "seen") { ImGui.TextColored(IltStyle.ColAmber, "Stored"); if (ImGui.IsItemHovered() && r.LastSeenUtc != default) - ImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd")); + SafeImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd")); } else ImGui.TextDisabled("No"); @@ -188,12 +237,12 @@ internal sealed class IltCharms : IIltFeature foreach (var h in hands) { ImGui.PushID(h.Id); - if (h.ServerDisabled) ImGui.TextDisabled($"{h.Name} - disabled on this server"); + if (h.ServerDisabled) SafeImGui.TextDisabled($"{h.Name} - disabled on this server"); else { var col = h.Status == IltTri.On ? IltStyle.ColGreen : h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber; - ImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? "); + SafeImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? "); ImGui.SameLine(); ImGui.TextUnformatted(h.Name); ImGui.SameLine(); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs index 94faab3..1a31b5d 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs @@ -2,7 +2,7 @@ // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // // Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb, -// /ilt features, the login probe, ...) goes through this one queue so that: +// the login probe, /myquests, ...) goes through this one queue so that: // * only one capture is in flight at a time (replies can't be attributed to the wrong // request), // * reply lines can be eaten so a Hub refresh doesn't spam the chat window, @@ -21,6 +21,12 @@ internal sealed class IltChatRequest public string Command = string.Empty; /// True for lines that belong to this reply (captured, refresh the idle timer). public Func IsResponseLine = _ => false; + /// + /// Optional: only these response lines arm / refresh the idle timer. Header / banner lines + /// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch: + /// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:). + /// + public Func? ArmsIdle; /// Optional: a line that ends the reply immediately (it is captured too). public Func? IsTerminator; /// The reply is complete after this long with no new response line. @@ -55,6 +61,8 @@ internal sealed class IltChatCapture private IltChatResult? _activeResult; private long _sentAt; private long _lastLineAt; + /// True once a response line that arms idle has arrived (always true when is null). + private bool _idleArmed; /// Minimum spacing between two sends so the server's own command throttles aren't tripped. private const long SendSpacingMs = 400; @@ -102,9 +110,11 @@ internal sealed class IltChatCapture if (_active != null && _activeResult != null) { bool gotAny = _activeResult.Lines.Count > 0; - if (gotAny && now - _lastLineAt >= _active.IdleEndMs) + // Idle completion only after a progress line when ArmsIdle is set (header alone is not enough). + bool idleReady = _active.ArmsIdle == null || _idleArmed; + if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs) Finish(); - else if (!gotAny && now - _sentAt >= _active.FirstLineTimeoutMs) + else if ((!gotAny || !idleReady) && now - _sentAt >= _active.FirstLineTimeoutMs) { _activeResult.TimedOut = true; Finish(); @@ -147,7 +157,12 @@ internal sealed class IltChatCapture if (!_active.IsResponseLine(text)) return false; _activeResult.Lines.Add(text); - _lastLineAt = NowMs; + // Header-only replies (e.g. /aug dashes + banner) must not start the idle clock. + if (_active.ArmsIdle == null || _active.ArmsIdle(text)) + { + _idleArmed = true; + _lastLineAt = NowMs; + } RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}"); return _active.Eat; } @@ -179,6 +194,7 @@ internal sealed class IltChatCapture _activeResult = result; _sentAt = now; _lastLineAt = now; + _idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line _lastSendAt = now; RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})"); _host.InvokeChatParser(req.Command); @@ -190,6 +206,7 @@ internal sealed class IltChatCapture var res = _activeResult; _active = null; _activeResult = null; + _idleArmed = false; if (req == null || res == null) return; RynthLog.Trace(LogCat.IltChat, $"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " + diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs index 09e8e9f..31f3b48 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs @@ -1,13 +1,17 @@ // IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab). // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // -// Chunk: uses a Lugian (Aetheria) Hammer on eligible items, one at a time: +// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time: // Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged -// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and -// max level (int 319) under the configured cap (Coalesced always qualifies). +// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), no kept +// C / CD / CDR rating (gear ints 372 / 374 / 375; on by default), and max level +// (int 319, up to 10 on ILT) under the configured cap (Coalesced always qualifies). // Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179), // not equipped, not never-chunk, cleave (292) <= 1. // Peace mode only unless ChunkInCombat; waits for the result line (10 s max). +// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...) +// are loot and chunk nothing: the server answers with no result line, so every item timed out +// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15). // Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. Needs the // AutoCraftingEnabled stamp; 30 min ± 2 min interval, first attempt ~1 min after enable. using System; @@ -15,6 +19,7 @@ using System.Collections.Generic; using System.Linq; using ImGuiNET; using RynthCore.Loot; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -60,10 +65,14 @@ internal sealed class IltChunkClap : IIltFeature // ── Chunk ─────────────────────────────────────────────────────────────── + /// Infinite Leaftide's chunking tool. + internal const string HammerName = "Lugian Aetheria Hammer"; + + /// True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it. + internal static bool IsChunkHammer(string name) => name.Equals(HammerName, StringComparison.OrdinalIgnoreCase); + private WorldObject? FindHammer() - => _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase) - || n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase) - || n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase)); + => _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo)); /// True/false when decidable; null when appraisal is still needed. private bool? IsChunkableAetheria(WorldObject wo) @@ -77,9 +86,24 @@ internal sealed class IltChunkClap : IIltFeature if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; } if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false; if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false; - return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel); + if (KeptForRatings(G, inv.Int(wo, IltInventory.IntGearCrit), inv.Int(wo, IltInventory.IntGearCritDamage), + inv.Int(wo, IltInventory.IntGearCritDamageResist))) + return false; + return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < ClampUnderLevel(G.ChunkAetheriaUnderLevel); } + /// The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level). + internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1); + + /// + /// True when an aetheria's C / CD / CDR rating is one the settings keep (any rating above 0 with + /// its keep switch on). Pure: the tests drive it. + /// + internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist) + => (g.KeepAetheriaWithCrit && crit > 0) + || (g.KeepAetheriaWithCritDamage && critDamage > 0) + || (g.KeepAetheriaWithCritDamageResist && critDamageResist > 0); + private bool? IsChunkableCorrupted(WorldObject wo) { if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false; @@ -109,6 +133,7 @@ internal sealed class IltChunkClap : IIltFeature RynthLog.Trace(LogCat.IltGear, $"ChunkNow()"); _manualPass = true; _lastChunkAt = 0; + _skip.Clear(); // a manual pass gives the items that got no answer another try _chunkStatus = "manual pass started"; } @@ -120,6 +145,7 @@ internal sealed class IltChunkClap : IIltFeature { if (now - _waitStartedAt < ChunkResultWaitMs) return; _skip.Add(_waitingOn); // no result line — don't hammer the same item forever + RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)_waitingOn:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass"); _waitingOn = 0; } if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return; @@ -129,11 +155,12 @@ internal sealed class IltChunkClap : IIltFeature if (_ctx.Inventory.IsBusy) return; var hammer = FindHammer(); - if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; } + if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; } var target = NextChunkTarget(); if (target == null) { - _chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible"; + _chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible") + + (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : ""); _manualPass = false; return; } @@ -216,23 +243,43 @@ internal sealed class IltChunkClap : IIltFeature TickClap(nowMs); } + internal enum ChunkResult { None, Busy, Done, Refused } + + /// + /// What a chat line says about the chunk in flight. ILT names the item and the tool ("You + /// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted + /// item with the hammer, powder or shatter is a result too (combat's "You smash Foo for 147" + /// names neither). Pure: the tests drive it. + /// + internal static ChunkResult ClassifyChat(string text) + { + if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase)) + return ChunkResult.Busy; + if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Refused; + if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Done; + if (text.Contains("corrupted", StringComparison.OrdinalIgnoreCase) + && (text.Contains("hammer", StringComparison.OrdinalIgnoreCase) || text.Contains("powder", StringComparison.OrdinalIgnoreCase) + || text.Contains("shatter", StringComparison.OrdinalIgnoreCase))) + return ChunkResult.Done; + return ChunkResult.None; + } + public bool OnChat(string text) { if (_waitingOn == 0) return false; - if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase)) + switch (ClassifyChat(text)) { - _waitingOn = 0; // retry the same item next interval - return false; - } - if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) - { - _chunked++; - _waitingOn = 0; - } - else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) - { - _skip.Add(_waitingOn); - _waitingOn = 0; + case ChunkResult.Busy: + _waitingOn = 0; // retry the same item next interval + break; + case ChunkResult.Done: + _chunked++; + _waitingOn = 0; + break; + case ChunkResult.Refused: + _skip.Add(_waitingOn); + _waitingOn = 0; + break; } return false; } @@ -249,7 +296,7 @@ internal sealed class IltChunkClap : IIltFeature public void Render() { - ImGui.TextColored(IltStyle.ColTeal, "Chunking (Lugian Hammer)"); + SafeImGui.TextColored(IltStyle.ColTeal, $"Chunking ({HammerName})"); bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat; if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a; ImGui.SameLine(); @@ -257,11 +304,24 @@ internal sealed class IltChunkClap : IIltFeature if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb; int under = G.ChunkAetheriaUnderLevel; ImGui.SetNextItemWidth(100); - if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = Math.Clamp(under, 1, 6); + if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level."); + bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist; + ImGui.TextUnformatted("Never chunk aetheria with:"); + ImGui.SameLine(); + if (ImGui.Checkbox("C##keepc", ref kc)) G.KeepAetheriaWithCrit = kc; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit rating (GearCrit)."); + ImGui.SameLine(); + if (ImGui.Checkbox("CD##keepcd", ref kcd)) G.KeepAetheriaWithCritDamage = kcd; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage rating (GearCritDamage)."); + ImGui.SameLine(); + if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist)."); if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items", "Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.", ChunkNow, "Chunk"); - ImGui.TextDisabled("Status: " + _chunkStatus); + SafeImGui.TextDisabled("Status: " + _chunkStatus); ImGui.Separator(); ImGui.TextColored(IltStyle.ColTeal, "Clap (/clap all)"); @@ -277,6 +337,6 @@ internal sealed class IltChunkClap : IIltFeature if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins); if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true)); ImGui.SameLine(); - ImGui.TextDisabled(_clapStatus); + SafeImGui.TextDisabled(_clapStatus); } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs index ca207b2..23a2345 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs @@ -18,6 +18,7 @@ using System.Linq; using ImGuiNET; using RynthCore.Loot; using RynthCore.Install; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -238,7 +239,7 @@ internal sealed class IltEquipSuits : IIltFeature var profiles = _profiles; if (profiles.Length == 0) { - ImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders)."); + SafeImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders)."); } else { @@ -258,7 +259,7 @@ internal sealed class IltEquipSuits : IIltFeature if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player")); } } - ImGui.TextDisabled("Status: " + _status); - foreach (string l in _preview) ImGui.BulletText(l); + SafeImGui.TextDisabled("Status: " + _status); + foreach (string l in _preview) SafeImGui.BulletText(l); } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs new file mode 100644 index 0000000..a0035c7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs @@ -0,0 +1,273 @@ +// IltFeatureCatalog.cs — Every Infinite Leaftide feature RynthILT supports, in one list. +// +// Each entry says what the feature is, where it lives in the Rynth tools, and how its state is +// known. Detection is client-side only: the server type comes from the login (the world name, +// RynthCore's "ilt" verdict), and the ILT profile below is the known set of what Infinite +// Leaftide runs, taken from ACECustom (its ServerConfig defaults and deploy/PROD_DEPLOY_PLAN.md, +// e.g. pet bond and potency on in prod, pet strain off since launch). The server is never asked +// for a list; what it returns on its own (probe replies, chat) refines the profile: +// * Profile (IltKnown.Profile): on in ILT (T11, split arrows, pet breeding, ...). On with the +// ILT world; a server refusal seen in chat turns it off. +// * Profile off (IltKnown.ProfileOff): an ACECustom option ILT runs with off (pet strain, +// defense scaling, the pyreal refill). Off with the ILT world; a chat line only the feature +// sends (e.g. a pyreal refill) turns it on. +// * Checked (IltKnown.Checked): the login probe answers it (/bank, /aug, /xp, /pets, ...). +// "checking" until the reply arrives, then on or off. +// * No server bit at all (the Temple guardians, Paragon gear): content, on with the ILT world. +// Off an ILT world nothing is claimed: every state is unknown. +// The list feeds the ILT settings window ("/ilt settings", IltSettingsView/) and "/ra hub features". +// Server facts copied from ACECustom: Fellowship.MaxFellows = 29 (Source/ACE.Server/Entity/ +// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on. +/// Stable id. +/// Display name. +/// Character, Items, Fellowship or Activities (the list's sections). +/// Where the Rynth tools handle it. +/// One line on what the server does. +/// The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world). +/// How the state is known while the bit hasn't been set (see ). +internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit, + IltKnown Known = IltKnown.Profile); + +/// How a feature's state is known on an ILT world before (or without) a server answer. +internal enum IltKnown +{ + /// On in ILT: on with the ILT world unless chat shows it off. + Profile, + /// The login probe answers it: "checking" until the reply arrives. + Checked, + /// Off in ILT: off with the ILT world unless chat shows it on. + ProfileOff, +} + +internal static class IltFeatureCatalog +{ + public const string GroupCharacter = "Character"; + public const string GroupItems = "Items"; + public const string GroupPets = "Pets"; + public const string GroupFellowship = "Fellowship"; + public const string GroupCombat = "Combat"; + public const string GroupActivities = "Activities"; + + /// The section order of the list (ACECustom's "/ilt features" uses the same). + public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities }; + + /// ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9. + public const int IltFellowshipMax = 29; + + /// A retail fellowship's member limit. + public const int RetailFellowshipMax = 9; + + /// Every Leaftide feature RynthILT supports, in display order. + public static readonly IltFeatureInfo[] All = + { + // Character progression and money. + new("bank", "Banking", GroupCharacter, "Mini Remote > Banking tab; Remote tab bank line", + "Bank pyreals, luminance, keys and coins; deposit, withdraw and transfer (/bank).", IltFeature.Bank, IltKnown.Checked), + new("bank_notes", "Trade note banking", GroupCharacter, "Mini Remote > Banking tab (trade notes)", + "Deposit trade notes as pyreals, withdraw any note from I to MMD, transfer note value (/bank d n).", "bank_notes"), + new("guardian", "Guardian (infinite base attributes)", GroupCharacter, "Guardian panel (/rc guardian)", + "Temple of Enlightenment guardians raise base attributes past the retail cap.", null), + new("attributes", "Infinite raised attributes", GroupCharacter, "Skills > Progression > Attributes", + "Spend unassigned XP on attributes past the retail max (/xp, /attr).", IltFeature.Xp, IltKnown.Checked), + new("augmentations", "Infinite augmentations", GroupCharacter, "Skills > Progression > Augmentations", + "Luminance augmentations far past retail: Creature 6000, Item / Life / War / Void 4000 (/aug).", IltFeature.Aug, IltKnown.Checked), + new("aug_charms", "Augmentation counter charms", GroupCharacter, "Skills > Progression > Augmentations", + "Triune Weave and the school charms add to your aug counts past the purchase cap (/aug).", "aug_charms"), + new("enlightenment", "Enlightenment", GroupCharacter, "Skills > Progression > Enlightenment", + "Enlightenment tiers past retail, with medallions, sigils and crests (/enl).", IltFeature.Enl, IltKnown.Checked), + new("ilt_skills", "Spend XP and train skills in one go", GroupCharacter, "Chat: /ilt xp, /ilt train", + "Spends all unspent XP into trained skills, or trains every affordable skill, in priority order.", "ilt_skills"), + new("leaderboards", "Leaderboards", GroupCharacter, "Chat: /top", + "Server leaderboards: quest bonus, level, enlightenment, augs, bank, pets and more (/top).", "leaderboards"), + + // Items, loot and crafting. + new("paragon_armor", "Paragon armor", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon armor progression; the 50th Armor Paragon gates enlightenment past 300.", null), + new("paragon_weapons", "Paragon weapons", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon weapon progression (Paragon Missile, Caster and Melee sets).", null), + new("paragon_jewelry", "Paragon jewelry", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon jewelry progression; the 50th Paragon gates enlightenment past 150.", null), + new("t11", "T11 items", GroupItems, "Item info and loot rules (RynthAi, RynthCore Loot Editor)", + "Tier 11 to 25 gear (Zone Control tiers): tiers, gear grades, property slots and modifiers.", "t11"), + new("t11_scaling", "T11+ weapon scaling", GroupItems, "Item info (RynthAi)", + "T11+ weapons scale with your augs and have aug wield floors; from T16, charm counts too.", "t11_scaling"), + new("t11_craft_gate", "T11+ crafting rules (crafting uniqueness)", GroupItems, "Mini Remote > Gear tab", + "On T11+ items the server refuses an imbue or tink that would replace a better value, and limits materials per item type.", + "t11_craft_gate"), + new("split_arrows", "Split arrows", GroupItems, "Mini Remote > Gear > Split arrows", + "Missile weapons carry split arrows, added with White Quartz salvage.", "split_arrows"), + new("charms", "Charms", GroupItems, "Mini Remote > Charms tab", + "Registry charms and the Guardian Hand, with their toggles; each charm is listed in the Charms section.", "charms"), + new("clap", "Chunk clap (auto craft)", GroupItems, "Mini Remote > Gear tab", + "Turns aetheria, chunks and trinkets into banked enlightened coins (/clap all).", IltFeature.Clap, IltKnown.Checked), + + // Pets. + new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked), + new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked), + new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab", + "Siphon lenses capture a creature's look into a pet essence (lens drops from kills are a separate server switch).", "monster_capture"), + new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding", + "Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"), + new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding", + "Bred pets start small and weak and grow up with kills.", "pet_maturity"), + new("pet_bond", "Pet bond", GroupPets, "Mini Remote > Pets tab", + "Pets gain bond XP from kills, which scales their stats (/top bonds). On in ILT (breeding needs bond 100).", IltFeature.PetBond), + new("pet_potency", "Pet potency", GroupPets, "Mini Remote > Pets tab", + "Savage Echo residue raises a pet's potency (/echo-notify). On in ILT.", IltFeature.PetPotency), + new("pet_strain", "Pet strain", GroupPets, "Mini Remote > Pets tab", + "High pet potency lowers the owner's damage rating. Off in ILT since launch.", "pet_strain", IltKnown.ProfileOff), + new("pet_refill", "Summon essence refill", GroupPets, "Mini Remote > Pets tab", + "Pays pyreals to refill an empty essence when you summon (needs its charm). Off by default; a refill message in chat shows it on.", IltFeature.PetRefill, IltKnown.ProfileOff), + new("universal_mastery", "Universal summoning mastery", GroupPets, "Mini Remote > Pets tab", + "Use pet essences of any summoning mastery (needs its charm).", IltFeature.UniversalMastery), + new("pet_naming", "Pet names", GroupPets, "Chat: /pet-name", + "Ask for a name for your pet; staff approve it (/pet-name).", "pet_naming"), + + // Fellowship. + new("fellowship_large", "Large fellowships (up to 29)", GroupFellowship, "The game's fellowship panel", + "Fellowships hold up to 29 members instead of retail's 9.", "fellowship_size"), + new("fship", "Fellowship commands", GroupFellowship, "ILT fellowship window (/ilt fellow)", + "Create, invite, invite your landblock, list nearby, leave and disband from chat (/fship).", "fship"), + new("zone_share", "Zone Share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", + "XP and luminance shared with everyone in a Zone Share area, capped at a fellowship's size.", "zone_share"), + new("fellowship_luminance", "Fellowship luminance share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", + "Luminance splits among fellows the way XP does.", "fellowship_luminance"), + new("fellowship_blackjack", "Fellowship Blackjack", GroupFellowship, "Mini Remote > Games tab", + "Blackjack played as a fellowship (/fblackjack).", IltFeature.FBlackjack, IltKnown.Checked), + + // Combat. + new("smart_ring", "Smart ring spells", GroupCombat, "Chat: /ilt smartring", + "Ring spells hit everything in their radius, with double and triple procs (/ilt smartring on|off).", "smart_ring"), + new("dmgformat", "Damage number format", GroupCombat, "Chat: /ilt dmgformat", + "Damage shown plain, with commas, or short (K/M/B) (/ilt dmgformat).", "dmgformat"), + new("overkill", "Overkill on kill messages", GroupCombat, "Chat: /ilt showoverkill", + "Kill and death messages show the overkill amount (/ilt showoverkill).", "overkill"), + new("missile_power", "Missile power bar damage", GroupCombat, "Combat", + "The missile accuracy bar scales damage from 1x to 2.5x.", "missile_power"), + new("t11_hit_gate", "T11+ hit gate", GroupCombat, "Combat", + "Attacks on v11+ monsters miss unless your aug counts meet that tier's requirement.", "t11_hit_gate"), + new("v11_endgame", "v11+ endgame scaling", GroupCombat, "Combat", + "Percent-of-max-HP damage, compressed vulnerabilities and tougher v11+ monsters.", "v11_endgame"), + new("defense_scaling", "Defense scaling", GroupCombat, "Combat", + "Curbs extreme evasion at very high defense skill. Off by default in ACECustom.", "defense_scaling", IltKnown.ProfileOff), + + // Activities. + new("quests", "Quest tracker", GroupActivities, "Mini Remote > Quests tab", + "Your quest timers from the server (/myquests).", IltFeature.Quests, IltKnown.Checked), + new("quest_bonus", "Quest bonus", GroupActivities, "Mini Remote > Quests tab (quest bonus)", + "Each quest completed adds to your XP bonus; the list (/qb).", IltFeature.Qb, IltKnown.Checked), + new("bounties", "Bounties", GroupActivities, "Bounties window (/rc bounties)", "ACECustom bounties and your progress.", "bounties"), + new("rifts", "Greater Rifts", GroupActivities, "Chat: /rift", "Private, timed dungeon runs that scale by tier (/rift).", "rifts"), + new("room_assign", "Room Assign dungeons", GroupActivities, "Portals and recalls", + "One-player rooms with their own spawns.", "room_assign"), + new("portal_requirements", "Aug / ENL / QB portals", GroupActivities, "Portals", + "Portals that need augmentations, an enlightenment level or a quest bonus.", "portal_requirements"), + new("powerball", "Powerball", GroupActivities, "Mini Remote > Games tab", "The Powerball lottery (/pb).", IltFeature.Powerball, IltKnown.Checked), + new("blackjack", "Blackjack", GroupActivities, "Mini Remote > Games tab", "Blackjack against the house (/blackjack).", IltFeature.Blackjack, IltKnown.Checked), + new("unstuck", "Unstuck", GroupActivities, "Chat: /unstuck", "Gets you out of a stuck portal or spot (/unstuck).", "unstuck"), + }; + + /// The entry with , or null. + public static IltFeatureInfo? Find(string key) + { + foreach (IltFeatureInfo f in All) + if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f; + return null; + } + + /// + /// A feature's state on an ILT world: what the server returned (a probe reply or a refusal in + /// chat) when it did; else the ILT profile: On for content and , + /// Off for , Unknown ("checking") for probed features. + /// Off ILT nothing is claimed: Unknown. + /// + public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func bit) + { + if (!iltWorld) return IltTri.Unknown; + if (f.ServerBit == null) return IltTri.On; + IltTri reported = bit(f.ServerBit); + if (reported != IltTri.Unknown) return reported; + return f.Known switch + { + IltKnown.Profile => IltTri.On, + IltKnown.ProfileOff => IltTri.Off, + _ => IltTri.Unknown, + }; + } + + /// + /// A charm's state: charms are part of the ILT profile, so on with the ILT world unless the + /// server refused one in chat (e.g. "Auto-Rebuff Charm is currently disabled globally"). + /// + public static IltTri CharmStateOf(bool iltWorld, IltTri reported) + => !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On; + + /// Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier". + public const string CharmKeyPrefix = "charm:"; + + /// + /// Display text for a key the settings view lists: a catalog feature (its label, group and + /// description with where it lives and how its state is known), a charm ("charm:..." under + /// Charms, named from the charm registry), or any other server bit as itself under "Other". + /// + public static (string Label, string Group, string Tooltip) Describe(string key) + { + IltFeatureInfo? f = Find(key); + if (f != null) return (f.Label, f.Group, f.Description + "\nWhere: " + f.Where + "\n" + HowKnown(f)); + if (key.StartsWith(CharmKeyPrefix, StringComparison.OrdinalIgnoreCase)) + { + const string charmNote = "Part of ILT: on unless the server refuses it in chat."; + foreach (IltCharmDef def in IltInventory.Charms) + if (IltFeature.Charm(def.Name).Equals(key, StringComparison.OrdinalIgnoreCase)) + return (def.Name, GroupCharms, (def.Effect.Length > 0 ? def.Effect + "\n" : string.Empty) + + "Where: Mini Remote > Charms tab\n" + charmNote); + return (key.Substring(CharmKeyPrefix.Length), GroupCharms, charmNote); + } + return (key, GroupOther, "A server switch RynthILT reads from chat."); + } + + /// One line on where a feature's state comes from (tooltips). + private static string HowKnown(IltFeatureInfo f) => f.ServerBit == null + ? "Built into ILT: on with the world." + : f.Known switch + { + IltKnown.Checked => "Checked at login: the server's reply decides.", + IltKnown.ProfileOff => "Off in ILT: on only if the server shows it in chat.", + _ => "Part of ILT: on unless the server refuses it in chat.", + }; + + /// The settings view's extra sections after . + public const string GroupCharms = "Charms"; + public const string GroupOther = "Other"; + + /// Short state text for the list and chat: "on", "off" or "checking". + public static string StateText(IltTri state) => state switch + { + IltTri.On => "on", + IltTri.Off => "off", + _ => "checking", + }; + + /// 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 chat listing for "/ra hub features": one line per feature, ASCII only. + public static List BuildChatLines(bool iltWorld, Func bit) + { + var lines = new List(All.Length + Groups.Length); + foreach (string g in Groups) + { + var parts = new List(); + foreach (IltFeatureInfo f in All) + if (f.Group == g) parts.Add($"{f.Label} [{StateText(StateOf(f, iltWorld, bit))}]"); + lines.Add($"{g}: {string.Join(", ", parts)}"); + } + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs index 44e5f5b..0a91a26 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Numerics; using System.Text.RegularExpressions; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -179,7 +180,7 @@ internal sealed class IltGames : IIltFeature ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u); bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet); ImGui.SameLine(); - ImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid"); + SafeImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid"); ImGui.BeginDisabled(!ok || _handActive); if (ImGui.Button($"Deal...##{id}")) @@ -192,7 +193,7 @@ internal sealed class IltGames : IIltFeature ImGui.EndDisabled(); if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id); - if (_lastResult.Length > 0 && _fellowshipHand == fellowship) ImGui.TextWrapped(_lastResult); + if (_lastResult.Length > 0 && _fellowshipHand == fellowship) SafeImGui.TextWrapped(_lastResult); } private void RenderHandButtons(string id) @@ -221,7 +222,7 @@ internal sealed class IltGames : IIltFeature if (!_ctx.Options.IsOn(IltFeature.Powerball)) { ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh)."); - if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus); + if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus); return; } int qty = S.PowerballQuantity; @@ -234,7 +235,7 @@ internal sealed class IltGames : IIltFeature _ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}", () => Send($"/pb buy {q}"), "Buy"); } - if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus); + if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus); } /// Small HUD with the current hand; called every frame by the Hub UI. @@ -245,7 +246,7 @@ internal sealed class IltGames : IIltFeature bool open = true; if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse)) { - ImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack"); + SafeImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack"); RenderHandButtons("hud"); } ImGui.End(); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs index c995a13..a986d5a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs @@ -4,7 +4,8 @@ // The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits) // that this tab just lays out, plus RynthAi's VTank .usd importer (it edits RynthAi's own rules, // so it stayed in RynthAi and is drawn here through RynthAi.Hub RenderSection). The charm strip (registry charms and the Guardian -// Hand, with their toggles) is the Charms tab now (IltCharms). +// Hand, with their toggles) is the Charms tab now (IltCharms). The Rings inscription chain +// (IltRingChainRunner) is SilentKelpie's RynthAi Crafting > Rings, moved here 2026-10-15. using ImGuiNET; namespace RynthCore.Plugin.RynthILT.Hub; @@ -15,6 +16,7 @@ internal sealed class IltGear : IIltFeature public IltChunkClap ChunkClap { get; } public IltSplitArrows Split { get; } public IltEquipSuits Suits { get; } + public IltRingChainRunner Rings { get; } private readonly IltHubContext _ctx; @@ -24,6 +26,9 @@ internal sealed class IltGear : IIltFeature ChunkClap = new IltChunkClap(ctx); Split = new IltSplitArrows(ctx); Suits = new IltEquipSuits(ctx); + // The two pack jobs that answer craft dialogs never run together. + Rings = new IltRingChainRunner(ctx, () => Split.Running); + Split.Blocked = () => Rings.Running; _ctx = ctx; } @@ -35,6 +40,7 @@ internal sealed class IltGear : IIltFeature ChunkClap.Tick(nowMs); Split.Tick(nowMs); Suits.Tick(nowMs); + Rings.Tick(nowMs); } public bool OnChat(string text) @@ -43,6 +49,7 @@ internal sealed class IltGear : IIltFeature eat |= ChunkClap.OnChat(text); eat |= Split.OnChat(text); eat |= Suits.OnChat(text); + eat |= Rings.OnChat(text); return eat; } @@ -52,6 +59,7 @@ internal sealed class IltGear : IIltFeature ChunkClap.OnLogout(); Split.OnLogout(); Suits.OnLogout(); + Rings.OnLogout(); } // ── UI (render thread) ────────────────────────────────────────────────── @@ -62,6 +70,7 @@ internal sealed class IltGear : IIltFeature if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render(); if (ImGui.CollapsingHeader("Split arrows")) Split.Render(); if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render(); + if (ImGui.CollapsingHeader("Rings (inscription chain)")) Rings.Render(); if (ImGui.CollapsingHeader("VirindiTank import") && !_ctx.Ai.RenderSection(RynthCore.Plugin.Shared.RynthAiHub.SectionVTankImport)) ImGui.TextDisabled("The VirindiTank .usd import fills RynthAi's rules: it comes with RynthAi, which isn't loaded."); ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab."); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs index 15b656d..eb3975c 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs @@ -465,16 +465,16 @@ internal sealed class IltGuardian : IIltFeature ImGui.TextDisabled("Heard:"); ImGui.SameLine(); ImGui.PushTextWrapPos(0f); - ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line)); + SafeImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line)); ImGui.PopTextWrapPos(); } string answer = _lastAnswer, npc = _lastNpc; if (answer.Length > 0) { - ImGui.TextColored(IltStyle.ColTeal, answer); + SafeImGui.TextColored(IltStyle.ColTeal, answer); ImGui.SameLine(); - ImGui.TextDisabled("-> " + npc); + SafeImGui.TextDisabled("-> " + npc); if (HandInRunning) { if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn()); @@ -485,7 +485,7 @@ internal sealed class IltGuardian : IIltFeature } } else ImGui.TextDisabled("No guardian answer yet."); - ImGui.TextDisabled("Hand-in: " + _handInStatus); + SafeImGui.TextDisabled("Hand-in: " + _handInStatus); ImGui.Spacing(); ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54)); @@ -506,7 +506,7 @@ internal sealed class IltGuardian : IIltFeature if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute)."); ImGui.SameLine(); DateTime synced = Attributes.SyncedUtc; - ImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}"); + SafeImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}"); ImGui.SameLine(); if (ImGui.SmallButton("Reset counts##grdreset")) _ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)", @@ -531,9 +531,9 @@ internal sealed class IltGuardian : IIltFeature var col = r.Ready ? IltStyle.ColGreen : r.Status == "Unknown" ? IltStyle.ColTextMute : IltStyle.ColAmber; - ImGui.TextColored(col, r.Status); + SafeImGui.TextColored(col, r.Status); if (ImGui.IsItemHovered()) - ImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates)."); + SafeImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates)."); ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta); } ImGui.EndTable(); @@ -555,8 +555,8 @@ internal sealed class IltGuardian : IIltFeature if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return; ImGui.TextColored(IltStyle.ColTextMute, "Guardian:"); ImGui.SameLine(); - ImGui.TextColored(IltStyle.ColTeal, answer); - if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}"); + SafeImGui.TextColored(IltStyle.ColTeal, answer); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}"); ImGui.SameLine(); if (HandInRunning) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs index 92eb4d0..9ded4c5 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs @@ -35,12 +35,26 @@ internal sealed class IltHubController 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 + // "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. + private const long DataRebuildMs = 2000; + private const long DataWatchMs = 6000; + /// How often the other characters' saved balances are re-read for the bank export. + private const long SiblingReadMs = 15_000; + private long _charmsReadAt, _bankReadAt; // set by readers (any thread, Interlocked) + private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt; + private volatile string _charmsJson = string.Empty; + private volatile string _bankJson = string.Empty; + private List _siblings = new(); + public IltBanking Banking { get; } public IltSessionRates Rates { get; } /// The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps. public IltQuestBonus QuestBonus { get; } /// The /pets and /shinies logs (the Pets tab's section). 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; } public IltProgression Progression { get; } public IltGear Gear { get; } public IltGames Games { get; } @@ -69,6 +83,7 @@ internal sealed class IltHubController Banking = new IltBanking(_ctx); PetLogs = new IltPetLogs(_ctx); + Breeding = new IltPetBreeding(_ctx); Rates = new IltSessionRates(_ctx); QuestBonus = new IltQuestBonus(_ctx); Progression = new IltProgression(_ctx); @@ -77,7 +92,7 @@ internal sealed class IltHubController Charms = new IltCharmTracker(_ctx); CharmsTab = new IltCharms(_ctx, Charms); Guardian = new IltGuardian(_ctx, QuestBonus); - _features.AddRange(new IIltFeature[] { Banking, PetLogs, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian }); + _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian }); Banking.BalanceChanged += Rates.OnBankBalanceChanged; Rates.MovingMoney = () => Banking.MovingMoney; @@ -86,6 +101,81 @@ internal sealed class IltHubController _ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); } + /// + /// The charms JSON ("RynthILT.Data" GetCharmsJson). Reading it marks the charms as watched, so + /// the pump keeps the snapshot fresh while a reader is showing it; "" until the first rebuild + /// after that. Any thread. + /// + public string CharmsJson + { + get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; } + } + + /// The bank JSON ("RynthILT.Data" GetBankJson), as . + public string BankJson + { + get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; } + } + + /// A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread. + public void RequestCharmToggle(uint objectId) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + if (!CharmsTab.ToggleFromReader(objectId)) + RynthLog.Trace(LogCat.IltGear, $"reader toggle refused: 0x{objectId:X8} isn't a carried charm"); + _charmsBuiltAt = 0; // show the new state on the next tick + }); + + /// + /// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson). + /// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread. + /// + public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty; + + /// A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread. + public void RequestBreedingVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Breeding.RunVerb(line); + }); + + /// A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread. + public void RequestBankVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Banking.RunVerb(line); + _bankBuiltAt = 0; + }); + + /// Pump: rebuilds the charms / bank snapshots a reader is watching. + private void RebuildReaderData(long now) + { + if (now - System.Threading.Interlocked.Read(ref _charmsReadAt) < DataWatchMs && now - _charmsBuiltAt >= DataRebuildMs) + { + _charmsBuiltAt = now; + _charmsJson = CharmsTab.BuildReaderJson(); + } + + bool bankWatched = now - System.Threading.Interlocked.Read(ref _bankReadAt) < DataWatchMs; + Banking.ReaderWatching = bankWatched; + if (!bankWatched || now - _bankBuiltAt < DataRebuildMs) return; + _bankBuiltAt = now; + if (_siblingsReadAt == 0 || now - _siblingsReadAt >= SiblingReadMs) + { + _siblingsReadAt = now; + _siblings = IltBankExport.ReadSiblings(_ctx.Store.CharFolder); + } + IltServerOptions o = _ctx.Options; + string me = _ctx.CharName.Length > 0 ? _ctx.CharName : System.IO.Path.GetFileName(_ctx.Store.CharFolder.TrimEnd('\\', '/')); + var rows = new List(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) }; + rows.AddRange(_siblings); + int enabled = o.IsOn(IltFeature.Bank) ? 1 : o.IsOff(IltFeature.Bank) ? 0 : -1; + _bankJson = IltBankExport.Build(o.IsIltLikeWorld, enabled, o.WorldName, me, rows, Banking.LatestResult, Banking.Transactions); + } + public IltHubState State => _ctx.State; public IltServerOptions Options => _ctx.Options; internal IltHubContext Context => _ctx; @@ -94,8 +184,8 @@ internal sealed class IltHubController public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn; /// - /// Whether a section can be shown now. Character always can (it explains why the ILT tabs are - /// idle and holds the Force-ILT override); the rest need server features. + /// Whether a section can be shown now: the ILT tabs and the Guardian need server features. + /// Character (moved to RynthOracle) always answers true so its redirect is never refused. /// public bool SectionAvailable(IltSection section) => section switch { @@ -107,7 +197,7 @@ internal sealed class IltHubController /// /// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT - /// override). The Character tab then always shows; the others follow . + /// override from RynthCore Options > Diagnostics). The tabs then follow . /// public bool OffersTabs => _ctx.Options.IsIltLikeWorld; @@ -117,6 +207,15 @@ 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: 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"). + /// + public void RenderRatesSection() => _ui.RenderRatesSection(); + + /// Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus"). + public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection(); + /// Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian"). public void RenderGuardianPanel() => _ui.RenderGuardianPanel(); @@ -180,6 +279,10 @@ internal sealed class IltHubController _ctx.Options.Tick(); PollQuestOutcome(); + // The charms / bank snapshots other plugins read (RynthILT.Data), only while watched. + 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; @@ -237,7 +340,7 @@ internal sealed class IltHubController private static LogCat CategoryOf(IIltFeature f) => f switch { IltBanking => LogCat.IltBanking, - IltPetLogs => LogCat.IltPets, + IltPetLogs or IltPetBreeding => LogCat.IltPets, IltSessionRates => LogCat.IltRates, IltQuestBonus => LogCat.IltQuests, IltProgression => LogCat.IltProgression, @@ -353,24 +456,31 @@ internal sealed class IltHubController { // Quests and Pets are RynthAi's tabs: not ours to open. if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false; - _ctx.Chat("[Mini Remote] Usage: /ra hub open character|quests|pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle]"); + _ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)"); break; } OpenSection(section, args.Length > 2 ? args[2] : "toggle"); break; case "tab": // The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs. - if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.IsTab(tab)) + if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.MovedCommand(tab) is string moved) + OpenMoved(tab, moved); + else if (args.Length > 1 && IltSections.TryParse(args[1], out tab) && IltSections.IsTab(tab)) _ctx.Ai.MiniRemoteTab(IltSections.TabId(tab), "select"); else return false; // the Remote tab or a RynthAi tab: RynthAi's break; case "refresh": _ctx.Options.Refresh(manual: true); break; case "bank": Banking.RequestRefresh(quiet: false); break; + // "/ilt qb": reads the /qb list again (the Quests tab's quest bonus section). + case "qb": _ctx.Chat("[RynthILT] " + QuestBonus.RefreshQb()); break; case "status": PrintStatus(); break; + case "features": PrintFeatures(); break; case "force": _ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase); - _ctx.Chat($"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server."); + _ctx.Chat(IltServerOptions.EngineDecides + ? $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")} for this character (RynthCore counts it unless /rc server ilt off). Use /ra hub refresh to re-check the server." + : $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server."); break; case "servers": HandleServers(rest); break; case "profile": HandleProfile(args.Skip(1).ToArray()); break; @@ -383,11 +493,11 @@ internal sealed class IltHubController ClearPending(); break; default: - _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|servers [list]|clap|confirm|cancel"); - _ctx.Chat("[Mini Remote] /ra hub open character|quests|pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs)"); + _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 [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); _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|check |window [show|hide]|favhud [show|hide]] /ra pets [show|hide]"); + _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)"); _ctx.Chat("[Mini Remote] /ra guardian [window|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)"); _ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)"); _ctx.Chat("[Mini Remote] The ILT verbs also work as /ilt hub ..., /ilt guardian ... (RynthILT)."); @@ -396,6 +506,17 @@ internal sealed class IltHubController return true; } + /// "/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each. + private void PrintFeatures() + { + IltServerOptions o = _ctx.Options; + string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; + _ctx.Chat($"[Mini Remote] Leaftide features on {world} ({(o.IsIltLikeWorld ? "ILT world" : "not an ILT world")}, " + + $"fellowships up to {IltFeatureCatalog.FellowshipMax(o.IsIltLikeWorld)}):"); + foreach (string line in IltFeatureCatalog.BuildChatLines(o.IsIltLikeWorld, o.Get)) + _ctx.Chat("[Mini Remote] " + line); + } + /// "/ra hub servers [list | <names, comma separated> | default]": which world names count as Infinite Leaftide. private void HandleServers(string rest) { @@ -448,6 +569,12 @@ internal sealed class IltHubController /// private void OpenSection(IltSection section, string mode) { + if (IltSections.MovedCommand(section) is string moved) + { + // Character left the Mini Remote: open its new home instead. + if (!mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) OpenMoved(section, moved); + return; + } if (!IltSections.IsTab(section)) { OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode); @@ -459,6 +586,19 @@ internal sealed class IltHubController _ctx.Chat("[Mini Remote] " + reply); } + /// + /// Opens the new home of a section that moved out of the Mini Remote (RynthOracle's Character + /// tab) by running its chat command, or says where it is when the command can't run (an older + /// RynthCore, or RynthOracle not loaded). Pump thread. + /// + public void OpenMoved(IltSection section, string command) + { + if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(command)) + return; + _ctx.Chat($"[Mini Remote] {IltSections.Label(section)} moved to RynthOracle's Character tab ({command}); " + + "the ILT session rates are in the Mini Remote's Session Stats."); + } + /// /// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]") /// through the engine's chat dispatcher. Pump thread. diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs index b68e7fd..b839669 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs @@ -53,7 +53,7 @@ public sealed class IltHubState public sealed class IltServerOptionsSnapshot { public string WorldName = string.Empty; - /// "ilt-features" (structured dump), "probe" (command probing) or "" (never refreshed). + /// "probe" (the login probe) or "" (never refreshed). public string Source = string.Empty; public DateTime LastRefreshUtc = DateTime.MinValue; /// Feature key → -1 unknown, 0 off, 1 on. @@ -77,6 +77,8 @@ public sealed class IltBankState /// Last transfer recipient typed into the transfer form. public string TransferTarget = string.Empty; public int TransferCurrencyIndex; + /// Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD). + public int TransferNoteIndex = 9; /// Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations). public int DepositIndex; @@ -106,6 +108,8 @@ public sealed class IltPetState /// Last captured /pets and /shinies rosters (display only; the Pets tab's logs). public List PetLog = new(); 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. } @@ -199,8 +203,17 @@ public sealed class IltGearState public bool AutoChunkCorrupted; public bool ChunkInCombat; public int ChunkIntervalMs = 2000; - /// Only chunk aetheria whose max level is below this (Coalesced always chunks). + /// + /// Only chunk aetheria whose max level is below this (Coalesced always chunks). Infinite Leaftide + /// aetheria goes up to level , so the cap runs to one past it. + /// public int ChunkAetheriaUnderLevel = 4; + /// Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+). + public bool KeepAetheriaWithCrit = true; + /// Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374). + public bool KeepAetheriaWithCritDamage = true; + /// Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375). + public bool KeepAetheriaWithCritDamageResist = true; // Auto-clap (/clap all) public bool AutoClap; @@ -216,6 +229,14 @@ public sealed class IltGearState // Equipment profiles (.utl suits). (The VTank .usd import path is RynthAi's: the importer stayed there.) public string LastEquipProfile = string.Empty; + + // Rings inscription chain (IltRingChainRunner; SilentKelpie's, moved from RynthAi's Crafting tab) + /// Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only. + public Dictionary RingRuns = new(StringComparer.OrdinalIgnoreCase); + /// Answer the server's craft dialog Yes for the queued combines (engine API v85). + public bool RingAnswerCraftDialog = true; + /// Craft and inscribe in combat mode too (servers with combat-mode crafting). + public bool RingAllowInCombat; } // ── Games ─────────────────────────────────────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs index 04fb5ef..970c033 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs @@ -145,6 +145,16 @@ internal sealed class IltHubStore s.Pet ??= new IltPetState(); s.Pet.PetLog ??= new(); s.Pet.ShinyLog ??= new(); + s.Pet.Breeding ??= new(); + s.Pet.Breeding.Rules ??= new(); + s.Pet.Breeding.StageNames ??= new(); + s.Pet.Breeding.Log ??= new(); + s.Pet.Breeding.LastDebug ??= new(); + 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; + if (s.Pet.Breeding.Log.Count > IltBreedingRules.MaxEvents) + s.Pet.Breeding.Log.RemoveRange(0, s.Pet.Breeding.Log.Count - IltBreedingRules.MaxEvents); s.Character ??= new IltCharacterState(); s.Character.ItemConversions ??= new(); s.Character.AugTargets = new Dictionary(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase); @@ -157,6 +167,7 @@ internal sealed class IltHubStore s.Gear ??= new IltGearState(); s.Gear.DispelInclusions ??= new(); s.Gear.DispelExclusions ??= new(); + s.Gear.RingRuns = new Dictionary(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase); s.Games ??= new IltGamesState(); s.Guardian ??= new IltGuardianState(); s.Guardian.TurnInCounts = new Dictionary(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase); @@ -286,6 +297,8 @@ internal sealed class IltHubStore { incoming.PetLog = current.PetLog; incoming.ShinyLog = current.ShinyLog; + // The breeding tracker holds this object; it is the character's own (not a profile setting). + incoming.Breeding = current.Breeding; return incoming; } @@ -301,6 +314,7 @@ internal sealed class IltHubStore s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh }; s.Pet.PetLog = new(); s.Pet.ShinyLog = new(); + s.Pet.Breeding = new(); s.UbSidecarsImported = false; s.WindowVisible = false; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs index c5bb740..9cca44f 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs @@ -4,12 +4,18 @@ // Infinite Leaftide items) that read the Hub's state. // // The ILT sections are tabs of RynthAi's Mini Remote (its MiniRemoteHud draws the tab bar and -// calls RenderTab through RynthILT.Hub): Character (world status, Force-ILT, server names, -// profiles, session rates), Banking, Gear, Charms and Games. A tab is offered only while the -// server reports its feature on. RenderSection draws the ILT pieces inside RynthAi's own -// surfaces (the Remote tab, the Quests and Pets tabs, the Mini Remote menu). The Guardian is a -// RynthCore ILT panel (the bar's ILT button, next to Bounties), drawn through -// RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation +// calls RenderTab through RynthILT.Hub): Banking, Gear, Charms and Games. A tab is offered only +// while the server reports its feature on. The Character tab left the Mini Remote on 2026-10-13: +// - the session rates are RynthCore's Mini Remote "Session Stats" section (RenderRatesSection, +// surface "section:ilt-rates"), below RynthAi's one session; +// - the character overview and session are RynthOracle's Character tab ("/ro character"); +// - the "Treat this world as ILT" override and the ILT world names are RynthCore's +// Options > Diagnostics server selection only ("/ra hub force" and "/ra hub servers" remain). +// The /qb list (RynthAi's Quests tab before it moved to RynthOracle) is RynthILT's own "Quests" +// section on the rail (RenderQuestBonusSection, surface "section:ilt-questbonus"). +// RenderSection draws the ILT pieces inside RynthAi's own surfaces (the Remote tab, the Pets tab, +// the Mini Remote menu). The Guardian is a RynthCore ILT panel (the bar's ILT button, next to +// Bounties), drawn through RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation // modal. Augmentations / Enlightenment / XP planning live on the engine Skills panel. All AC // actions go through IltHubContext.Post / Confirm so nothing here touches the game directly. using System; @@ -24,15 +30,16 @@ internal sealed class IltHubUi private const string ConfirmPopupId = "Confirm##iltconfirm"; private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f); + /// Where a server is forced now (the only place: RynthCore's Options window). + private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics)."; + + /// RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+). + private const string DiagnosticsCommand = "/rc diagnostics"; + private readonly IltHubController _hub; private readonly IltHubContext _ctx; private IltConfirmRequest? _confirm; private bool _confirmOpened; - private string _profileName = string.Empty; - private bool _profileShared; - private string[] _profileList = Array.Empty(); - private int _profileIdx; - private string? _serverNamesEdit; // The last tab body drawn (for one shown log event per tab change); -1 = none yet. private int _lastTabLogged = -1; @@ -59,14 +66,50 @@ internal sealed class IltHubUi } switch (section) { - case IltSection.Character: RenderCharacterBody(); break; case IltSection.Banking: _hub.Banking.Render(); break; case IltSection.Gear: _hub.Gear.Render(); break; case IltSection.Charms: _hub.CharmsTab.Render(); break; case IltSection.Games: _hub.Games.Render(); break; + default: + // A saved tab id from before the move: say where the section lives now. + if (IltSections.MovedCommand(section) is string moved) + MovedLink(section, moved); + break; } } + /// + /// The ILT session extras in RynthCore's Mini Remote "Session Stats" section (surface + /// "section:ilt-rates", the Infinite Leaftide group): coins, pyreals and item conversions. + /// XP, luminance and kills are RynthAi's session stats, drawn above it in the same section. + /// + public void RenderRatesSection() + { + if (!_hub.Available) + { + RenderHeader(); + RenderUnavailable(); + return; + } + _hub.Rates.Render(extrasOnly: true); + ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression."); + } + + /// + /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (surface + /// "section:ilt-questbonus"); it was a section of RynthAi's Quests tab, which moved to RynthOracle. + /// + public void RenderQuestBonusSection() + { + if (!_ctx.Options.IsIltLikeWorld) + { + RenderHeader(); + RenderUnavailable(); + return; + } + _hub.QuestBonus.RenderQb(); + } + /// /// One of the ILT pieces RynthAi draws in its own surfaces (RynthIltHub.Section*). False when /// there is nothing to draw (unknown id, or not an ILT world). @@ -92,6 +135,10 @@ internal sealed class IltHubUi if (!o.IsIltLikeWorld) return false; _hub.PetLogs.RenderSection(); return true; + case RynthIltHub.SectionPetBreeding: + if (!o.IsIltLikeWorld) return false; + _hub.Breeding.RenderSection(); + return true; case RynthIltHub.SectionIltStatus: return RenderIltStatus(); case RynthIltHub.SectionServerMenu: @@ -117,111 +164,28 @@ internal sealed class IltHubUi _hub.Guardian.Render(); } - /// Character tab: world / options header, then session rates (or why the ILT tabs are idle). - private void RenderCharacterBody() + /// A button that opens a moved section's new home (posted: the command runs on the pump). + private void MovedLink(IltSection section, string command) { - RenderHeader(); - ImGui.Separator(); - if (!_hub.Available) { RenderUnavailable(); return; } - if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render(); - ImGui.Spacing(); - ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab"); - ImGui.TextDisabled("(right-click the dashboard's Char button > Progression)."); + const string home = "RynthOracle > Character"; + SafeImGui.TextDisabled($"{IltSections.Label(section)} moved to {home}; the ILT session rates are in Session Stats."); + if (ImGui.SmallButton($"Open {home}##moved{(int)section}")) + _ctx.Post(() => _hub.OpenMoved(section, command)); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(command); } + /// The world and when the server's ILT features were last read, with a Refresh. private void RenderHeader() { var o = _ctx.Options; string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; - ImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world); + SafeImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world); ImGui.SameLine(); - ImGui.TextDisabled(o.IsRefreshing ? "checking server options..." + SafeImGui.TextDisabled(o.IsRefreshing ? "checking server options..." : o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet" : $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}"); ImGui.SameLine(); if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true)); - - bool force = _ctx.State.ForceLeaftideFeatures; - if (ImGui.Checkbox("Treat this world as ILT", ref force)) _hub.ForceIltWorld = force; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("World-identity override only: the Mini Remote asks the server which ILT features exist.\nIt never turns a feature on by itself."); - ImGui.SameLine(); - if (ImGui.SmallButton("Servers...")) { _serverNamesEdit = null; ImGui.OpenPopup("##iltservers"); } - ImGui.SameLine(); - if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); } - RenderServersPopup(); - RenderProfilesPopup(); - } - - /// - /// The world names that count as Infinite Leaftide (RynthAi's Settings > Misc "Server Features" - /// list before the move; one list for every character now). - /// - private void RenderServersPopup() - { - if (!ImGui.BeginPopup("##iltservers")) return; - ImGui.TextColored(IltStyle.ColTeal, "Infinite Leaftide world names"); - ImGui.TextDisabled(ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures)); - string text = _serverNamesEdit ?? ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings)); - ImGui.SetNextItemWidth(320); - bool enter = ImGui.InputTextWithHint("##iltservernames", "InfiniteLeaftide, *Leaftide*", ref text, 512, ImGuiInputTextFlags.EnterReturnsTrue); - _serverNamesEdit = text; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Comma-separated world names that turn on the ILT tabs, the Guardian, the Progression\n" + - "planners and the attribute raiser. * is a wildcard (*Leaftide* matches any\n" + - "name containing Leaftide). Case does not matter. Also: /ra hub servers ."); - ImGui.SameLine(); - if (ImGui.SmallButton("Save") || enter) - { - var list = ServerFeatureGate.ParseList(_serverNamesEdit); - if (list.Count > 0) - _ctx.Post(() => { _ctx.Settings.ServerNames = list; _ctx.SaveSettings(); }); - _serverNamesEdit = null; - } - ImGui.SameLine(); - if (ImGui.SmallButton("Default")) - { - _ctx.Post(() => { _ctx.Settings.ServerNames = new(ServerFeatureGate.DefaultServerNames); _ctx.SaveSettings(); }); - _serverNamesEdit = null; - } - ImGui.EndPopup(); - } - - private void RenderProfilesPopup() - { - if (!ImGui.BeginPopup("##iltprofiles")) return; - ImGui.TextColored(IltStyle.ColTeal, "ILT profiles (settings only; no balances)"); - ImGui.SetNextItemWidth(180); - ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u); - ImGui.SameLine(); - ImGui.Checkbox("shared", ref _profileShared); - ImGui.SameLine(); - if (ImGui.SmallButton("Save")) - { - string n = _profileName; bool sh = _profileShared; - _ctx.Post(() => - { - _ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[Mini Remote] Saved profile '{n}'." : "[Mini Remote] Save failed: " + err); - _profileList = _ctx.Store.ListProfiles().ToArray(); - }); - } - var list = _profileList; - if (list.Length > 0) - { - _profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1); - ImGui.SetNextItemWidth(180); - ImGui.Combo("##proflist", ref _profileIdx, list, list.Length); - ImGui.SameLine(); - if (ImGui.SmallButton("Load")) - { - string n = list[_profileIdx]; - _ctx.Confirm("Load ILT profile", $"Replace the current ILT settings with profile '{n}'?", - () => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[Mini Remote] Loaded profile '{n}'." : "[Mini Remote] Load failed: " + err), - "Load"); - } - } - else ImGui.TextDisabled("No saved profiles."); - ImGui.EndPopup(); } private void RenderUnavailable() @@ -229,8 +193,7 @@ internal sealed class IltHubUi var o = _ctx.Options; if (!o.IsIltLikeWorld) { - ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tabs are idle. " - + "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh."); + SafeImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tools are idle. " + ForceHint); } else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue) { @@ -247,9 +210,19 @@ internal sealed class IltHubUi private void RenderRemoteBank() { var b = _ctx.State.Bank; - if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; } + if (b.LastUpdated == DateTime.MinValue) + { + // Nothing read yet this install: offer a quiet /bank (the Banking tab has the full view). + ImGui.TextDisabled("Bank: not loaded yet"); + ImGui.SameLine(); + if (ImGui.SmallButton("Load##mrbank")) _ctx.Post(() => _hub.Banking.RequestRefresh(quiet: true)); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Reads your bank balances (/bank, reply hidden). The Banking tab has the details."); + BankLink(); + return; + } Stat("P:", Compact(b.Pyreals)); Stat("Lum:", Compact(b.Luminance)); + BankLink(); if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return; ImGui.TableNextColumn(); Stat("LK:", Compact(b.LegendaryKeys)); ImGui.TableNextColumn(); Stat("MK:", Compact(b.MythicalKeys)); @@ -260,9 +233,20 @@ internal sealed class IltHubUi ImGui.EndTable(); } + /// The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's). + private void BankLink() + { + if (!_hub.SectionAvailable(IltSection.Banking)) return; + ImGui.SameLine(); + if (ImGui.SmallButton("Bank##mrbanklink")) + _ctx.Ai.MiniRemoteTab(IltSections.TabId(IltSection.Banking), "show"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The Banking tab: deposits, withdrawals and transfers (/ra hub open banking)."); + } + private static void Stat(string label, string value) { - ImGui.TextColored(ColLabel, label); + SafeImGui.TextColored(ColLabel, label); ImGui.SameLine(); ImGui.TextUnformatted(value); } @@ -280,27 +264,28 @@ internal sealed class IltHubUi // ── RynthAi's Mini Remote menu: the Infinite Leaftide section ────────── /// - /// Under the Infinite Leaftide section while no ILT feature is on: why, this character's - /// "Treat this world as ILT" override and a server-features refresh. False when features are on. + /// Under the Infinite Leaftide section while no ILT feature is on: why, where a server is + /// forced (RynthCore Options > Diagnostics only) and a server-features refresh. False when + /// features are on. /// private bool RenderIltStatus() { if (_hub.Available) return false; var o = _ctx.Options; - ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world." + SafeImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world." : o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..." : "No ILT features reported."); - bool force = _hub.ForceIltWorld; - if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) _hub.ForceIltWorld = force; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("World-identity override only: RynthILT asks the server which features exist.\nIt never turns a feature on by itself."); + if (!o.IsIltLikeWorld && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", DiagnosticsCommand)) + _ctx.Post(() => { if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(DiagnosticsCommand); }); + if (!o.IsIltLikeWorld && ImGui.IsItemHovered()) SafeImGui.SetTooltip(ForceHint); if (ImGui.MenuItem("Refresh server features##mrrefresh")) _hub.RequestOptionsRefresh(); return true; } /// /// RynthILT's own Infinite Leaftide entries, for when RynthCore sends no server list (older - /// RynthCore, or its ImGui layer off): the tabs, and the Guardian / Bounties panels. + /// RynthCore, or its ImGui layer off): the tabs, where Character went, and the Guardian / + /// Bounties panels. /// private bool RenderLocalMenu() { @@ -312,6 +297,8 @@ internal sealed class IltHubUi if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, _hub.SectionAvailable(section))) _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); } + if (ImGui.MenuItem("Character##mrlocal", IltSections.OracleCharacterCommand)) + _ctx.Post(() => _hub.OpenMoved(IltSection.Character, IltSections.OracleCharacterCommand)); if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, _hub.SectionAvailable(IltSection.Guardian))) _ctx.Post(() => _hub.OpenEnginePanel("guardian", "Guardian", "show")); if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties")) @@ -340,9 +327,9 @@ internal sealed class IltHubUi bool keepOpen = true; if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize)) { - ImGui.TextColored(IltStyle.ColAmber, _confirm.Title); + SafeImGui.TextColored(IltStyle.ColAmber, _confirm.Title); ImGui.Separator(); - ImGui.TextWrapped(_confirm.Message); + SafeImGui.TextWrapped(_confirm.Message); ImGui.Spacing(); if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0))) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs index 9b1874d..272a233 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs @@ -49,6 +49,12 @@ internal sealed class IltInventory public const uint IntImbuedEffect = 179; public const uint IntCleaving = 292; public const uint IntItemMaxLevel = 319; + /// Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5). + public const int AetheriaMaxLevel = 10; + /// Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist). + public const uint IntGearCrit = 372; + public const uint IntGearCritDamage = 374; + public const uint IntGearCritDamageResist = 375; public const uint IntSummoningMastery = 362; public const uint IntEnlightenment = 390; public const uint IntSplitArrowCount = 9031; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs index f0a7c00..4d37e4b 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs @@ -14,8 +14,11 @@ internal static class IltParse { private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant; - /// "/aug" level line: "Creature: 1,234". - public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", Opt); + /// + /// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2". + /// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys. + /// + public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*([\d,]+)", Opt); /// "/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener". public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs new file mode 100644 index 0000000..70f9147 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs @@ -0,0 +1,790 @@ +// IltPetBreeding.cs - The pet breeding tracker: the Breeding sub-tab of RynthAi's Mini Remote Pets tab, +// drawn here (RynthILT.Hub section "pets-breeding"; RynthAi only hosts it), and the same data as JSON +// for other plugins ("RynthILT.Data" v2 GetPetBreedingJson / PetBreedingCommand). +// Originally SilentKelpie's (2026-10-15, his RynthILT 0.2.7); ported into RynthILT 0.3.1 without his +// RynthOracle Pet Breeding tab: breeding is Leaftide's, so only this plugin draws it. +// +// What it does, on Infinite Leaftide only: +// * reads every carried combat essence (appraisal qualities + the LongDesc breeding block) and +// evaluates it with IltBreedingEssence: stud / dam, each gate that fails, when it clears, growth; +// * counts Ivo's supplies and applies a breeding booster to an essence after the player confirms; +// * runs "@breed-debug" (quietly) for the room check and "@dance" to start the ritual; +// * logs breeding chat (ritual, charge spent, birth, guardian, growth, adulthood, imprint); +// * learns this server's rules from its own text (IltBreedingRules) and reports what it sees to +// the Leaftide feature profile (the pet_breeding / pet_maturity bits). +// Essences are read only while someone is looking (the section drawn, or a reader asking for the +// JSON within WatchMs), so an unwatched tracker costs nothing. +// Threading: Tick / OnChat / actions on the pump; Render on the ImGui thread reads only the +// immutable snapshot and posts actions. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Everything the breeding UI and reader JSON show, rebuilt whole on the pump. +/// is a frozen copy of the rules: the render thread plans with it while the pump learns. +internal sealed record BreedingSnapshot( + IReadOnlyList Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies, + IReadOnlyList Rules, IReadOnlyList Events, BreedDebugInfo? Debug, DateTime DebugUtc, + IltTri Enabled, IltTri Maturity, IltTri Bond, string Room, int FreeSlots, string Message, double NowUnix, bool Built, + IltBreedingRules RulesView) +{ + public static readonly BreedingSnapshot Empty = new(Array.Empty(), Array.Empty<(BreedSupplyDef, long)>(), + Array.Empty(), Array.Empty(), null, default, IltTri.Unknown, IltTri.Unknown, + IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState())); +} + +internal sealed class IltPetBreeding : IIltFeature +{ + /// Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows). + public const string BitBreeding = RynthIltHub.FeaturePetBreeding; + public const string BitMaturity = "pet_maturity"; + + /// ACE commands: the diagnostics reply, and the courtship dance. + public const string DebugCommand = "@breed-debug"; + public const string DanceCommand = "@dance"; + + // ACECustom pet device qualities (AssessmentProperty, sent with the appraisal). + private const uint StrLongDesc = 16; + private const uint IntUseRequiresLevel = 369; + private const uint IntUseLevelRequirement = 364; + private const uint IntBondLevel = 9053; + private const uint IntPotencyStored = 9056; + private const uint IntMaleCharges = 9057; + private const uint IntMutDamage = 9070, IntMutDamageResist = 9071, IntMutCrit = 9072, IntMutVitality = 9073, IntMutPotency = 9074; + private const uint IntMutationCount = 9075; + private const uint IntMaturityKills = 9077; + private const uint FloatNextBreeding = 9056; + private const uint FloatMaleRefresh = 9057; + private const uint FloatIncense = 9058; + private const uint FloatMaturityXpMult = 9059; + private const uint BoolBondAttuned = 9047; + private const uint BoolNeutered = 9051; + private const uint BoolMaleOverride = 50053; + private const uint BoolJuvenile = 50054; + private const uint BoolCatalyst = 50055; + private const uint BoolOffering = 50056; + + /// The tracker reads essences while it was looked at within this long. + private const long WatchMs = 6000; + /// How often a watched tracker re-reads the essences. + private const long ScanMs = 2000; + /// Appraisal requests per scan for essences not yet appraised. + private const int AppraisePerScan = 2; + + private readonly IltHubContext _ctx; + private readonly IltBreedingRules _rules; + private long _watchedAt; // Interlocked: render thread and readers mark it + private long _scannedAt; + private bool _refreshAll; // re-appraise every essence on the next scan (after an event) + private string _message = string.Empty; + private volatile BreedingSnapshot _snap = BreedingSnapshot.Empty; + private volatile string _readerJson = string.Empty; + + // Render-thread selections (ids of carried essences; 0 = none). + private int _studId, _damId, _targetId; + + public IltPetBreeding(IltHubContext ctx) + { + _ctx = ctx; + _rules = new IltBreedingRules(ctx.State.Pet.Breeding); + } + + /// The rules (tests and the controller). + internal IltBreedingRules Rules => _rules; + + /// The latest snapshot (any thread). + public BreedingSnapshot Snapshot => _snap; + + /// Someone is looking: keep the essences fresh for a while (any thread). + public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs); + + /// The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread. + public string ReaderJson + { + get { MarkWatched(); return _readerJson; } + } + + private static double UnixNow => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0; + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - System.Threading.Interlocked.Read(ref _watchedAt) > WatchMs) return; + if (_scannedAt != 0 && nowMs - _scannedAt < ScanMs) return; + _scannedAt = nowMs; + Scan(); + } + + public bool OnChat(string text) + { + if (string.IsNullOrEmpty(text)) return false; + DateTime utc = DateTime.UtcNow; + bool changed = _rules.LearnAll(IltBreedingRules.FromChat(text), utc); + foreach (string raw in text.Split('\n')) + { + string line = raw.Trim(); + string? kind = EventKind(line); + if (kind == null) continue; + _rules.AddEvent(kind, line, utc); + changed = true; + if (kind is "ritual" or "birth" or "charge") _ctx.Options.Set(BitBreeding, IltTri.On); + if (kind is "growth" or "adult") + { + _ctx.Options.Set(BitMaturity, IltTri.On); + if (IltBreedingRules.TryParseGrownInto(line, out int stage, out string name)) _rules.LearnStageName(stage, name); + } + // The essences changed on the server (charges, rest, a baby, growth): read them again soon. + if (kind is not "dance") { _refreshAll = true; _scannedAt = 0; } + } + if (changed) RynthLog.Trace(LogCat.IltPets, "breeding: chat updated rules / events"); + return false; + } + + public void OnLogout() + { + _snap = BreedingSnapshot.Empty; + _readerJson = string.Empty; + _scannedAt = 0; + _message = string.Empty; + } + + /// The event kind of a breeding chat line, or null for any other line. + internal static string? EventKind(string line) + { + if (line.Length == 0) return null; + if (line.StartsWith("The mating ritual has begun between", StringComparison.OrdinalIgnoreCase)) return "ritual"; + if (line.Contains("spent a breeding charge", StringComparison.OrdinalIgnoreCase)) return "charge"; + if (line.Contains("A baby pet has been born", StringComparison.OrdinalIgnoreCase)) return "birth"; + if (line.StartsWith("The union stirs something", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("yields to its parents", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("Awakened Blessing", StringComparison.OrdinalIgnoreCase)) return "mutation"; + if (line.Contains("spectral guardian dissolves", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("has grown into a", StringComparison.OrdinalIgnoreCase)) return "growth"; + if (line.Contains("has reached adulthood", StringComparison.OrdinalIgnoreCase)) return "adult"; + if (line.Contains("has imprinted on you", StringComparison.OrdinalIgnoreCase)) return "imprint"; + if (line.StartsWith("[Breeding] Your pet performs the courtship dance", StringComparison.OrdinalIgnoreCase)) return "dance"; + if (line.StartsWith("You administer the Nurturing Draught", StringComparison.OrdinalIgnoreCase)) return "supply"; + if (line.StartsWith("You have permanently spayed/neutered", StringComparison.OrdinalIgnoreCase)) return "supply"; + return null; + } + + // ── Scan (pump) ───────────────────────────────────────────────────────── + + /// Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON. + private void Scan() + { + IltInventory inv = _ctx.Inventory; + RynthCoreHost host = _ctx.Host; + double now = UnixNow; + DateTime utc = DateTime.UtcNow; + var essences = new List(); + int appraised = 0; + bool sawBlock = false, sawGrowth = false; + + foreach (WorldObject wo in inv.Items()) + { + uint wcid = inv.Wcid(wo); + if (!IltBreedingEssence.IsCombatEssence(wcid) && !LooksLikeEssence(wo, inv)) continue; + + BreedEssenceFacts f = ReadFacts(host, inv, wo, wcid); + if (f.LongDesc.Contains("Sex:", StringComparison.Ordinal)) sawBlock = true; + if (f.LongDesc.Contains("Growth:", StringComparison.Ordinal)) sawGrowth = true; + _rules.LearnAll(IltBreedingRules.FromAppraisal(f.LongDesc, f.MaleRefreshUnix, now), utc); + if (IltBreedingRules.TryParseGrowth(f.LongDesc, out string stageName, out int stage, out _, out _, out _, out _)) + _rules.LearnStageName(stage, stageName); + essences.Add(IltBreedingEssence.Evaluate(f, _rules, now)); + + // Appraise what isn't loaded (a few per scan), or everything after a breeding event. + if ((_refreshAll || !f.HasId) && appraised < (_refreshAll ? 32 : AppraisePerScan) && inv.RequestAppraisal(wo)) + appraised++; + } + _refreshAll = false; + + // The server only writes the breeding block while breeding is on: seeing it is the server saying so. + if (sawBlock) _ctx.Options.Set(BitBreeding, IltTri.On); + if (sawGrowth) _ctx.Options.Set(BitMaturity, IltTri.On); + + essences.Sort((a, b) => + { + int c = b.Ready.CompareTo(a.Ready); + if (c != 0) return c; + c = b.Male.CompareTo(a.Male); + return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + + var supplies = new List<(BreedSupplyDef, long)>(IltBreedingSupplies.All.Length); + foreach (BreedSupplyDef s in IltBreedingSupplies.All) supplies.Add((s, inv.CountByWcid(s.Wcid))); + + IltBreedingState st = _rules.State; + BreedDebugInfo? debug = st.LastDebug.Count > 0 ? IltBreedingRules.ParseDebug(st.LastDebug) : null; + var events = st.Log.Select(e => new IltBreedingEvent { Utc = e.Utc, Kind = e.Kind, Text = e.Text }).ToArray(); + + var snap = new BreedingSnapshot(essences, supplies, _rules.All(), events, debug, st.LastDebugUtc, + EnabledState(), _ctx.Options.Get(BitMaturity), _ctx.Options.Get(IltFeature.PetBond), + _rules.RoomText(), inv.FreeMainPackSlots(), _message, now, true, _rules.Frozen()); + _snap = snap; + _readerJson = BuildJson(snap, _rules, _ctx.Options.WorldName); + } + + /// The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on"). + private IltTri EnabledState() + { + IltTri t = _ctx.Options.Get(BitBreeding); + return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown; + } + + /// An essence outside the WCID table (a new family) that the server gave a breeding block. + private static bool LooksLikeEssence(WorldObject wo, IltInventory inv) + => wo.Name.EndsWith("Essence", StringComparison.OrdinalIgnoreCase) + && inv.Str(wo, StrLongDesc).Contains("Sex:", StringComparison.Ordinal); + + private static BreedEssenceFacts ReadFacts(RynthCoreHost host, IltInventory inv, WorldObject wo, uint wcid) + { + uint id = unchecked((uint)wo.Id); + var f = new BreedEssenceFacts + { + Id = wo.Id, + Name = wo.Name, + Wcid = wcid, + HasId = inv.HasAppraisal(wo), + Bond = inv.Int(wo, IntBondLevel), + PotencyStored = inv.Int(wo, IntPotencyStored), + MutDamage = inv.Int(wo, IntMutDamage), + MutDamageResist = inv.Int(wo, IntMutDamageResist), + MutCrit = inv.Int(wo, IntMutCrit), + MutVitality = inv.Int(wo, IntMutVitality), + MutPotency = inv.Int(wo, IntMutPotency), + MutationCount = inv.Int(wo, IntMutationCount), + Neutered = TryBool(host, id, BoolNeutered, out bool n) && n, + JuvenileFlag = TryBool(host, id, BoolJuvenile, out bool j) && j, + Catalyst = TryBool(host, id, BoolCatalyst, out bool c) && c, + Offering = TryBool(host, id, BoolOffering, out bool o) && o, + Attuned = TryBool(host, id, BoolBondAttuned, out bool a) && a, + NextBreedUnix = TryDouble(host, id, FloatNextBreeding), + MaleRefreshUnix = TryDouble(host, id, FloatMaleRefresh), + Incense = TryDouble(host, id, FloatIncense), + MaturityXpMult = TryDouble(host, id, FloatMaturityXpMult), + LongDesc = inv.Str(wo, StrLongDesc), + }; + f.UseLevel = inv.Int(wo, IntUseRequiresLevel); + if (f.UseLevel <= 0) f.UseLevel = inv.Int(wo, IntUseLevelRequirement); + if (TryBool(host, id, BoolMaleOverride, out bool male)) f.MaleOverride = male; + // Absent and 0 differ for these two: absent = never bred / a full stud. + f.MaturityKills = TryInt(host, id, IntMaturityKills, out int kills) ? kills : -1; + f.MaleCharges = TryInt(host, id, IntMaleCharges, out int charges) ? charges : -1; + return f; + } + + private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v) + { + v = false; + return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v); + } + + private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v) + { + v = 0; + return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v); + } + + private static double TryDouble(RynthCoreHost host, uint id, uint stype) + => host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out double v) ? v : 0; + + // ── Actions (pump) ────────────────────────────────────────────────────── + + /// Re-appraises every essence and rescans. + public void RefreshAll() + { + _refreshAll = true; + _scannedAt = 0; + MarkWatched(); + } + + /// Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby). + public void RequestDebug() + { + if (_ctx.Capture.IsPending(DebugCommand)) return; + _message = "Asking the server for breeding diagnostics..."; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = DebugCommand, + IsResponseLine = IltBreedingRules.IsDebugLine, + IsTerminator = IltBreedingRules.IsDebugEnd, + IdleEndMs = 1500, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = ApplyDebug, + }); + _scannedAt = 0; + } + + private void ApplyDebug(IltChatResult r) + { + if (r.UnknownCommand) { _message = "This server has no @breed-debug (no pet breeding here)."; _ctx.Options.Set(BitBreeding, IltTri.Off); return; } + if (r.NotSent) { _message = "This RynthCore can't send chat commands."; return; } + if (r.Lines.Count == 0) { _message = "No reply to @breed-debug."; return; } + DateTime utc = DateTime.UtcNow; + IltBreedingState st = _rules.State; + st.LastDebug = new List(r.Lines); + st.LastDebugUtc = utc; + foreach (string l in r.Lines) _rules.LearnAll(IltBreedingRules.FromChat(l), utc); + BreedDebugInfo d = IltBreedingRules.ParseDebug(r.Lines); + if (d.Enabled.HasValue) _ctx.Options.Set(BitBreeding, d.Enabled.Value ? IltTri.On : IltTri.Off); + _message = d.Enabled == false ? "The server says breeding is switched off." + : d.LocationOk == true ? $"You're in the breeding room. Partners nearby: {Math.Max(0, d.Partners)}." + : d.LocationOk == false ? $"Not in the breeding room ({_rules.RoomText()})." + : "Diagnostics read."; + _rules.AddEvent("debug", _message, utc); + _scannedAt = 0; + } + + /// Starts the courtship dance ("@dance"); the breed happens when a partner dances in time. + public void Dance() + { + if (!_ctx.Host.HasInvokeChatParser) { _message = "This RynthCore can't send chat commands."; return; } + _ctx.Host.InvokeChatParser(DanceCommand); + _message = $"Danced. Your partner must *dance* within {_rules.Get(IltBreedingRules.DanceWindow):0.#}s with their pet in the same room."; + _scannedAt = 0; + } + + /// + /// Uses a supply on a carried essence, re-checking both are still here and that the server would + /// take it. Returns a message for the UI. Called after the player confirmed. + /// + public string ApplySupply(string key, int essenceId) + { + BreedSupplyDef? def = IltBreedingSupplies.Find(key); + if (def == null || !def.Apply) return _message = "That supply isn't applied from here."; + IltInventory inv = _ctx.Inventory; + WorldObject? item = inv.FindByWcid(def.Wcid); + if (item == null) return _message = $"No {def.Name} in your pack."; + BreedEssence? e = _snap.Essences.FirstOrDefault(x => x.Id == essenceId); + if (e == null || !inv.Items().Any(wo => wo.Id == essenceId)) return _message = "That essence isn't in your pack any more."; + string? refuse = IltBreedingSupplies.RefuseReason(def, e, _rules); + if (refuse != null) return _message = refuse; + if (inv.IsBusy) return _message = "You're busy; try again in a moment."; + bool sent = inv.UseOn(item, unchecked((uint)essenceId)); + _message = sent ? $"Used {def.Name} on {e.Name}." : $"Couldn't use {def.Name} (the engine refused)."; + if (sent) _rules.AddEvent("supply", _message, DateTime.UtcNow); + RefreshAll(); + return _message; + } + + /// + /// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance, + /// or "apply <supplyKey> <essenceId>" (the reader confirmed it with the player). Pump thread. + /// + public void RunVerb(string line) + { + string[] parts = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + switch (parts[0].ToLowerInvariant()) + { + case "refresh": RefreshAll(); break; + case "debug": RequestDebug(); break; + case "dance": Dance(); break; + case "apply" when parts.Length == 3 && int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id): + ApplySupply(parts[1], id); + break; + default: + RynthLog.Trace(LogCat.IltPets, $"breeding: unknown reader verb '{line}'"); + break; + } + } + + // ── Reader JSON ───────────────────────────────────────────────────────── + + /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape). + internal static string BuildJson(BreedingSnapshot s, IltBreedingRules r, string world) + { + var sb = new StringBuilder(4096); + sb.Append("{\"available\":true"); + Str(sb, "world", world); + Str(sb, "enabled", TriText(s.Enabled)); + Str(sb, "maturity", TriText(s.Maturity)); + Str(sb, "bond", TriText(s.Bond)); + Str(sb, "room", s.Room); + sb.Append(",\"freeSlots\":").Append(s.FreeSlots); + Str(sb, "message", s.Message); + + sb.Append(",\"essences\":["); + for (int i = 0; i < s.Essences.Count; i++) + { + BreedEssence e = s.Essences[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"id\":").Append(e.Id); + Str(sb, "name", e.Name); + Str(sb, "sex", e.Male ? "M" : "F"); + sb.Append(",\"tier\":").Append(e.Tier).Append(",\"bond\":").Append(e.Bond); + sb.Append(",\"ready\":").Append(e.Ready ? "true" : "false"); + Str(sb, "status", e.Status); + double readyIn = e.ReadyAtUnix > s.NowUnix ? e.ReadyAtUnix - s.NowUnix : 0; + sb.Append(",\"readyIn\":").Append((long)Math.Ceiling(readyIn)); + sb.Append(",\"charges\":").Append(e.Charges).Append(",\"chargesMax\":").Append(e.ChargesMax); + sb.Append(",\"juvenile\":").Append(e.Juvenile ? "true" : "false"); + Str(sb, "stage", e.StageName); + sb.Append(",\"kills\":").Append(e.Kills).Append(",\"killsRequired\":").Append(e.KillsRequired); + sb.Append(",\"mutations\":").Append(e.StatMutations).Append(",\"potencyMutations\":").Append(e.MutP); + Arr(sb, "problems", e.Problems); + Arr(sb, "boosters", e.Boosters); + sb.Append('}'); + } + sb.Append(']'); + + // Ready pairings, best odds first (the fewest inherited mutations keeps the decay low). + var studs = s.Essences.Where(e => e.Male && e.Ready).ToList(); + var dams = s.Essences.Where(e => !e.Male && e.Ready).ToList(); + var pairs = new List<(BreedEssence Stud, BreedEssence Dam, BreedPairPlan Plan)>(); + foreach (BreedEssence st in studs) + foreach (BreedEssence d in dams) + pairs.Add((st, d, IltBreedingPlanner.Plan(st, d, r))); + pairs.Sort((a, b) => b.Plan.ChanceBest.CompareTo(a.Plan.ChanceBest)); + sb.Append(",\"pairs\":["); + for (int i = 0; i < pairs.Count && i < 6; i++) + { + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "stud", pairs[i].Stud.Name, first: true); + Str(sb, "dam", pairs[i].Dam.Name); + sb.Append(",\"chanceBest\":").Append(pairs[i].Plan.ChanceBest.ToString("0.####", CultureInfo.InvariantCulture)); + sb.Append(",\"chanceWorst\":").Append(pairs[i].Plan.ChanceWorst.ToString("0.####", CultureInfo.InvariantCulture)); + sb.Append(",\"inheritMin\":").Append(pairs[i].Plan.InheritMin).Append(",\"inheritMax\":").Append(pairs[i].Plan.InheritMax); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"supplies\":["); + for (int i = 0; i < s.Supplies.Count; i++) + { + (BreedSupplyDef def, long count) = s.Supplies[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "key", def.Key, first: true); + Str(sb, "name", def.Name); + Str(sb, "effect", def.Effect); + sb.Append(",\"count\":").Append(count).Append(",\"price\":").Append(def.Price); + sb.Append(",\"apply\":").Append(def.Apply ? "true" : "false"); + // Essences the server would take this on now (the reader's Use buttons). + var targets = def.Apply && count > 0 + ? s.Essences.Where(e => IltBreedingSupplies.RefuseReason(def, e, r) == null).Select(e => e.Id).ToList() + : new List(); + sb.Append(",\"targets\":[").Append(string.Join(',', targets)).Append(']'); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"rules\":["); + for (int i = 0; i < s.Rules.Count; i++) + { + BreedRuleValue v = s.Rules[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "label", v.Def.Label, first: true); + Str(sb, "value", IltBreedingRules.Format(v)); + Str(sb, "source", IltBreedingRules.SourceText(v.Source)); + Str(sb, "help", v.Def.Help); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"events\":["); + int start = Math.Max(0, s.Events.Count - 20); + for (int i = s.Events.Count - 1; i >= start; i--) + { + IltBreedingEvent e = s.Events[i]; + if (i != s.Events.Count - 1) sb.Append(','); + sb.Append('{'); + Str(sb, "when", e.Utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); + Str(sb, "kind", e.Kind); + Str(sb, "text", e.Text); + sb.Append('}'); + } + sb.Append(']'); + + if (s.Debug != null) + { + BreedDebugInfo d = s.Debug; + sb.Append(",\"debug\":{"); + Str(sb, "when", s.DebugUtc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); + Str(sb, "enabled", d.Enabled == null ? "unknown" : d.Enabled.Value ? "on" : "off"); + Str(sb, "location", d.Location); + Str(sb, "match", d.LocationOk == null ? "" : d.LocationOk.Value ? "valid" : "invalid"); + Str(sb, "pet", d.ActivePet); + Str(sb, "sex", d.PetSex); + sb.Append(",\"partners\":").Append(d.Partners); + sb.Append('}'); + } + sb.Append('}'); + return sb.ToString(); + } + + private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + + private static void Str(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('"'); + } + + private static void Arr(StringBuilder sb, string name, IReadOnlyList values) + { + sb.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < values.Count; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(IltStyle.JsonEscape(values[i])).Append('"'); + } + sb.Append(']'); + } + + // ── UI (render thread): Mini Remote > Pets > Breeding ─────────────────── + + /// The Breeding tab's body (RynthIltHub.SectionPetBreeding). + public void RenderSection() + { + MarkWatched(); + BreedingSnapshot s = _snap; + + RenderHeader(s); + if (!s.Built) + { + ImGui.TextDisabled("Reading your essences..."); + return; + } + ImGui.Separator(); + RenderEssences(s); + RenderPlanner(s); + RenderSupplies(s); + RenderRules(s); + RenderEvents(s); + RenderGuide(s); + } + + private void RenderHeader(BreedingSnapshot s) + { + Vector4 col = s.Enabled == IltTri.Off ? IltStyle.ColHp : IltStyle.ColTeal; + SafeImGui.TextColored(col, s.Enabled switch + { + IltTri.Off => "Pet breeding is off on this server.", + IltTri.On => $"Pet breeding: on. Breeding room: {s.Room}.", + _ => "Pet breeding: not confirmed yet (run Diagnostics in the breeding room).", + }); + if (s.Bond == IltTri.Off) SafeImGui.TextColored(IltStyle.ColAmber, "Pet bond is off here, so bond can't reach the breeding minimum."); + + if (ImGui.SmallButton("Refresh##brrefresh")) _ctx.Post(RefreshAll); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-appraise every essence (charges, rest timers, bond, growth)."); + ImGui.SameLine(); + if (ImGui.SmallButton("Diagnostics##brdebug")) _ctx.Post(RequestDebug); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("@breed-debug: are you in the breeding room, your summoned pet, partners nearby (reply hidden, shown here)."); + ImGui.SameLine(); + if (ImGui.SmallButton("Dance##brdance")) + _ctx.Confirm("Courtship dance", + "Dance now? If your partner dances within the window with both pets summoned in the same room, the breed happens:" + + " the stud spends a charge, the dam rests, incense is used up and the baby goes to the dam's owner.", + Dance, "Dance"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("@dance (the same as typing *dance*). Both owners must dance within the window."); + + if (s.Message.Length > 0) SafeImGui.TextDisabled(s.Message); + if (s.FreeSlots == 0) SafeImGui.TextColored(IltStyle.ColAmber, "Your main pack is full: as the dam's owner you couldn't receive the baby."); + } + + private void RenderEssences(BreedingSnapshot s) + { + int ready = s.Essences.Count(e => e.Ready); + if (!ImGui.CollapsingHeader($"Essences ({ready} ready of {s.Essences.Count})###bress", ImGuiTreeNodeFlags.DefaultOpen)) return; + if (s.Essences.Count == 0) + { + ImGui.TextDisabled("No combat pet essences in your pack."); + return; + } + + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.ScrollY; + float h = Math.Min(260f, 26f + s.Essences.Count * ImGui.GetTextLineHeightWithSpacing()); + if (!ImGui.BeginTable("##brtable", 6, flags, new Vector2(0, h))) return; + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("Essence", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Sex", ImGuiTableColumnFlags.WidthFixed, 34); + ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 34); + ImGui.TableSetupColumn("Bond", ImGuiTableColumnFlags.WidthFixed, 38); + ImGui.TableSetupColumn("Breeding", ImGuiTableColumnFlags.WidthFixed, 130); + ImGui.TableSetupColumn("Muts", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableHeadersRow(); + for (int i = 0; i < s.Essences.Count; i++) + { + BreedEssence e = s.Essences[i]; + ImGui.PushID(i); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + bool picked = e.Id == _studId || e.Id == _damId; + if (ImGui.Selectable(SafeText(e.Name) + "##sel", picked, ImGuiSelectableFlags.SpanAllColumns)) + { + if (e.Male) _studId = e.Id; else _damId = e.Id; + _targetId = e.Id; + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(e)); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.Male ? "M" : "F"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.HasId ? e.Bond.ToString(CultureInfo.InvariantCulture) : "?"); + ImGui.TableNextColumn(); + Vector4 col = e.Ready ? IltStyle.ColGreen + : e.Gate is BreedGate.Resting or BreedGate.NoCharges or BreedGate.Growing or BreedGate.NeedsId ? IltStyle.ColAmber + : IltStyle.ColTextMute; + SafeImGui.TextColored(col, e.Status); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.MutP > 0 ? $"{e.StatMutations}+{e.MutP}p" : e.StatMutations.ToString(CultureInfo.InvariantCulture)); + ImGui.PopID(); + } + ImGui.EndTable(); + ImGui.TextDisabled("Click a male to pick the stud, a female for the dam (and the supply target). Hover for details."); + } + + private static string Tooltip(BreedEssence e) + { + var sb = new StringBuilder(); + sb.Append(e.Name).Append('\n').Append(e.Role).Append(", tier ").Append(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?") + .Append(", bond ").Append(e.Bond); + if (e.Male) sb.Append("\nCharges ").Append(e.Charges).Append('/').Append(e.ChargesMax); + if (e.Bred) sb.Append(e.Juvenile ? $"\nGrowing: {e.StageName}, {e.KillsToNext} kills to the next stage, {Math.Max(0, e.KillsRequired - e.Kills)} to Adult" : "\nBred: Adult"); + if (e.Unbound) sb.Append("\nUnbound: imprints on the first character to summon it."); + sb.Append($"\nMutations: damage {e.MutD}, damage resist {e.MutDR}, crit {e.MutC}, vitality {e.MutV}, potency {e.MutP}"); + if (e.Boosters.Count > 0) sb.Append("\nBoosters: ").Append(string.Join(", ", e.Boosters)); + foreach (string p in e.Problems) sb.Append("\n- ").Append(p); + return sb.ToString(); + } + + private void RenderPlanner(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("Pair planner###brplan")) return; + BreedEssence? stud = s.Essences.FirstOrDefault(e => e.Id == _studId && e.Male); + BreedEssence? dam = s.Essences.FirstOrDefault(e => e.Id == _damId && !e.Male); + PickCombo("Stud##brstud", s.Essences.Where(e => e.Male).ToList(), stud, id => _studId = id); + PickCombo("Dam##brdam", s.Essences.Where(e => !e.Male).ToList(), dam, id => _damId = id); + if (stud == null || dam == null) + { + ImGui.TextDisabled("Pick a stud and a dam (yours, or an alt's carried here) to see the odds."); + ImGui.TextDisabled("Breeding needs two owners: each dances with their own summoned pet."); + return; + } + BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, s.RulesView); + if (p.CanBreed) SafeImGui.TextColored(IltStyle.ColGreen, "Both are ready to breed."); + foreach (string b in p.Blockers) SafeImGui.TextColored(IltStyle.ColAmber, b); + SafeImGui.Text($"Stat mutation chance: {Pct(p.ChanceWorst)} to {Pct(p.ChanceBest)} (baby inherits {p.InheritMin}-{p.InheritMax} stat mutations)"); + SafeImGui.Text($"Potency mutation chance: {Pct(p.PotencyChance)}" + (p.Incense > 0 ? $"; incense +{p.Incense * 100:0.#}%" : "")); + foreach (string n in p.Notes) SafeImGui.BulletText(n); + } + + private static void PickCombo(string label, List list, BreedEssence? current, Action set) + { + ImGui.SetNextItemWidth(260); + if (!ImGui.BeginCombo(label, current != null ? SafeText(current.Name) : "(none)")) return; + foreach (BreedEssence e in list) + { + if (ImGui.Selectable($"{SafeText(e.Name)} - {SafeText(e.Status)}##{e.Id}", current != null && current.Id == e.Id)) set(e.Id); + } + ImGui.EndCombo(); + } + + private void RenderSupplies(BreedingSnapshot s) + { + long carried = s.Supplies.Sum(x => x.Count); + if (!ImGui.CollapsingHeader($"Supplies ({carried} carried)###brsup")) return; + BreedEssence? target = s.Essences.FirstOrDefault(e => e.Id == _targetId); + PickCombo("Use on##brtarget", s.Essences.ToList(), target, id => _targetId = id); + ImGui.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed."); + for (int i = 0; i < s.Supplies.Count; i++) + { + (BreedSupplyDef def, long count) = s.Supplies[i]; + ImGui.PushID("sup" + i); + Vector4 col = count > 0 ? IltStyle.ColGreen : IltStyle.ColTextMute; + SafeImGui.TextColored(col, $"{count,3} {def.Name}"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{def.Effect}\nIvo's price: {IltBreedingSupplies.PriceText(def.Price)} pyreals"); + if (def.Apply && count > 0 && target != null) + { + ImGui.SameLine(300); + string? refuse = IltBreedingSupplies.RefuseReason(def, target, s.RulesView); + if (refuse != null) + { + ImGui.TextDisabled("can't"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(refuse); + } + else if (ImGui.SmallButton("Use")) + { + string key = def.Key; + int id = target.Id; + _ctx.Confirm("Use " + def.Name, + $"Use {def.Name} on {target.Name}? {def.Effect}{IltBreedingSupplies.Warning(def, target)}", + () => ApplySupply(key, id), "Use"); + } + } + ImGui.PopID(); + } + } + + private void RenderRules(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("Server rules###brrules")) return; + ImGui.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults."); + foreach (BreedRuleValue v in s.Rules) + { + SafeImGui.Text(v.Def.Label); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(v.Def.Help); + ImGui.SameLine(200); + SafeImGui.Text(IltBreedingRules.Format(v)); + ImGui.SameLine(280); + SafeImGui.TextColored(v.Source == BreedRuleSource.Server ? IltStyle.ColGreen : IltStyle.ColTextMute, + IltBreedingRules.SourceText(v.Source)); + } + if (s.Debug != null) + { + ImGui.Separator(); + SafeImGui.TextDisabled($"Last diagnostics ({s.DebugUtc.ToLocalTime():g}):"); + BreedDebugInfo d = s.Debug; + if (d.Location.Length > 0) SafeImGui.BulletText("You: " + d.Location); + if (d.LocationOk.HasValue) SafeImGui.BulletText(d.LocationOk.Value ? "In the breeding room" : "Not in the breeding room"); + if (d.ActivePet.Length > 0) SafeImGui.BulletText("Pet: " + d.ActivePet + (d.PetSex.Length > 0 ? " (" + d.PetSex + ")" : "")); + if (d.Partners >= 0) SafeImGui.BulletText($"Partners nearby: {d.Partners}"); + } + } + + private static void RenderEvents(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader($"Recent events ({s.Events.Count})###brevents")) return; + if (s.Events.Count == 0) ImGui.TextDisabled("Nothing yet: rituals, births, growth and charges land here."); + for (int i = s.Events.Count - 1, shown = 0; i >= 0 && shown < 20; i--, shown++) + { + IltBreedingEvent e = s.Events[i]; + SafeImGui.TextDisabled(e.Utc.ToLocalTime().ToString("MM-dd HH:mm", CultureInfo.InvariantCulture)); + ImGui.SameLine(90); + SafeImGui.TextWrapped(e.Text); + } + } + + private static void RenderGuide(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("How to breed###brguide")) return; + SafeImGui.BulletText($"Go to the Seedy Motel (portal by Prof. Ruggan in Lin, 54.7S 73.5E); breeding room {s.Room}."); + SafeImGui.BulletText("Two owners: one summons a male (stud), the other a female (dam). Both pets in the same room."); + SafeImGui.BulletText("Both parents: tier 100+, bond 100+, adult, not shiny, not neutered. The stud needs a charge, the dam must have rested."); + SafeImGui.BulletText("Both owners *dance* (or @dance) within a few seconds. The baby goes to the dam's owner (free pack slot needed)."); + SafeImGui.BulletText("A mating guardian may rise: both parents kill it in time for an Awakened Blessing mutation."); + SafeImGui.BulletText("The baby imprints on whoever summons it first, and grows up with kills (Nurturing Draught doubles the credit)."); + } + + private static string Pct(double v) => (v * 100).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + + /// Item names go into ImGui labels, where "##" would start the hidden id. + private static string SafeText(string s) => (s ?? string.Empty).Replace("#", ""); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs index 55b456b..8db5181 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -78,7 +79,7 @@ internal sealed class IltPetLogs : IIltFeature if (ImGui.TreeNode($"{label} ({snap.Length})##{key}")) { if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies)); - foreach (string s in snap) ImGui.BulletText(s); + foreach (string s in snap) SafeImGui.BulletText(s); ImGui.TreePop(); } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs index 7e45198..ac87d89 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs @@ -63,6 +63,10 @@ internal sealed class IltProgression : IIltFeature private volatile string _augStatus = "not loaded"; // Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet. private bool _augAutoTried; + /// Second Refresh current while /aug is already queued or in flight (UB coalesces the same way). + private bool _augRefreshAgain; + /// Passive /aug window: accept AugLine chat until this tick (like T11's report parser). + private long _augPassiveUntilMs; // Cached player facts for the render thread (refreshed in Tick). private volatile int _enl, _level, _freeSlots; @@ -104,38 +108,82 @@ internal sealed class IltProgression : IIltFeature public void RequestAugs() { RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()"); - if (_ctx.Options.IsOff(IltFeature.Aug) || _ctx.Capture.IsPending("/aug")) return; + if (_ctx.Options.IsOff(IltFeature.Aug)) + { + _augStatus = "/aug is off for this world"; + return; + } + // Coalesce: a click during an in-flight /aug runs again when that capture finishes (UB). + if (_ctx.Capture.IsPending("/aug")) + { + _augRefreshAgain = true; + _augStatus = "refresh queued (waiting for current /aug)..."; + return; + } _augStatus = "loading..."; + _augPassiveUntilMs = IltHubContext.NowMs + 20_000; // also accept lines if capture finishes early _ctx.Capture.Enqueue(new IltChatRequest { Command = "/aug", IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t), + // Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines. + ArmsIdle = t => IltParse.AugLine.IsMatch(t), IdleEndMs = 2000, FirstLineTimeoutMs = 15000, Eat = true, OnComplete = r => { - if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; } + if (r.UnknownCommand) + { + _ctx.Options.Set(IltFeature.Aug, IltTri.Off); + _augStatus = "/aug not available"; + _augRefreshAgain = false; + return; + } ApplyAugLines(r.Lines); + if (r.TimedOut) + { + int have; + lock (_augLevels) have = _augLevels.Count; + if (have == 0) + _augStatus = "timed out waiting for /aug level lines"; + } + if (_augRefreshAgain) + { + _augRefreshAgain = false; + RequestAugs(); + } }, }); } - /// Parses "/aug" output (also fed from the login probe). + /// Parses "/aug" output (also fed from the login probe and passive chat). public void ApplyAugLines(List lines) { RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})"); int n = 0; foreach (string l in lines) { - var m = IltParse.AugLine.Match(l.Trim()); - if (!m.Success) continue; - string key = m.Groups[1].Value.ToLowerInvariant(); - if (key == "specialize") key = "specialization"; - lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value); - n++; + if (TryApplyAugLine(l)) n++; } _augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply"; + RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines done: {_augStatus} (raw lines={lines.Count})"); + } + + /// Applies one "/aug" Type: N line. Returns true when a known planner key was updated. + private bool TryApplyAugLine(string raw) + { + var m = IltParse.AugLine.Match((raw ?? string.Empty).Trim()); + if (!m.Success) return false; + string key = m.Groups[1].Value.ToLowerInvariant(); + if (key == "specialize") key = "specialization"; + // Planner rows only; charm / Triune Weave lines are ignored here (T11 reads those). + bool known = false; + foreach (var (k, _) in IltAugCosts.Labels) + if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; } + if (!known) return false; + lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value); + return true; } /// Sends "/enl" (server shows the confirmation dialog). Pump thread. @@ -172,6 +220,18 @@ internal sealed class IltProgression : IIltFeature public bool OnChat(string text) { Attributes.OnChat(text); + // Passive /aug reader: updates Current even when the capture idle finished on the banner alone + // (chat-hold backlog) or the player typed /aug by hand. Window opens on the header. + string t = text; + if (t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + else if (IltHubContext.NowMs <= _augPassiveUntilMs && TryApplyAugLine(t)) + { + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + int n; + lock (_augLevels) n = _augLevels.Count; + _augStatus = $"{n} aug types @ {DateTime.Now:t}"; + } if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase) || text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase)) { @@ -188,6 +248,8 @@ internal sealed class IltProgression : IIltFeature Attributes.OnLogout(); lock (_augLevels) _augLevels.Clear(); _augAutoTried = false; + _augRefreshAgain = false; + _augPassiveUntilMs = 0; _augStatus = "not loaded"; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs index 38203d9..a95f9cb 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Numerics; using System.Text.RegularExpressions; using ImGuiNET; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -178,7 +179,7 @@ internal sealed class IltQuestBonus : IIltFeature if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb())); ImGui.SameLine(); long count = _qbCount; - ImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus); + SafeImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus); string filter = _ctx.State.Character.QbFilter; ImGui.SetNextItemWidth(220); @@ -195,7 +196,7 @@ internal sealed class IltQuestBonus : IIltFeature if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}")) { if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown)); - foreach (string s in shown) ImGui.TextColored(color, s); + foreach (string s in shown) SafeImGui.TextColored(color, s); ImGui.TreePop(); } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs new file mode 100644 index 0000000..f0e1883 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs @@ -0,0 +1,130 @@ +// IltRingChain.cs - Infinite Leaftide's ring inscription chain (Gear tab > Rings), from UB-IT's +// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy. SilentKelpie's RynthAi Crafting > Rings +// (MiniRemote/Crafting/RingChain.cs), moved to RynthILT 2026-10-15: it is Leaftide-only. +// +// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction +// Step 2: Enlightened Quill used on Ink of Partition -> partition quill +// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll +// Then each scroll is used on a ring / jewelry / weapon. +// +// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the +// craft queue order and the scroll-to-target pairing. IltRingChainRunner does the using. +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One ingredient: the first of found in an item's name, unless it also has . +internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = ""); + +/// One combine: is used on . +/// 1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first. +/// Step 3: the words the resulting inscription scroll's name carries. +internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes, + IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers); + +internal static class IltRingChain +{ + /// Every inscription scroll's name has this. + public const string InscriptionMarker = "Inscription of"; + /// Most runs of one recipe the tab queues. + public const int MaxRuns = 99; + + private static readonly IltRingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition", + new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" }); + + private static IltRingRecipe Glyph(string id, string element, string scroll) => new( + id, 3, $"Step 3: {element} glyph - {scroll}", + $"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.", + PartitionQuill, + // The full glyph name: a short one can match the wrong stack. + new IltRingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }), + new[] { scroll, element }); + + /// The chain, in UB-IT's order. + public static readonly IltRingRecipe[] Recipes = + { + new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy", + "Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.", + new IltRingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"), + // Not plain "Trophy": scrolls and kits carry that word too. + new IltRingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }), + Array.Empty()), + new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition", + "Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.", + new IltRingIngredient("Enlightened Quill of Infliction", + new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"), + new IltRingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }), + Array.Empty()), + Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"), + Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"), + Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"), + Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"), + Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"), + Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"), + Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"), + Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"), + }; + + /// True when an item's name is this ingredient. + public static bool Matches(string? name, IltRingIngredient ing) + { + if (string.IsNullOrEmpty(name)) return false; + if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false; + foreach (string n in ing.Names) + if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + /// + /// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in + /// definition order (a later tier's ingredients come out of the earlier one). + /// + public static List Expand(Func runs) + { + var queue = new List(); + foreach (var r in Recipes.OrderBy(r => r.Tier)) + { + int n = Math.Clamp(runs(r.Id), 0, MaxRuns); + for (int i = 0; i < n; i++) queue.Add(r); + } + return queue; + } + + /// The glyph recipe a scroll came from (null when its name has no known marker). + public static IltRingRecipe? GlyphOf(string? scrollName) + { + if (string.IsNullOrEmpty(scrollName)) return null; + foreach (var r in Recipes) + foreach (string m in r.ScrollMarkers) + if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r; + return null; + } + + public static bool IsInscriptionScroll(string? name) + => !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0; + + /// The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name. + public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName; + + /// + /// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones + /// last, by name), targets by object id, one scroll per target. + /// + public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable targets) + { + var ordered = scrolls + .OrderBy(s => ScrollOrderKey(s.Name), StringComparer.Ordinal) + .ThenBy(s => s.Id) + .ToList(); + var pairs = new List<(int, int)>(); + int i = 0; + foreach (int t in targets.Distinct().OrderBy(x => x)) + { + if (i >= ordered.Count) break; + pairs.Add((ordered[i++].Id, t)); + } + return pairs; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs new file mode 100644 index 0000000..d4b9106 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs @@ -0,0 +1,557 @@ +// IltRingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls +// (Gear tab > Rings). SilentKelpie's RynthAi RingChainRunner (MiniRemote/Crafting/), moved to +// RynthILT 2026-10-15 and run on the ILT Hub's context; its settings are the Gear state's +// (IltGearState.RingRuns, RingAnswerCraftDialog, RingAllowInCombat), saved with the Hub. +// +// Tick runs on the pump thread; Render on the render thread reads the volatile snapshots and +// posts the commands (IltHubContext.Post / Confirm). +// Crafting: the queue from IltRingChain.Expand, one combine at a time: +// 1. gates: peace mode (unless allowed in combat for servers with combat crafting), not busy, +// no other ILT pack job (the split-arrow imbuer); +// 2. find the tool and the target by name; a later step's ingredients come out of the earlier +// combine, so a missing one is looked for again for a while (inventory lag) before giving up; +// 3. arm the engine's confirmation answer (API v85; Yes: the player queued it) and use tool on +// target; without v85 (or with the answer off) the player clicks Yes in AC's dialog; +// 4. the combine is done when the tool or the target stack shrinks or the output shows up. +// No sign of it stops the job instead of retrying, so nothing is crafted twice. +// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or +// the carried jewelry paired the UB-IT way) and is done when it leaves the pack. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One line of the Rings scan: a recipe header (Found null) or an ingredient. +/// 0 found, 1 comes from an earlier step, 2 missing. +internal sealed record IltRingScanLine(string Text, string? Found, int State); + +internal sealed class IltRingChainRunner : IIltFeature +{ + private const uint ErrorYoureTooBusy = 0x1D; + private const long StepTimeoutMs = 15_000; + /// The player answers AC's own dialog: give them time. + private const long ManualTimeoutMs = 60_000; + private const long StepGapMs = 700; + private const long RetryDelayMs = 1_500; + private const int MaxBusyRetries = 3; + /// A missing ingredient is looked for this often and this many times (~10 s). + private const long LookAgainMs = 250; + private const int LookTries = 40; + private const long RunsViewMs = 1000; + + private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private enum Mode { Idle, Craft, Apply } + + private readonly IltHubContext _ctx; + /// True while another ILT job (the split-arrow imbuer) is using the pack. + private readonly Func _blocked; + + // Job (pump thread) + private Mode _mode; + private List _queue = new(); + private List<(int Scroll, int Target)> _pairs = new(); + private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq; + private bool _waiting, _manual; + private long _stepAt, _nextAt, _runsViewAt; + // Counts before the current combine (craft) / the scroll's stack (apply). + private long _toolBefore, _targetBefore, _outputBefore; + private int _scrollStackBefore; + + // Render snapshots + private volatile string _status = "idle"; + private volatile IltRingScanLine[] _scan = Array.Empty(); + private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>(); + private volatile (int Id, string Name)[] _jewelry = Array.Empty<(int, string)>(); + // Runs per recipe (IltRingChain.Recipes order), copied from the Gear state on the pump. + private volatile int[] _runsView = new int[IltRingChain.Recipes.Length]; + private volatile bool _running; + + public IltRingChainRunner(IltHubContext ctx, Func blocked) + { + _ctx = ctx; + _blocked = blocked; + } + + public bool Running => _running; + public string Status => _status; + public IltRingScanLine[] ScanLines => _scan; + /// The inscription scrolls the last scan found. + public (int Id, string Name)[] Scrolls => _scrolls; + + private RynthCoreHost Host => _ctx.Host; + private IltInventory Inv => _ctx.Inventory; + private IltGearState G => _ctx.State.Gear; + + /// Pump thread: the saved run count for a recipe. + private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0; + + /// Pump thread: sets a recipe's run count (0 removes it) and the render copy. + public void SetRuns(string id, int runs) + { + runs = Math.Clamp(runs, 0, IltRingChain.MaxRuns); + if (runs == 0) G.RingRuns.Remove(id); + else G.RingRuns[id] = runs; + PublishRuns(); + } + + private void PublishRuns() + { + var view = new int[IltRingChain.Recipes.Length]; + for (int i = 0; i < view.Length; i++) view[i] = Runs(IltRingChain.Recipes[i].Id); + _runsView = view; + } + + // ── Inventory ─────────────────────────────────────────────────────────── + + private IEnumerable Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w)); + + private WorldObject? Find(IltRingIngredient ing) => Carried().FirstOrDefault(w => IltRingChain.Matches(w.Name, ing)); + + private long Count(IltRingIngredient ing) => Carried().Where(w => IltRingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w)); + + private long ScrollCount() => Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w)); + + /// What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll. + private long OutputCount(IltRingRecipe r) => r.Tier switch + { + 1 => Count(IltRingChain.Recipes[1].Tool), + 2 => Count(IltRingChain.Recipes[2].Tool), + _ => ScrollCount(), + }; + + // ── Scan ──────────────────────────────────────────────────────────────── + + /// + /// Lists every queued recipe's ingredients, marking the ones a later step only gets from an + /// earlier combine (UB-IT's "(after Step 1)"), the carried inscription scrolls and the carried + /// jewelry they can go on. Pump thread. + /// + public void Scan() + { + var lines = new List(); + bool Stocked(int tier) => IltRingChain.Recipes + .Where(r => r.Tier == tier && Runs(r.Id) > 0) + .All(r => Find(r.Tool) != null && Find(r.Target) != null); + bool tier1 = Stocked(1), tier2 = Stocked(2); + bool any = false, blocking = false; + foreach (var r in IltRingChain.Recipes) + { + int runs = Runs(r.Id); + if (runs <= 0) continue; + any = true; + lines.Add(new IltRingScanLine($"{r.Name} x{runs}", null, 0)); + foreach (var ing in new[] { r.Tool, r.Target }) + { + var found = Find(ing); + if (found != null) { lines.Add(new IltRingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; } + string? later = r.Tier == 2 && !tier1 ? "(after Step 1)" + : r.Tier == 3 && !tier1 ? "(after Step 1)" + : r.Tier == 3 && !tier2 ? "(after Step 2)" + : null; + if (later == null) blocking = true; + lines.Add(new IltRingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1)); + } + } + _scan = lines.ToArray(); + RefreshScrolls(); + _status = !any ? "set how many times to craft at least one recipe" + : blocking ? "missing ingredients are marked (not found)" + : "ready: Create runs every Step 1, then Step 2, then Step 3"; + } + + private void RefreshScrolls() + { + _scrolls = Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)) + .Select(w => (w.Id, w.Name ?? string.Empty)) + .OrderBy(s => IltRingChain.ScrollOrderKey(s.Item2), StringComparer.Ordinal) + .ToArray(); + _jewelry = Carried().Where(w => w.ObjectClass == AcObjectClass.Jewelry) + .Select(w => (w.Id, w.Name ?? string.Empty)) + .OrderBy(j => j.Id) + .ToArray(); + } + + // ── Job control (pump thread) ─────────────────────────────────────────── + + /// Crafts the queued recipes (after the tab's confirm). + public void Create() + { + if (_running) return; + if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } + var queue = IltRingChain.Expand(Runs); + if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; } + Begin(Mode.Craft); + _queue = queue; + _status = $"crafting {queue.Count} combine(s)"; + RynthLog.Write(LogCat.IltGear, $"[Rings] create, {queue.Count} combine(s)"); + } + + /// Uses one scroll on the item selected in AC. + public void ApplyToSelected(int scrollId) + { + uint sel = Host.GetSelectedItemId(); + if (sel == 0) { _status = "select the ring or item in AC first"; return; } + if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; } + ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) }); + } + + /// Pairs the carried scrolls with these items (the carried jewelry) and uses them. + public void ApplyToItems(IReadOnlyList targetIds) + { + RefreshScrolls(); + if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; } + if (targetIds.Count == 0) { _status = "no jewelry carried (worn items aren't inscribed)"; return; } + ApplyPairs(IltRingChain.PairScrolls(_scrolls, targetIds)); + } + + private void ApplyPairs(List<(int Scroll, int Target)> pairs) + { + if (_running) return; + if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } + if (pairs.Count == 0) { _status = "nothing to apply"; return; } + Begin(Mode.Apply); + _pairs = pairs; + _status = $"applying {pairs.Count} inscription(s)"; + RynthLog.Write(LogCat.IltGear, $"[Rings] apply {pairs.Count} inscription(s)"); + } + + private void Begin(Mode mode) + { + _mode = mode; + _index = 0; + _crafted = 0; + _lookTries = 0; + _busyRetries = 0; + _waiting = false; + _nextAt = 0; + _running = true; + } + + public void Stop(string why) + { + if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + _mode = Mode.Idle; + _waiting = false; + _running = false; + _queue = new List(); + _pairs = new List<(int, int)>(); + _status = why; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void OnLogout() + { + Stop("idle"); + _scan = Array.Empty(); + _scrolls = Array.Empty<(int, string)>(); + _jewelry = Array.Empty<(int, string)>(); + } + + public void Tick(long nowMs) + { + if (nowMs - _runsViewAt >= RunsViewMs) + { + // A profile load replaces the Gear state: follow it. + _runsViewAt = nowMs; + PublishRuns(); + } + if (_mode == Mode.Idle) return; + if (_waiting) { Wait(nowMs); return; } + if (nowMs < _nextAt) return; + if (!G.RingAllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; } + if (Inv.IsBusy) return; + + if (_mode == Mode.Craft) NextCombine(nowMs); + else NextScroll(nowMs); + } + + private void NextCombine(long nowMs) + { + if (_index >= _queue.Count) + { + Stop($"done - {_crafted} combine(s)"); + RefreshScrolls(); + RynthLog.Write(LogCat.IltGear, $"[Rings] done, {_crafted} combine(s)"); + return; + } + var r = _queue[_index]; + var tool = Find(r.Tool); + var target = Find(r.Target); + if (tool == null || target == null) + { + string label = tool == null ? r.Tool.Label : r.Target.Label; + if (++_lookTries <= LookTries) + { + _nextAt = nowMs + LookAgainMs; + _status = $"{r.Name}: looking for {label}"; + return; + } + Stop($"{r.Name}: no {label} in the pack"); + return; + } + _lookTries = 0; + + _toolBefore = Count(r.Tool); + _targetBefore = Count(r.Target); + _outputBefore = OutputCount(r); + if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})")) + { + Stop($"{r.Name}: the use request didn't go out"); + return; + } + string ask = _manual ? " - click Yes in AC's craft dialog" : ""; + _status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}"; + } + + private void NextScroll(long nowMs) + { + if (_index >= _pairs.Count) + { + Stop($"done - {_crafted} inscription(s) applied"); + RefreshScrolls(); + return; + } + var (scrollId, targetId) = _pairs[_index]; + var scroll = Inv.Cache?[scrollId]; + var target = Inv.Cache?[targetId]; + if (scroll == null || target == null) + { + // UB-IT moves on past a pair whose scroll or item is gone. + _status = $"inscription {_index + 1}: the scroll or the item is gone - skipped"; + _index++; + _nextAt = nowMs + StepGapMs; + return; + } + if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; } + _scrollStackBefore = Inv.StackSize(scroll); + if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}")) + { + Stop("the use request didn't go out"); + return; + } + string ask = _manual ? " - click Yes in AC's dialog" : ""; + _status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}"; + } + + /// Arms the dialog answer (Yes: the player asked for this) and uses source on target. + private bool Use(WorldObject source, WorldObject target, string why) + { + _manual = !(G.RingAnswerCraftDialog && Host.HasConfirmationAnswers + && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1); + _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; + _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; + if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "IltRings", why, UseKind.Asked)) + { + if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + return false; + } + _waiting = true; + _stepAt = Environment.TickCount64; + return true; + } + + private void Wait(long nowMs) + { + if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _) + && seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction) + { + _confSeq = seq; + if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; } + if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed) + { + _manual = true; + _status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})"; + } + } + + if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq) + { + _errSeq = es; + // Busy: the server did nothing, so the same combine can go again. + if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries) + { + _waiting = false; + _nextAt = nowMs + RetryDelayMs; + _status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})"; + return; + } + Stop($"the server refused it (error 0x{error:X})"); + return; + } + + if (Done()) { Next(nowMs); return; } + + if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs)) + Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)"); + } + + /// The current combine or inscription went through. + private bool Done() + { + if (_mode == Mode.Craft) + { + var r = _queue[_index]; + return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore; + } + var scroll = Inv.Cache?[_pairs[_index].Scroll]; + return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore; + } + + private void Next(long nowMs) + { + _waiting = false; + _busyRetries = 0; + _crafted++; + _index++; + _nextAt = nowMs + StepGapMs; + } + + /// "cannot be used on" ends the job: the names didn't match what the server expects. Never eaten. + public bool OnChat(string text) + { + if (!_waiting || string.IsNullOrEmpty(text)) return false; + if (CannotUse.IsMatch(text)) Stop(text); + return false; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + /// The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls. + public void Render() + { + ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring."); + int[] runsView = _runsView; + if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Recipe"); + for (int i = 0; i < IltRingChain.Recipes.Length; i++) + { + var r = IltRingChain.Recipes[i]; + ImGui.PushID(r.Id); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + int n = i < runsView.Length ? runsView[i] : 0; + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("##runs", ref n, 1)) + { + string id = r.Id; + int runs = Math.Clamp(n, 0, IltRingChain.MaxRuns); + var shown = (int[])runsView.Clone(); + shown[i] = runs; + _runsView = shown; // shown at once; the pump saves it and republishes + _ctx.Post(() => SetRuns(id, runs)); + } + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Name); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes); + ImGui.PopID(); + } + ImGui.EndTable(); + } + + bool answer = G.RingAnswerCraftDialog, combat = G.RingAllowInCombat; + if (ImGui.Checkbox("Answer the craft dialog##rings", ref answer)) G.RingAnswerCraftDialog = answer; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Answers AC's craft confirmation Yes for each combine you queued (needs RynthCore plugin API v85).\nOff, or on an older RynthCore: click Yes in AC's dialog yourself."); + ImGui.SameLine(); + if (ImGui.Checkbox("Allow in combat mode##rings", ref combat)) G.RingAllowInCombat = combat; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting in combat mode."); + + bool running = Running; + bool blocked = _blocked(); + ImGui.BeginDisabled(running); + if (ImGui.Button("Scan##rings")) _ctx.Post(Scan); + ImGui.SameLine(); + ImGui.BeginDisabled(blocked); + if (ImGui.Button("Create##rings")) + { + int[] view = _runsView; + int total = IltRingChain.Expand(id => + { + int k = Array.FindIndex(IltRingChain.Recipes, x => x.Id == id); + return k >= 0 && k < view.Length ? view[k] : 0; + }).Count; + _ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.", + Create, "Create"); + } + ImGui.EndDisabled(); + ImGui.EndDisabled(); + ImGui.SameLine(); + ImGui.BeginDisabled(!running); + if (ImGui.Button("Stop##rings")) _ctx.Post(() => Stop("stopped by player")); + ImGui.EndDisabled(); + ImGui.SameLine(); + if (blocked && !running) ImGui.TextColored(IltStyle.ColAmber, "the split-arrow imbuer is running"); + else SafeImGui.TextDisabled(Status); + + var lines = ScanLines; + if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp)) + { + foreach (var l in lines) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + if (l.Found == null) { SafeImGui.TextColored(IltStyle.ColTeal, l.Text); continue; } + ImGui.TextUnformatted(" " + l.Text); + ImGui.TableNextColumn(); + if (l.State == 0) ImGui.TextUnformatted(l.Found); + else if (l.State == 1) SafeImGui.TextDisabled(l.Found); + else SafeImGui.TextColored(IltStyle.ColAmber, l.Found); + } + ImGui.EndTable(); + } + + ImGui.Separator(); + RenderScrolls(running || blocked); + } + + /// The carried inscription scrolls: one to the selected item, or all to the carried jewelry. + private void RenderScrolls(bool busy) + { + ImGui.TextColored(IltStyle.ColTeal, "Inscription scrolls"); + var scrolls = Scrolls; + if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; } + + ImGui.BeginDisabled(busy); + foreach (var (id, name) in scrolls) + { + ImGui.PushID(id); + if (ImGui.SmallButton("Apply to selected")) + { + int scrollId = id; + string scrollName = name; + _ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?", + () => ApplyToSelected(scrollId), "Apply"); + } + ImGui.SameLine(); + ImGui.TextUnformatted(name); + ImGui.PopID(); + } + + // UB-IT pairs the scrolls with a scan's items; here the carried (not worn) jewelry. + var jewelry = _jewelry; + var targets = jewelry.Select(j => j.Id).ToList(); + ImGui.BeginDisabled(targets.Count == 0); + if (ImGui.Button($"Apply all to the carried jewelry ({targets.Count})")) + { + int pairs = Math.Min(targets.Count, scrolls.Length); + _ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the carried jewelry, one each?", + () => ApplyToItems(targets), "Apply"); + } + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip("Scrolls in glyph order go on the jewelry in your pack (not worn) in id order (UB-IT's pairing).\n" + + (jewelry.Length == 0 ? "No jewelry carried (Scan to look again)." + : string.Join("\n", jewelry.Select(j => j.Name)))); + ImGui.EndDisabled(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs new file mode 100644 index 0000000..5682bc5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs @@ -0,0 +1,72 @@ +// IltSalvage.cs - Infinite Leaftide's own tinkering salvage, for the Mini Remote's Crafting tab. +// +// Served through RynthILT's "RynthServer.Profile" JSON (ProfileInterface.cs, the "salvage" list), +// which RynthAi's Crafting tab shows under "Server tinkering" on ILT; RynthAi itself knows no +// server's recipes. Taken from UB-IT's LeaftideImbueHelper via SilentKelpie (his RynthAi Crafting +// tab, rynth/RynthSuite PR 12, moved here 2026-10-15): the weapon crit lines (Yellow Garnet, +// Turquoise, White Quartz, Abyssal-Touched Gems, Tourmaline, Wool), Tiger Eye on missile weapons, +// Leather as the post-cap tink, the jewelry rating salvages (Silver, Copper, Green Jade, +// Tourmaline, and Serpentine + Steel sharing a cap of 10) and the trinket tiers (Diamond, Ruby, +// Gromnie Hide, Pyreal, prepared on Ammunition). ILT's recipes live in its database, so their +// chances are the server's: the Crafting runner reads the confirmation's percent. +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltSalvage +{ + // 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, + Silver = 63, Steel = 64, Serpentine = 71; + + // ILT's flag ints on the item: 2 = that salvage is on. + public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSilver = 374, IntJewelTourmaline = 375; + public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387; + + /// Steel and Serpentine stack on ILT jewelry, at most this many combined. + public const string JewelryStackGroup = "jewelry-stack"; + public const int JewelryStackCap = 10; + + private const string Once = "once", Tink = "tink"; + private const string PostCap = "100% tink once the 10 ordinary tinks are on"; + + public static readonly ServerSalvage[] Rows = + { + new("melee", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("melee", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("melee", WhiteQuartz, "Cleaving (no tink slot)", Once, UsesTinkSlot: false, Order: 90), + new("melee", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), + new("melee", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), + new("melee", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), + new("melee", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + new("missile", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("missile", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("missile", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), + new("missile", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), + new("missile", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), + new("missile", TigerEye, "+missile defense bonus", Tink, Order: 230), + new("missile", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + new("caster", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("caster", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("caster", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + // ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots. + new("jewelry", Silver, "+1 critical damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelSilver, Order: 10), + new("jewelry", Copper, "+1 damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelCopper, Order: 20), + new("jewelry", GreenJade, "+1 damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade, Order: 30), + new("jewelry", Tourmaline, "+1 critical damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline, Order: 40), + new("jewelry", Serpentine, "+1 critical rating (stacks with Steel, 10 max)", Tink, UsesTinkSlot: false, Order: 50, + StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), + new("jewelry", Steel, "Steel stack tier (stacks with Serpentine, 10 max)", Tink, UsesTinkSlot: false, Order: 60, + StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), + + // UB-IT's trinket imbues, in its order: Diamond, Ruby, Gromnie Hide, Pyreal. + new("trinkets", Diamond, "Trinket tier: Diamond", Once, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true, Order: 10), + new("trinkets", Ruby, "Trinket tier: Ruby", Once, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true, Order: 20), + new("trinkets", GromnieHide, "Trinket tier: Gromnie Hide", Once, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true, Order: 30), + new("trinkets", Pyreal, "Trinket tier: Pyreal", Once, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true, Order: 40), + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs index 9a00675..080c7df 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs @@ -1,20 +1,30 @@ // IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel. // Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13. // -// Character, Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws -// the tab bar (after its Remote, Quests and Pets tabs) and asks RynthILT for each tab's body -// (RynthILT.Hub GetTabs / RenderTab); "/ra hub open
" picks one. Guardian is a RynthCore -// ILT panel instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this -// plugin through RynthPluginRenderEmbed("guardian"). The Quests and Pets tabs are RynthAi's -// (every server: /myquests and summoning essences aren't ILT's). +// Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar +// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub +// GetTabs / RenderTab); "/ra hub open
" picks one, and with RynthCore's sections rail +// RynthAi lists them as "section:" views (Inventory). Guardian is a RynthCore ILT panel +// instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through +// RynthPluginRenderEmbed("guardian"). The Pets tab is RynthAi's (every server: summoning essences +// aren't ILT's); quests are RynthOracle's. +// +// Character was a Mini Remote tab until 2026-10-13. It moved out: +// the character overview and session -> RynthOracle's Character tab ("/ro character"); +// the ILT session rates -> RynthCore's Mini Remote "Session Stats" section +// (RynthILT's own surface "section:ilt-rates"); +// the force-server override -> RynthCore Options > Diagnostics only. +// Its names still parse, so old links and commands land on the new home (MovedCommand). Charms and +// Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. using System; using System.Numerics; namespace RynthCore.Plugin.RynthILT.Hub; -/// ILT sections: the Mini Remote's ILT tabs, then the Guardian panel. +/// ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel. internal enum IltSection { + /// Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section. Character, Banking, Gear, @@ -30,12 +40,15 @@ internal static class IltSections /// The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs). public static readonly IltSection[] Tabs = { - IltSection.Character, IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, + IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, }; /// The Mini Remote's own tab (the remote itself): its tab id. public const string RemoteTab = ""; + /// RynthOracle's Character tab: the character overview and this session. + public const string OracleCharacterCommand = "/ro character"; + public static string Label(IltSection s) => s switch { IltSection.Character => "Character", @@ -62,10 +75,20 @@ internal static class IltSections _ => s.ToString().ToLowerInvariant(), }; - /// True for the sections drawn as Mini Remote tabs (all but the Guardian panel). - public static bool IsTab(IltSection s) => s != IltSection.Guardian; + /// True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games). + public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games; - /// "quests" / "pets" (and their aliases): RynthAi's universal tabs, not ILT sections. + /// + /// Where a section that moved out of the Mini Remote lives now, as the chat command that opens + /// it; null for a section that is still RynthILT's (a tab or the Guardian panel). + /// + public static string? MovedCommand(IltSection s) => s switch + { + IltSection.Character => OracleCharacterCommand, + _ => null, + }; + + /// "quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests). public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch { "quests" or "quest" or "pets" or "pet" => true, @@ -83,7 +106,7 @@ internal static class IltSections case "games": case "game": section = IltSection.Games; return true; case "charms": case "charm": section = IltSection.Charms; return true; case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true; - default: section = IltSection.Character; return false; + default: section = IltSection.Gear; return false; } } @@ -93,7 +116,6 @@ internal static class IltSections ///
public static Vector2 TabSize(IltSection section) => section switch { - IltSection.Character => new Vector2(520, 440), IltSection.Banking => new Vector2(560, 520), IltSection.Gear => new Vector2(560, 520), IltSection.Charms => new Vector2(560, 520), diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs index 90f4544..15ddef1 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs @@ -7,17 +7,20 @@ // * World identity: ServerFeatureGate (RynthILT's server list, or this character's // override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never // switches a feature on by itself. -// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once -// ACECustom ships it. Today the server prints "Coming Soon", so: -// * Fallback: a one-shot login probe of read-only commands (/bank, /aug, /qb, /pets, -// /shinies, /xp, /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten. +// * Everything is decided on the Rynth side: the server is never asked for a feature list +// (ACECustom has none; "/ilt features" prints "Coming Soon"). IltFeatureCatalog's ILT +// profile says what the server runs, and these bits only record what the server returned: +// * Login probe: one pass of read-only commands (/bank, /aug, /qb, /pets, /shinies, /xp, +// /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten. // /enl is NEVER probed — it opens the enlightenment confirmation dialog. // * Passive: explicit server refusals seen in chat at any time flip a bit to Off -// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...). +// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...), +// and lines only an enabled feature sends flip it On (a summon-time pyreal refill). // Unknown bits are treated as OFF by anything that spends currency or runs automation. using System; using System.Collections.Generic; using System.Linq; +using RynthCore.Plugin.RynthILT.IltSettingsView; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthILT.Hub; @@ -103,11 +106,23 @@ internal sealed class IltServerOptions } } + /// RynthCore's id for Infinite Leaftide in its server verdicts. + public const string EngineServerId = "ilt"; + /// - /// True when the world is (or is declared to be) an ACECustom/ILT shard: its name is in the - /// server list (IltSettings), or this character's override is on (ServerFeatureGate). + /// RynthCore (2026.10.5.47+) decides whether this is Infinite Leaftide: one world check for + /// the engine and every plugin, with its per-character override ("/rc server ilt on|off|auto"). + /// True once its first verdict has arrived (IltEngineVerdict). /// - public bool IsIltLikeWorld + public static bool EngineDecides => IltEngineVerdict.Active.HasValue; + + /// + /// RynthILT's own verdict: the world name is in the server list (IltSettings), or this + /// character's "Treat this world as ILT" is on (ServerFeatureGate). This is what the status + /// export reports to the engine, which adds it to its own detection (never echo the engine's + /// verdict back, or it would latch on). + /// + public bool IsIltLikeWorldLocal { get { @@ -118,7 +133,21 @@ internal sealed class IltServerOptions } } - /// True while a refresh (dump or probe) is running. + /// + /// True when the world is (or is declared to be) an ACECustom/ILT shard. With a RynthCore + /// that sends server verdicts, its verdict (which already includes ours, IsIltLikeWorldLocal, + /// unless this character's override is off); otherwise our own. + /// + public bool IsIltLikeWorld + { + get + { + bool? engine = IltEngineVerdict.Active; + return engine ?? IsIltLikeWorldLocal; + } + } + + /// True while the login probe is running. public bool IsRefreshing => _refreshInFlight; public string Source => _state.ServerOptions.Source; @@ -179,8 +208,11 @@ internal sealed class IltServerOptions return; } - // World not reported yet: try again next tick rather than concluding "not ILT". - if (string.IsNullOrEmpty(WorldName) && sinceLogin < WorldNameWaitMs) + // World not reported yet: try again next tick rather than concluding "not ILT". RynthCore's + // verdict trails the world name by up to a second (its push), and before its first push + // there is none: keep checking for the same window rather than conclude early. + if ((string.IsNullOrEmpty(WorldName) || EngineDecides || !IltEngineVerdict.Pushed) + && sinceLogin < WorldNameWaitMs) return; _loginRefreshDone = true; @@ -189,8 +221,8 @@ internal sealed class IltServerOptions } /// - /// Runs the dump-then-probe refresh. Manual refreshes report progress in chat; the - /// login refresh is silent. + /// Runs the probe refresh. Manual refreshes report progress in chat; the login refresh is + /// silent. /// public void Refresh(bool manual) { @@ -201,7 +233,10 @@ internal sealed class IltServerOptions } if (!IsIltLikeWorld) { - if (manual) _chat("[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override)."); + if (manual) + _chat(EngineDecides + ? "[Mini Remote] RynthCore doesn't treat this world as Infinite Leaftide (/rc server ilt on forces it for this character; /rc server names ilt add adds the world)." + : "[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override)."); return; } @@ -210,87 +245,8 @@ internal sealed class IltServerOptions RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')"); if (manual) _chat("[Mini Remote] Refreshing server options..."); - // Step 1: structured dump. Lines start with "=== ILT Custom Features ===". - _capture.Enqueue(new IltChatRequest - { - Command = "/ilt features", - IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase) - || t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase) - || t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase), - IdleEndMs = 1200, - FirstLineTimeoutMs = 8000, - Eat = true, - OnComplete = r => OnFeatureDump(r, manual), - }); - } - - private void OnFeatureDump(IltChatResult r, bool manual) - { - var fromDump = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string line in r.Lines) - { - if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue; - foreach (var kv in ParseFeatureLine(line)) - { - Set(kv.Key, kv.Value); - fromDump.Add(kv.Key); - } - } - - _state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe"; - RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}"); - RunProbes(fromDump, manual); - } - - /// - /// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0". - /// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys. - /// - internal static IEnumerable> ParseFeatureLine(string line) - { - string body = line.Substring("ILTFEATURE".Length).Trim(); - foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries)) - { - int eq = token.IndexOf('='); - if (eq <= 0) continue; - string key = token.Substring(0, eq).Trim(); - string val = token.Substring(eq + 1).Trim(); - - if (key.Equals("charms", StringComparison.OrdinalIgnoreCase)) - { - foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries)) - { - int c = pair.IndexOf(':'); - if (c <= 0) continue; - yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1))); - } - continue; - } - yield return new(MapServerKey(key), ParseTri(val)); - } - } - - private static IltTri ParseTri(string v) - { - v = v.Trim().ToLowerInvariant(); - return v is "1" or "on" or "true" or "yes" ? IltTri.On - : v is "0" or "off" or "false" or "no" ? IltTri.Off - : IltTri.Unknown; - } - - private static string MapServerKey(string key) - { - string k = key.Trim().ToLowerInvariant(); - return k switch - { - "powerball_enabled" => IltFeature.Powerball, - "quest_info_enabled" => IltFeature.Quests, - "pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill, - "pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery, - "pet_bond_enabled" => IltFeature.PetBond, - "pet_potency_enabled" => IltFeature.PetPotency, - _ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k, - }; + _state.ServerOptions.Source = "probe"; + RunProbes(manual); } // ── Probe ─────────────────────────────────────────────────────────────── @@ -325,15 +281,13 @@ internal sealed class IltServerOptions || t.Contains(keyword2, StringComparison.OrdinalIgnoreCase) || (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith(" alreadyKnown, bool manual) + private void RunProbes(bool manual) { - var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).ToList(); + var todo = Probes.ToList(); // /enl is never probed (it pops the enlightenment confirmation). On an ILT-like - // world the command is part of ACECustom, so it is assumed present unless the - // dump said otherwise. - if (!alreadyKnown.Contains(IltFeature.Enl)) - Set(IltFeature.Enl, IltTri.On); + // world the command is part of ACECustom, so it is assumed present. + Set(IltFeature.Enl, IltTri.On); _probesOutstanding = todo.Count; if (_probesOutstanding == 0) { CompleteRefresh(manual); return; } @@ -345,6 +299,8 @@ internal sealed class IltServerOptions { Command = probe.Command, IsResponseLine = probe.IsReply, + // /aug: banner alone must not end the probe before Creature:/Item: lines arrive. + ArmsIdle = probe.Key == IltFeature.Aug ? t => IltParse.AugLine.IsMatch(t) : null, IdleEndMs = 1500, FirstLineTimeoutMs = 8000, Eat = true, @@ -379,8 +335,8 @@ internal sealed class IltServerOptions // ── Passive refusals ──────────────────────────────────────────────────── /// - /// Watches every chat line for explicit server refusals and flips the matching bit Off. - /// Cheap substring checks; runs on the pump thread. + /// Watches every chat line for explicit server refusals (bit Off) and for lines only an + /// enabled feature sends (bit On). Cheap substring checks; runs on the pump thread. /// public void OnChatLine(string text) { @@ -398,8 +354,19 @@ internal sealed class IltServerOptions Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off); else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase)) Set(IltFeature.Bank, IltTri.Off); + else if (IsPyrealRefillLine(text)) + Set(IltFeature.PetRefill, IltTri.On); } + /// + /// ACECustom's summon-time refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon). The + /// server sends them only while pet_device_pyreal_auto_refill_enabled is on, so any of them + /// proves the refill is on even when the profile says it's off. + /// + internal static bool IsPyrealRefillLine(string text) + => text.Contains("charge on your summoning essence", StringComparison.OrdinalIgnoreCase) + || text.Contains("pyreals to auto-replenish your summoning essence", StringComparison.OrdinalIgnoreCase); + /// Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes). public void NoteQuestTrackerOutcome(bool disabled, int recordCount) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs index 3dff383..813b7f7 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs @@ -1,4 +1,6 @@ -// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab. +// IltSessionRates.cs — Session earnings / per-hour rates for Infinite Leaftide: the coins, pyreals and +// item conversions RynthCore's Mini Remote "Session Stats" section shows under "Server: Infinite +// Leaftide" (surface "section:ilt-rates", 2026-10-13; it was the ILT Character tab before). // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // // Sources (all passive — nothing is sent to the server except the optional bank refresh @@ -44,7 +46,9 @@ internal sealed class IltSessionRates : IIltFeature // Render snapshot. private volatile RateRow[] _rows = Array.Empty(); - private sealed record RateRow(string Label, string Total, string PerHour); + // Shared = one of RynthAi's session stats rows (XP, luminance, kills), which the Session Stats + // section already shows above this table; the embedded view leaves those out. + private sealed record RateRow(string Label, string Total, string PerHour, bool Shared = false); /// Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample). public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour); @@ -157,13 +161,13 @@ internal sealed class IltSessionRates : IIltFeature var rows = new List(); if (_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s)) { - rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour))); - rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour))); + rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour), Shared: true)); + rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour), Shared: true)); // Per hour at the last five minutes' pace. - rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0))); + rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0), Shared: true)); if (s.PassUpTracked != 0) - rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour))); - rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"))); + rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour), Shared: true)); + rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"), Shared: true)); } rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours))); rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours))); @@ -189,12 +193,16 @@ internal sealed class IltSessionRates : IIltFeature // ── UI (render thread) ────────────────────────────────────────────────── - public void Render() + /// + /// True in the Mini Remote's Session Stats section: RynthAi's XP / luminance / kills rows are + /// drawn there already (one session), so only the ILT coins, pyreals and items are listed. + /// + public void Render(bool extrasOnly = false) { // The session clock is RynthAi's session stats' (it and the coins reset together). var start = _ctx.Ai.TryGetSessionStats(out SessionStatsV1 v) && v.SessionSeconds > 0 && v.StartUtcTicks > 0 ? new DateTime(v.StartUtcTicks, DateTimeKind.Utc) : _start; - ImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}"); + SafeImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}"); ImGui.SameLine(); if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll); @@ -206,11 +214,12 @@ internal sealed class IltSessionRates : IIltFeature ImGui.TableHeadersRow(); foreach (var r in _rows) { + if (extrasOnly && r.Shared) continue; ImGui.TableNextRow(); ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label); - if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) ImGui.SetTooltip(PassUpTooltip); + if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) SafeImGui.SetTooltip(PassUpTooltip); ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total); - ImGui.TableNextColumn(); ImGui.TextColored(IltStyle.ColTeal, r.PerHour); + ImGui.TableNextColumn(); SafeImGui.TextColored(IltStyle.ColTeal, r.PerHour); } ImGui.EndTable(); } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs index f7a8469..404b5e4 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs @@ -4,7 +4,8 @@ // The list was RynthAi's Settings > Misc "Server Features" (FeatureServerNames, saved with each // RynthAi profile). RynthILT keeps one list for every character; the first time a character // logs in with RynthILT, IltMigration folds that character's RynthAi list into this one. -// Edited from the Character tab and "/ilt servers ". +// Edited with "/ilt servers " (the Character tab's editor went with the tab, 2026-10-13; +// RynthCore Options > Diagnostics lists the world names RynthCore uses). using System; using System.Collections.Generic; using System.IO; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs index 219092f..01d86f1 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs @@ -14,6 +14,7 @@ using System.Linq; using System.Text.RegularExpressions; using ImGuiNET; using RynthCore.Loot; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; @@ -50,6 +51,9 @@ internal sealed class IltSplitArrows : IIltFeature private IltGearState G => _ctx.State.Gear; public bool Running => _weaponId != 0; + /// True while another ILT pack job (the Rings chain) is running: no imbue starts then. + public Func? Blocked; + private int Needed(WorldObject w) { var inv = _ctx.Inventory; @@ -83,6 +87,7 @@ internal sealed class IltSplitArrows : IIltFeature { var w = _ctx.Inventory.Cache?[weaponId]; if (w == null) { _status = "weapon not found"; return; } + if (Blocked?.Invoke() == true) { _status = "the Rings chain is running"; return; } if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; } int need = Needed(w); if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; } @@ -179,7 +184,7 @@ internal sealed class IltSplitArrows : IIltFeature ImGui.SameLine(); bool skip = G.SplitIgnoreImbued; if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip; - ImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}"); + SafeImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}"); foreach (var w in _weapons) { @@ -200,6 +205,6 @@ internal sealed class IltSplitArrows : IIltFeature } if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried."); if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player")); - ImGui.TextDisabled("Status: " + _status); + SafeImGui.TextDisabled("Status: " + _status); } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs index be81dd6..f696ec3 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs @@ -74,7 +74,7 @@ internal sealed unsafe class RynthAiClient if (_host.HasGetPluginInterface) { var t = (RynthAiHubApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); - if (t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiHubApiV1)) _t = t; + if (t != null && t->Version >= 1 && t->StructSize >= RynthAiHubApiV1.BaseStructSize) _t = t; } System.Threading.Volatile.Write(ref _renderTable, (IntPtr)_t); return _t; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs index f9b948d..3f06a8f 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs @@ -4,9 +4,9 @@ // One gate for everything ILT-shaped: the Mini Remote's ILT tabs, the Guardian, the Skills // panel's Progression planners and the attribute raiser. A world is "on" when: // * its name matches one of the server patterns (IltSettings.ServerNames, '*' wildcard, -// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers" or the Character tab +// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers" // edits them — they were RynthAi's Settings > Misc "Server Features" list), or -// * this character's override is on (the Character tab's "Treat this world as ILT", +// * this character's override is on ("Treat this world as ILT", // "/ra hub force on"; also set by migration from RynthAi's "Force enable" profile flag). // The gate only decides whether RynthILT ASKS the server; each feature still follows the // server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off. @@ -67,7 +67,11 @@ internal static class ServerFeatureGate return true; } - /// The gate itself: the character's override, or the world name in the list. + /// + /// RynthILT's own gate: the character's override, or the world name in the list. RynthCore's + /// verdict, once it sends one, takes over in IltServerOptions.IsIltLikeWorld; this stays ours + /// (it is what the status export reports, IltServerOptions.IsIltLikeWorldLocal). + /// public static bool IsEnabled(string world, IltSettings? settings, bool forceOn) => forceOn || NameMatches(world, Patterns(settings), out _); @@ -92,6 +96,14 @@ internal static class ServerFeatureGate { world = (world ?? string.Empty).Trim(); string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)"; + var engine = IltSettingsView.IltEngineVerdict.Server; + if (engine != null) + { + string why = engine.Force == "on" ? "forced on for this character" + : engine.Force == "off" ? "forced off for this character" + : engine.Detected ? "RynthCore recognises the world" : "RynthCore doesn't recognise the world"; + return $"This world {shown}: {(engine.Active ? "ON" : "OFF")} - {why}."; + } if (NameMatches(world, Patterns(settings), out string matched)) return $"This world {shown}: ON - matches '{matched}'."; if (forceOn) diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs new file mode 100644 index 0000000..ef919a4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs @@ -0,0 +1,62 @@ +// IltFellowshipCommands.cs - Infinite Leaftide's fellowship chat commands (ACECustom /fship). +// +// ACECustom (Source/ACE.Server/Command/Handlers/PlayerCommands.cs, "fship") adds these on top +// of retail's fellowship panel; its fellowships hold up to 29 (Fellowship.MaxFellows). The list +// is kept in the shared "servercommands" form (Plugins/Shared/ServerCommandShare.cs) and drawn by +// RynthILT's fellowship window (IltFellowshipUi, "/ilt fellow"). +// A name with spaces is sent quoted; ACE's command parser joins "two words". Pure: no ImGui, no host. +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltFellowship; + +internal static class IltFellowshipCommands +{ + /// The RynthCore section the commands belong to. + public const string Section = "fellowship"; + + /// RynthCore's server id for Infinite Leaftide. + public const string ServerId = "ilt"; + + /// The server's display name. + public const string ServerName = "Infinite Leaftide"; + + /// ACECustom's fellowship size (Fellowship.MaxFellows; retail is 9). + public const int MaxFellows = 29; + + /// The /fship commands, in button order. + public static readonly IReadOnlyList Commands = new[] + { + new ServerCommand("Create", "/fship create", "A", + "Create a fellowship with the name in the box (you lead it). Up to " + MaxFellows + " members on ILT."), + new ServerCommand("Invite", "/fship add", "a", + "Invite the player named in the box, or your selected player when the box is empty."), + new ServerCommand("Dismiss", "/fship remove", "ac", + "Leader: remove the player named in the box, or your selected player when the box is empty."), + new ServerCommand("Invite landblock", "/fship landblock", "c", + "Invite every player in your landblock (not in the Marketplace). Over level 50, only level 50+ players are invited."), + new ServerCommand("List nearby", "/fship list", "", + "The fellowships in your area and their leaders (wider in VOD and T10). Once every 10 seconds."), + new ServerCommand("Leave", "/fship leave", "c", + "Leave your fellowship."), + new ServerCommand("Disband", "/fship disband", "c", + "Leader: disband your fellowship."), + new ServerCommand("Help", "/fship", "", + "The server's /fship help."), + }; + + /// The set while ILT is active; with no commands when it isn't (a receiver drops it). + public static ServerCommandSet Set(bool active) => + new(Section, ServerId, ServerName, active ? Commands : Array.Empty()); + + /// The "servercommands" payload for . + public static string Payload(bool active) => ServerCommandShare.Build(Set(active)); + + /// + /// ILT is active: RynthCore's verdict once it has sent one (), + /// else the world name has "Leaftide" in it (RynthCore's default ILT names). + /// + public static bool IsActive(bool? engineActive, string? worldName) => + engineActive ?? (worldName ?? string.Empty).IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs new file mode 100644 index 0000000..6c009c9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs @@ -0,0 +1,44 @@ +// IltFellowshipUi.cs - The "ILT fellowship" view: Infinite Leaftide's /fship commands as buttons. +// +// Drawn in its own window ("/ilt fellow"). Clicks queue the chat command for the plugin tick. +// Render thread only. +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltFellowship; + +internal sealed class IltFellowshipUi +{ + private const string WindowTitle = "ILT fellowship (RynthILT)##rynthilt_fellowship"; + + private static readonly ServerCommandSet Set = IltFellowshipCommands.Set(active: true); + + private readonly ServerCommandPanel _panel = new("iltfship"); + private readonly Func _send; + + /// The standalone window is open ("/ilt fellow"). + public bool WindowOpen; + + /// Queues a chat command for the plugin tick; false when it can't. + public IltFellowshipUi(Func send) => _send = send; + + /// The standalone window, while open. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(420, 170), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); + ImGui.End(); + WindowOpen = open; + } + + /// The view's content, into the current window. + public void RenderBody() + { + SafeImGui.TextDisabled("Infinite Leaftide /fship (up to " + IltFellowshipCommands.MaxFellows + " members)"); + _panel.Render(Set, _send); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs new file mode 100644 index 0000000..f14c026 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs @@ -0,0 +1,32 @@ +// IltEngineVerdict.cs - RynthCore's Infinite Leaftide verdict as RynthILT last heard it. +// +// RynthCore decides whether this world is ILT once, for itself and every plugin, with this +// character's Auto / On / Off override ("/rc server ilt"). RynthILT reads that verdict from the +// engine's server list (plugin API v86, GetServerStateJson; the plugin tick polls it into +// IltSettingsModel.Engine). The Hub's world check (IltServerOptions, ServerFeatureGate) follows it +// once one has arrived; before that, or on an engine older than v86, RynthILT's own server list +// and "Treat this world as ILT" decide. +// +// RynthILT's status export must keep reporting its own verdict, not this one: the engine adds +// RynthILT's verdict to its detection, and an echo would keep ILT on after "/rc ilt auto". +// Any thread: one volatile reference read. +using System.Threading; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +internal static class IltEngineVerdict +{ + private static IltSettingsModel? _model; + + /// The model the plugin feeds from RynthCore's server list (RynthILTPlugin's constructor). + public static void Attach(IltSettingsModel? model) => Volatile.Write(ref _model, model); + + /// RynthCore has sent its server list at least once since login (it may list no ILT). + public static bool Pushed => Volatile.Read(ref _model)?.Engine != null; + + /// RynthCore's ILT entry; null until a RynthCore with the server list (v86) has sent one. + public static IltServerView? Server => Volatile.Read(ref _model)?.Engine?.Server; + + /// RynthCore's verdict for this world; null when it hasn't given one. + public static bool? Active => Server?.Active; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs new file mode 100644 index 0000000..9f9076a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs @@ -0,0 +1,114 @@ +// IltSettingsModel.cs - RynthILT's copy of the Infinite Leaftide settings (the "ILT settings" view). +// +// Nothing here is decided by RynthILT; it shows and edits what others own: +// * RynthCore owns the world verdict, this character's Auto / On / Off override and the ILT +// world-name list. RynthILT reads the verdict from its server list (plugin API v86, +// GetServerStateJson, parsed by Plugins/Shared/EngineServerState.cs): the plugin tick polls +// it every 2 s and publishes the "ilt" entry here (ApplyServerState). The world names aren't +// in that list; "/rc server names ilt" prints them. Edits go back as RynthCore commands: +// "/rc server ilt auto|on|off" and "/rc server names ilt add|remove ". +// * RynthILT's own Hub reads which ILT features the server has on; the plugin tick publishes +// them (PublishFeatures). +// Each is one immutable snapshot published with a single reference write, so the render thread +// always reads a whole one. Pure (no host calls): RynthILT.Tests covers it. +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +/// RynthCore's verdict for Infinite Leaftide. +internal sealed record IltServerView(string Name, bool Active, string Force, bool Detected, string Reason); + +/// What RynthCore's server list says: the ILT verdict (null if it lists no "ilt"). +internal sealed record IltEngineView(IltServerView? Server); + +/// The Hub's server read: the world, its last check, and each feature (-1 unknown, 0 off, 1 on). +internal sealed record IltFeatureView(string World, string Source, string LastCheck, bool Checking, bool IltLike, + KeyValuePair[] Features); + +internal sealed class IltSettingsModel +{ + /// RynthCore's id for Infinite Leaftide. + public const string ServerId = EngineServerState.IltId; + + /// Longest pattern RynthCore keeps (EngineSettings.MaxIltServerNameLength). + public const int MaxPattern = 64; + + /// The RynthCore command that prints the ILT world names (and hosts) in chat. + public const string NamesListCommand = "/rc server names " + ServerId; + + private IltEngineView? _engine; + private IltFeatureView? _features; + + /// The last server list from RynthCore (null until one arrives). Any thread. + public IltEngineView? Engine => Volatile.Read(ref _engine); + + /// The last feature read (null until the Hub publishes one). Any thread. + public IltFeatureView? Features => Volatile.Read(ref _features); + + /// RynthCore's server list (GetServerStateJson); null (no answer) keeps the last one. Any thread. + public void ApplyServerState(EngineServerState? state) + { + IltEngineView? view = FromServerState(state); + if (view != null) Volatile.Write(ref _engine, view); + } + + /// The Hub's own feature read (plugin tick); null clears it. Any thread. + public void PublishFeatures(IltFeatureView? view) => Volatile.Write(ref _features, view); + + /// Logout: the next character's world and features come fresh. + public void Clear() + { + Volatile.Write(ref _engine, null); + Volatile.Write(ref _features, null); + } + + /// The ILT verdict from RynthCore's server list; null for no list. + public static IltEngineView? FromServerState(EngineServerState? state) + { + if (state == null) return null; + EngineServer? s = state.Find(ServerId); + return new IltEngineView(s == null ? null + : new IltServerView(s.Name.Length > 0 ? s.Name : "Infinite Leaftide", s.Active, NormalizeForce(s.Force), s.Detected, s.Reason)); + } + + /// "auto", "on" or "off" (anything else is shown as auto). + public static string NormalizeForce(string? force) => (force ?? string.Empty).Trim().ToLowerInvariant() switch + { + "on" => "on", + "off" => "off", + _ => "auto", + }; + + /// The RynthCore command that sets this character's override; "" for an unknown mode. + public static string ForceCommand(string mode) => mode switch + { + "auto" or "on" or "off" => "/rc server " + ServerId + " " + mode, + _ => string.Empty, + }; + + /// + /// The RynthCore command that adds or removes a world-name pattern, or "" (with + /// ) when the pattern can't be sent: empty, longer than + /// , or with a control character or '/' (it is spliced into a command). + /// + public static string NamesCommand(bool add, string? pattern, out string error) + { + error = string.Empty; + string p = (pattern ?? string.Empty).Trim(); + if (p.Length == 0) { error = "Enter a world name ('*' matches any text)."; return string.Empty; } + if (p.Length > MaxPattern) { error = $"At most {MaxPattern} characters."; return string.Empty; } + foreach (char c in p) + if (char.IsControl(c) || c == '/' || c >= 128) + { + error = "World names are plain text (no '/', line breaks or special characters)."; + return string.Empty; + } + return "/rc server names " + ServerId + (add ? " add " : " remove ") + p; + } + + /// A feature's state as text. + public static string StateText(int value) => value switch { 1 => "on", 0 => "off", _ => "unknown" }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs new file mode 100644 index 0000000..0d10361 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs @@ -0,0 +1,198 @@ +// 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). +// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the +// result. Render thread only. +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +internal sealed class IltSettingsUi +{ + private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); + private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); + private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); + + private const string WindowTitle = "ILT settings (RynthILT)##rynthilt_settings"; + + private readonly IltSettingsModel _model; + private readonly Action _runCommand; + private readonly Func _refreshFeatures; + private string _newName = string.Empty; + private string _status = string.Empty; + + /// The standalone window is open ("/ilt settings"). + public bool WindowOpen; + + /// 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) + { + _model = model; + _runCommand = runCommand; + _refreshFeatures = refreshFeatures; + } + + /// The standalone window, while open. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(440, 480), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); + ImGui.End(); + WindowOpen = open; + } + + /// The view's content, into the current window. + public void RenderBody() + { + RenderVerdict(); + ImGui.Separator(); + RenderFeatures(); + if (_status.Length > 0) + { + ImGui.Separator(); + SafeImGui.TextWrapped(_status); + } + } + + private void RenderVerdict() + { + IltEngineView? engine = _model.Engine; + if (engine == null) + { + ImGui.TextWrapped("Waiting for RynthCore's server list (it needs plugin API v86). Until then RynthILT's own " + + "world list and this character's 'Treat this world as ILT' (/ra hub force on|off) decide."); + return; + } + + IltServerView? s = engine.Server; + if (s == null) + { + ImGui.TextDisabled("RynthCore doesn't list Infinite Leaftide."); + } + else + { + SafeImGui.TextColored(s.Active ? Teal : Mute, s.Active ? s.Name + ": on for this world" : s.Name + ": not this world"); + if (s.Reason.Length > 0) + { + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(s.Reason); + ImGui.PopStyleColor(); + } + + // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). + string force = s.Force switch { "on" => "forced on", "off" => "forced off", _ => "auto (detected)" }; + SafeImGui.TextDisabled("This character: " + force + " (change it in RynthCore Options > Diagnostics)"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\nor /rc server ilt auto|on|off in chat."); + } + + ImGui.Spacing(); + ImGui.TextUnformatted("ILT world names"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Worlds whose name matches one of these count as Infinite Leaftide ('*' matches any text).\nThe launch host is checked too. Kept by RynthCore for every character."); + ImGui.SameLine(); + if (ImGui.SmallButton("List in chat##iltnames")) + { + _runCommand(IltSettingsModel.NamesListCommand); + _status = "RynthCore lists the names in chat (" + IltSettingsModel.NamesListCommand + ")."; + } + ImGui.SetNextItemWidth(220); + bool enter = ImGui.InputTextWithHint("##iltnewname", "world name, * = any text", ref _newName, (uint)IltSettingsModel.MaxPattern, + ImGuiInputTextFlags.EnterReturnsTrue); + ImGui.SameLine(); + if (ImGui.Button("Add##iltname") || enter) + { + string cmd = IltSettingsModel.NamesCommand(true, _newName, out string err); + if (Send(cmd, err, "Adding '" + _newName.Trim() + "'...")) _newName = string.Empty; + } + ImGui.SameLine(); + if (ImGui.Button("Remove##iltname")) + { + string cmd = IltSettingsModel.NamesCommand(false, _newName, out string err); + if (Send(cmd, err, "Removing '" + _newName.Trim() + "'...")) _newName = string.Empty; + } + } + + /// + /// 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 + /// how many are on and each feature's state; the tooltip says where the Rynth tools handle it. + /// + private void RenderFeatures() + { + IltFeatureView? f = _model.Features; + ImGui.TextUnformatted("Server features"); + ImGui.SameLine(); + if (ImGui.SmallButton("Refresh##iltfeatures")) + _status = _refreshFeatures() ? "Checking the server again..." : "Not ready yet (log in first)."; + if (f == null) + { + ImGui.TextWrapped("RynthILT reads which ILT features the server has on once this character is logged in. Not read yet."); + return; + } + + string when = f.Checking ? "checking the server..." : f.LastCheck.Length == 0 ? "not checked yet" : "checked " + f.LastCheck; + SafeImGui.TextDisabled((f.World.Length > 0 ? f.World : "unknown world") + " - " + when + + (f.Source.Length > 0 ? " (" + f.Source + ")" : string.Empty)); + if (!f.IltLike) ImGui.TextDisabled("This world isn't treated as Infinite Leaftide, so the server isn't asked."); + if (f.Features.Length == 0) + { + ImGui.TextDisabled("The server hasn't reported any ILT features yet."); + return; + } + + var groups = new Dictionary>(StringComparer.Ordinal); + foreach (var kv in f.Features) + { + var (label, group, tooltip) = IltFeatureCatalog.Describe(kv.Key); + if (!groups.TryGetValue(group, out var rows)) groups[group] = rows = new(); + rows.Add((label, tooltip, kv.Value)); + } + foreach (string group in FeatureGroups()) + { + if (!groups.TryGetValue(group, out var rows)) continue; + int on = 0, off = 0; + foreach (var r in rows) { if (r.State == 1) on++; else if (r.State == 0) off++; } + if (!ImGui.CollapsingHeader($"{group} ({on} of {rows.Count} on)##iltfg_{group}")) continue; + for (int i = 0; i < rows.Count; i++) + { + var r = rows[i]; + SafeImGui.TextColored(r.State == 1 ? Teal : r.State == 0 ? Warn : Mute, IltSettingsModel.StateText(r.State)); + ImGui.SameLine(80); + SafeImGui.Text(r.Label); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Tooltip); + } + } + } + + /// The feature sections in display order: the catalog's groups, then Charms and Other. + private static IEnumerable FeatureGroups() + { + foreach (string g in IltFeatureCatalog.Groups) yield return g; + yield return IltFeatureCatalog.GroupCharms; + yield return IltFeatureCatalog.GroupOther; + } + + /// Queues , or shows when it is empty. + private bool Send(string command, string error, string pending) + { + if (command.Length == 0) + { + _status = error; + return false; + } + _runCommand(command); + _status = pending; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs index 099e9b0..30653ef 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs @@ -11,8 +11,12 @@ public static unsafe class PluginExports { internal static readonly RynthPluginRuntime Runtime = new(); - // Typed interface for RynthAi (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT - // tabs and sections its Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs). + // Typed interfaces (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT tabs and + // 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). // Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) @@ -20,7 +24,10 @@ public static unsafe class PluginExports try { string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; - return HubInterface.Query(iface, version); + IntPtr table = HubInterface.Query(iface, version); + if (table != IntPtr.Zero) return table; + table = ProfileInterface.Query(iface, version); + return table != IntPtr.Zero ? table : DataInterface.Query(iface, version); } catch { @@ -37,9 +44,12 @@ 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 { ProfileInterface.Release(); } catch { } + try { DataInterface.Release(); } catch { } foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero), - Interlocked.Exchange(ref _statusPtr, IntPtr.Zero) }) + Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) }) if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); + _sectionsJson = null; } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] @@ -76,9 +86,13 @@ public static unsafe class PluginExports /// /// Engine panels drawn by RynthILT (render thread): "guardian" is the engine's Guardian ILT - /// panel (RynthCore's GuardianFace); ":popout" is added when it is popped out into a window of - /// its own, and RynthILT draws in the engine's current context either way. The panel is - /// user-sized: want echoes the size given. 1 = drawn, 0 = not ready / unknown surface. + /// panel (RynthCore's GuardianFace); "section:ilt-rates" (the ILT session extras, Session Stats), + /// "section:ilt-fellowship" (the /fship commands), "section:ilt-questbonus" (the /qb list, + /// RynthILT's Quests section) and "section:ilt-settings" (the ILT settings, for an engine that + /// 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. /// [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) @@ -88,16 +102,28 @@ public static unsafe class PluginExports if (surface == null) return 0; ReadOnlySpan name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface); if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length]; - if (!name.SequenceEqual("guardian"u8)) return 0; var plugin = Runtime.Plugin; - if (plugin == null || !plugin.RenderEmbeddedGuardian()) return 0; + if (plugin == null) return 0; + if (name.SequenceEqual("guardian"u8)) + { + if (!plugin.RenderEmbeddedGuardian()) return 0; + if (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = height; + return 1; + } + string? view = name.SequenceEqual("section:ilt-settings"u8) ? RynthILTPlugin.SettingsSurface + : name.SequenceEqual("section:ilt-fellowship"u8) ? RynthILTPlugin.FellowshipSurface + : 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 (wantWidth != null) *wantWidth = width; - if (wantHeight != null) *wantHeight = height; + if (wantHeight != null) *wantHeight = wantH; return 1; } catch { - return 0; + return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client } } @@ -191,11 +217,20 @@ public static unsafe class PluginExports try { string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; + if (action.Length == 0 || action.Length > 32) return; + var plugin = Runtime.Plugin; + if (plugin == null) return; + if (RynthILTPlugin.IsParsedRemoteAction(action)) + { + // RynthCore's "servermenu" push (a few KB): answered here, never queued as an ILT verb. + plugin.ApplyRemoteCommand(action, valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty); + return; + } string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; - if (action.Length == 0 || action.Length + value.Length > 512) return; - Runtime.Plugin?.EnqueueRemoteCommand(action, value); + if (action.Length + value.Length > 512) return; + plugin.EnqueueRemoteCommand(action, value); } - catch { } + catch { /* never let a managed exception cross the native boundary */ } } private static IntPtr _statusPtr = IntPtr.Zero; @@ -203,8 +238,9 @@ public static unsafe class PluginExports /// /// What RynthILT knows about the world (UTF-8 JSON, previous reply valid until the next call): /// {"loaded":true,"ilt":bool,"forced":bool,"available":bool,"world":"..."}. "ilt" is RynthILT's - /// own verdict (its server list or this character's "Treat this world as ILT"); the engine's - /// IltInfo adds it to its own detection. Engine pump thread. + /// own verdict (its server list or this character's "Treat this world as ILT"), never the + /// engine's verdict echoed back: the engine's IltInfo adds it to its own detection, and an + /// echo would keep ILT on after "/rc ilt auto". Engine pump thread. /// [UnmanagedCallersOnly(EntryPoint = "RynthILTGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })] public static IntPtr GetStatusJson() @@ -214,7 +250,7 @@ public static unsafe class PluginExports var hub = Runtime.Plugin?.Hub; string json = hub == null ? "{\"loaded\":true,\"ilt\":false,\"forced\":false,\"available\":false,\"world\":\"\"}" - : "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorld ? "true" : "false") + : "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorldLocal ? "true" : "false") + ",\"forced\":" + (hub.ForceIltWorld ? "true" : "false") + ",\"available\":" + (hub.Available ? "true" : "false") + ",\"world\":\"" + RynthCore.Plugin.RynthILT.Hub.IltStyle.JsonEscape(hub.Options.WorldName) + "\"}"; @@ -223,6 +259,28 @@ public static unsafe class PluginExports catch { return IntPtr.Zero; } } + private static IntPtr _sectionsPtr = IntPtr.Zero; + private static string? _sectionsJson; + + /// + /// RynthCore 2026.10.5.46+ (optional): what RynthILT adds to the Mini Remote's sections (UTF-8 + /// JSON, schema 1; RynthILTPlugin.BuildSectionsJson). Null before login. An unchanged manifest + /// keeps the same buffer. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + string? json = Runtime.Plugin?.BuildSectionsJson(); + if (json == null) return IntPtr.Zero; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + return Utf8Swap(ref _sectionsPtr, json); + } + catch { return IntPtr.Zero; } + } + private static IntPtr Utf8Swap(ref IntPtr slot, string json) { IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); diff --git a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs new file mode 100644 index 0000000..1e7d28c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs @@ -0,0 +1,102 @@ +// ProfileInterface.cs - RynthILT's side of "RynthServer.Profile" (Plugins/Shared/RynthServerProfileApi.cs): +// Infinite Leaftide's settings as JSON for other plugins, the same interface and JSON writer the +// server plugins use (Plugins/Shared/ServerPack/ServerPackProfile.cs). RynthCore's GetServerStateJson +// names RynthILT as the owner of "ilt"; a reader (RynthAi's Crafting tab, ...) then asks it for this. +// The profile carries ILT's tinkering salvage (Hub/IltSalvage.cs). +// +// As ServerPackInterface: the table is allocated once per loaded copy of RynthILT and never freed; +// after Release() it reports Version 0 and GetProfileJson answers 0. Before the Hub is up the profile +// still describes the server (active false, no world). +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class ProfileInterface +{ + private static RynthServerProfileApiV1* _table; + private static volatile bool _released; + + /// What RynthILT knows about its server (identity from the csproj's manifest properties). + internal static readonly ServerPackInfo Info = + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Emulator = "ACE", + Salvage = IltSalvage.Rows, + Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)", + }; + + /// 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 static Snapshot? _last; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); + t->StructSize = (uint)sizeof(RynthServerProfileApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthServerProfileApiV1.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 for RynthILT's verdict () and the world name. + /// Any thread. + /// + internal static string CurrentJson(bool active, string? world) + { + world ??= string.Empty; + 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)); + return json; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + IltHubController? hub = PluginExports.Runtime.Plugin?.Hub; + string json = CurrentJson(hub?.Options.IsIltLikeWorld == true, hub?.Options.WorldName); + return Write(json, 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.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj index db5c2d3..7e7966a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -5,12 +5,16 @@ not in RynthAi or the engine core. The engine shows its panels (the bar's ILT button: Bounties, Guardian; /rc bounties, /rc guardian; the Skills panel's Progression tab) only on ILT (RynthCore Compatibility/IltInfo.cs, which also asks RynthILT). - Bounty/ the Bounties window's tracker (ported from SilentKelpie's rynth/RynthSuite PR #11). - Hub/ the ILT Hub (SilentKelpie's): the Mini Remote's ILT tabs (Character, Banking, Gear, - Charms, Games), the Guardian, the progression planners and the attribute raiser, - server feature detection. Moved out of RynthAi 2026-10-13: RynthAi's Mini Remote - hosts the tabs through RynthILT.Hub, and RynthILT borrows from RynthAi through - RynthAi.Hub (Plugins/Shared/RynthIltHubApi.cs, RynthAiHubApi.cs). + Bounty/ the Bounties window's tracker (ported from SilentKelpie's rynth/RynthSuite PR #11). + Hub/ the ILT Hub (SilentKelpie's): the Mini Remote's ILT tabs (Character, Banking, Gear, + Charms, Games), the Guardian, the progression planners and the attribute raiser, + server feature detection, the Rings inscription chain (Gear tab). Moved out of + RynthAi 2026-10-13: RynthAi's Mini Remote hosts the tabs through RynthILT.Hub, and + 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"). + IltFellowship/ ILT's /fship commands as buttons ("/ilt fellow"). --> net10.0-windows @@ -29,10 +33,17 @@ x86 + newer call (plugin interfaces v68, live object ids v69, vendor trade v67, confirmation + answers v85, the server list v86, ...) is behind its Has* check, as it was in RynthAi. --> 66 - Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression and the attribute raiser. + + ilt + 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. @@ -45,8 +56,19 @@ + + + + + + + + + + @@ -56,6 +78,9 @@ + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs index 903c6e9..a918fbb 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -5,17 +5,33 @@ // /rc bounties). Its reads run only while that window polls RynthILTGetBountiesJson, and the // engine polls only on ILT. // * The ILT Hub (Hub/, SilentKelpie's, moved here from RynthAi 2026-10-13): the Mini Remote's -// ILT tabs (Character, Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through -// RynthILT.Hub, HubInterface.cs), their sections in its Quests / Pets / Remote tabs, the -// Guardian panel (RynthPluginRenderEmbed "guardian"), the Skills panel's Progression data -// (RynthILTGetProgressionJson, "prog ..." through RynthILTCommand), server feature detection. -// Every feature stays dormant off an ILT-like world (IltServerOptions: no probes, no chat). +// ILT tabs (Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through +// RynthILT.Hub, HubInterface.cs, and lists them on RynthCore's sections rail; the Gear tab has +// the Rings inscription chain; the Character tab moved to RynthOracle's Character tab), its +// own Mini Remote sections (BuildSectionsJson: the ILT session extras in Session Stats, the +// /fship buttons in Fellowship, the /qb list in a Quests section), its sections in RynthAi's +// Pets / Remote tabs, the Guardian panel (RynthPluginRenderEmbed "guardian"), +// the Skills panel's Progression data (RynthILTGetProgressionJson, "prog ..." through +// RynthILTCommand), server feature detection, and the charms and bank balances for other +// plugins ("RynthILT.Data", DataInterface.cs). Every feature stays dormant off an ILT-like +// world (IltServerOptions: no probes, no chat). +// +// Second: a copy of the ILT settings (IltSettingsView/): RynthCore's verdict, this character's +// override (read only: it is set in RynthCore Options > Diagnostics), the ILT world names and +// every feature the Hub read from the server, in its own window ("/ilt settings"). The verdict +// comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it +// once one arrives (IltEngineVerdict). +// +// 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. // // Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls // run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it // there, our own InvokeChatParser too), and RynthAi forwards its "/ra hub ..." verbs from there too, // so commands only queue and run on the next tick. OnRender / RenderEmbed and the RynthILT.Hub -// render functions run on the render thread and only read what the pump built. +// render functions run on the render thread and only read what the pump built; the settings and +// fellowship windows queue their chat commands for the tick. using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -24,6 +40,8 @@ using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.Plugin.RynthILT.Bounty; using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.RynthILT.IltFellowship; +using RynthCore.Plugin.RynthILT.IltSettingsView; using RynthCore.Plugin.Shared; using RynthCore.PluginCore; @@ -32,7 +50,51 @@ namespace RynthCore.Plugin.RynthILT; public sealed class RynthILTPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT"); - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.0"); + // Previous release: 0.3.1. + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.2"); + + /// + /// The settings view's surface. Not in the sections manifest (the force-server override lives + /// only in RynthCore Options > Diagnostics), but still drawn for an engine that asks. + /// + internal const string SettingsSurface = "section:ilt-settings"; + + /// The ILT session extras' surface in RynthCore's Mini Remote "Session Stats" section. + internal const string RatesSurface = "section:ilt-rates"; + + /// The fellowship commands' surface in RynthCore's Fellowship section. + internal const string FellowshipSurface = "section:ilt-fellowship"; + + /// + /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (it was part of + /// RynthAi's Quests tab, which moved to RynthOracle; Infinite Leaftide's /qb stays RynthILT's). + /// + internal const string QuestBonusSurface = "section:ilt-questbonus"; + + /// RynthAi's name for the plugin-command broker (its Fellowship view draws our commands). + private const string RynthAiPlugin = "RynthAi"; + + private readonly IltSettingsModel _settingsModel = new(); + private readonly IltSettingsUi _settingsUi; + private readonly IltFellowshipUi _fellowshipUi; + // Chat commands from the settings and fellowship windows (render thread), run on the next tick. + private readonly ConcurrentQueue _chatCommands = new(); + private const int MaxQueuedChatCommands = 32; + + public RynthILTPlugin() + { + _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures); + _fellowshipUi = new IltFellowshipUi(QueueChatCommand); + IltEngineVerdict.Attach(_settingsModel); + } + + /// Render thread: queues a chat command for the tick; false when the engine can't run one. + private bool QueueChatCommand(string command) + { + if (!Host.HasInvokeChatParser || _chatCommands.Count >= MaxQueuedChatCommands) return false; + _chatCommands.Enqueue(command); + return true; + } /// Wait this long after login for the character's name before tracking without a save file. private const long NameWaitMs = 30_000; @@ -100,6 +162,7 @@ public sealed class RynthILTPlugin : RynthPluginBase _nextNameTryMs = 0; _nextHubTryMs = 0; _ai?.Reset(); + PollServerState(force: true); TryStartBounties(); TryStartHub(); } @@ -111,16 +174,24 @@ public sealed class RynthILTPlugin : RynthPluginBase StopHub(); _ai?.Reset(); _loginComplete = false; + ClearSharedFellowshipCommands(); while (_commands.TryDequeue(out _)) { } while (_typedBounty.TryDequeue(out _)) { } + while (_engineCommands.TryDequeue(out _)) { } + while (_chatCommands.TryDequeue(out _)) { } + _settingsModel.Clear(); + _serverStateJson = string.Empty; } - // Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the next copy. + // Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the + // next copy. No broker call while the engine unloads us: RynthAi drops the fellowship commands + // once they stop arriving (ServerCommandModel.StaleMs). public override void Shutdown() { SaveBounties(); StopHub(); HubInterface.Release(); + IltEngineVerdict.Attach(null); RynthLog.Shutdown(); } @@ -129,16 +200,264 @@ public sealed class RynthILTPlugin : RynthPluginBase try { RynthLog.Pump(); } catch { } if (!_loginComplete) return; _ai?.Tick(); + PollServerState(force: false); if (_bounties == null) TryStartBounties(); if (_hub == null) TryStartHub(); DrainTypedBounty(); while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand); + DrainChatCommands(); _bounties?.Tick(); try { _hub?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); } RetryPendingMigration(); PostDataWriteProblems(); + try { PublishHubFeatures(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PublishHubFeatures"); } + try { ShareFellowshipCommands(); } + catch (Exception ex) { Host.Log($"[RynthILT] Fellowship commands to RynthAi failed: {ex.Message}"); } + } + + // ── ILT fellowship commands for RynthAi's Fellowship view (IltFellowship/) ── + + private const long FellowshipShareCheckMs = 2000; + private const long FellowshipShareResendMs = 10_000; + private long _fellowshipShareNextAt; + private long _fellowshipShareSentAt; + // The last payload RynthAi took; empty when nothing was delivered (or after a clear). + private string _fellowshipShareLast = string.Empty; + + /// + /// Plugin tick: sends RynthAi ILT's fellowship commands while ILT is active (an empty list when + /// it isn't), when that changes and every (RynthAi may load + /// later, and drops a list that stops arriving). Nothing on an engine without the broker. + /// + private void ShareFellowshipCommands() + { + if (!Host.HasSendPluginCommand) return; + long now = Environment.TickCount64; + if (now < _fellowshipShareNextAt) return; + _fellowshipShareNextAt = now + FellowshipShareCheckMs; + + bool active = IltActive(); + // Nothing to clear when RynthAi never got a list. + if (!active && _fellowshipShareLast.Length == 0) return; + string payload = IltFellowshipCommands.Payload(active); + if (payload == _fellowshipShareLast && now - _fellowshipShareSentAt < FellowshipShareResendMs) return; + _fellowshipShareSentAt = now; + // Not delivered (RynthAi not installed or not loaded yet): the resend timer tries again. + if (Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, payload)) + _fellowshipShareLast = active ? payload : string.Empty; + } + + /// Clears RynthAi's copy of the fellowship commands (logout) if it has one. + private void ClearSharedFellowshipCommands() + { + if (_fellowshipShareLast.Length == 0) return; + _fellowshipShareLast = string.Empty; + _fellowshipShareNextAt = 0; + try + { + if (Host.HasSendPluginCommand) + Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, IltFellowshipCommands.Payload(active: false)); + } + catch { /* RynthAi drops a list that stops arriving */ } + } + + /// + /// The Hub's world check (RynthCore's verdict once it has one, else RynthILT's server list and + /// "Treat this world as ILT"); before the Hub exists, the engine verdict or the world name + /// (IltFellowshipCommands.IsActive). + /// + private bool IltActive() + { + var hub = _hub; + if (hub != null) return hub.Options.IsIltLikeWorld; + bool? engine = IltEngineVerdict.Active; + string world = engine == null && Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w : string.Empty; + return IltFellowshipCommands.IsActive(engine, world); + } + + // ── RynthCore's Mini Remote sections ───────────────────────────────────── + + /// + /// The broker actions answered on arrival rather than queued for the tick: RynthCore's + /// "servermenu" push (2026.10.5.47+, every 10 s) and the older "iltfeatures" text. + /// + internal static bool IsParsedRemoteAction(string action) => + action.Equals("servermenu", StringComparison.OrdinalIgnoreCase) + || action.Equals("iltfeatures", StringComparison.OrdinalIgnoreCase); + + /// + /// RynthPluginApplyRemoteCommand "servermenu" / "iltfeatures". Any thread. Taken and dropped: + /// the same verdicts, overrides and world names reach the settings model from RynthCore's + /// server list (plugin API v86, PollServerState), which RynthILT reads itself, so the push is + /// only acknowledged (it must not fall through to the ILT verbs). + /// + internal void ApplyRemoteCommand(string action, string value) { } + + /// + /// RynthPluginRenderEmbed: (Session Stats), + /// (Fellowship), (RynthILT's Quests section) or + /// in RynthCore's Mini Remote, drawn into the engine's current + /// window and context (popped-out windows have their own). is the + /// height it used. False until login or for another surface. Render thread. + /// + internal bool RenderEmbedded(string surface, out float wantHeight) + { + wantHeight = 0; + if (!_loginComplete) return false; + Action? body = surface switch + { + SettingsSurface => _settingsUi.RenderBody, + FellowshipSurface => _fellowshipUi.RenderBody, + RatesSurface => RenderRatesSurface, + QuestBonusSurface => RenderQuestBonusSurface, + _ => null, + }; + if (body == null) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + try + { + float startY = ImGui.GetCursorPosY(); + body(); + wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); + return true; + } + catch (Exception ex) + { + Host.Log($"[RynthILT] View {surface} failed: {ex.Message}"); + return false; + } + finally { ImGui.SetCurrentContext(previous); } + } + + /// The ILT session extras (render thread), or a line saying they start with the Hub. + private void RenderRatesSurface() + { + IltHubController? hub = _hub; + if (hub == null) { ImGui.TextDisabled("ILT session rates start once RynthILT's Hub is ready."); return; } + hub.RenderRatesSection(); + } + + /// The /qb list (render thread), or a line saying it starts with the Hub. + private void RenderQuestBonusSurface() + { + IltHubController? hub = _hub; + if (hub == null) { ImGui.TextDisabled("The quest bonus list starts once RynthILT's Hub is ready."); return; } + hub.RenderQuestBonusSection(); + } + + /// + /// 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. + /// + internal string? BuildSectionsJson() => _loginComplete ? SectionsJson : 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}]}"; + + /// Plugin tick: runs the settings and fellowship views' chat commands through the engine. + private void DrainChatCommands() + { + while (_chatCommands.TryDequeue(out string? command)) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + ChatLine("[RynthILT] RynthCore didn't take: " + command); + } + } + + private const long ServerStatePollMs = 2000; + private long _serverStateNextAt; + private string _serverStateJson = string.Empty; + + /// + /// Plugin tick, every 2 s (and at login): RynthCore's server list (plugin API v86, + /// GetServerStateJson) into the settings model, whose "ilt" entry the Hub's world check follows + /// (IltEngineVerdict). Parsed only when the text changed. An older engine leaves it empty, and + /// RynthILT's own list decides. + /// + private void PollServerState(bool force) + { + long now = Environment.TickCount64; + if (!force && now < _serverStateNextAt) return; + _serverStateNextAt = now + ServerStatePollMs; + try + { + if (!Host.HasGetServerStateJson || !Host.TryGetServerStateJson(out string json) || json == _serverStateJson) return; + _serverStateJson = json; + _settingsModel.ApplyServerState(EngineServerState.Parse(json)); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PollServerState"); } + } + + private const long FeaturePublishMs = 1000; + private long _featurePublishNextAt; + + /// + /// Plugin tick, at most once a second: the Hub's server read (world, last check, feature bits) + /// for the ILT settings view (IltSettingsModel.PublishFeatures); cleared while there is no Hub. + /// + private void PublishHubFeatures() + { + long now = Environment.TickCount64; + if (now < _featurePublishNextAt) return; + _featurePublishNextAt = now + FeaturePublishMs; + var hub = _hub; + if (hub == null) + { + _settingsModel.PublishFeatures(null); + return; + } + var options = hub.Options; + DateTime last = options.LastRefreshUtc; + string when = last == default ? string.Empty : last.ToLocalTime().ToString("HH:mm:ss"); + _settingsModel.PublishFeatures(new IltFeatureView(options.WorldName, options.Source ?? string.Empty, when, + options.IsRefreshing, options.IsIltLikeWorld, BuildFeatureRows(options))); + } + + /// + /// The settings view's feature rows: every catalog feature with its state (IltFeatureCatalog), + /// then each ILT charm ("charm:...", on with the world unless refused in chat), then any other + /// bit chat or a probe set that the catalog doesn't show. Pump thread. + /// + private static KeyValuePair[] BuildFeatureRows(IltServerOptions options) + { + bool ilt = options.IsIltLikeWorld; + var rows = new List>(IltFeatureCatalog.All.Length + 32); + var shown = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (IltFeatureInfo f in IltFeatureCatalog.All) + { + rows.Add(new KeyValuePair(f.Key, (int)IltFeatureCatalog.StateOf(f, ilt, options.Get))); + if (f.ServerBit != null) shown.Add(f.ServerBit); + } + foreach (IltCharmDef def in IltInventory.Charms) + { + string key = IltFeature.Charm(def.Name); + rows.Add(new KeyValuePair(key, (int)IltFeatureCatalog.CharmStateOf(ilt, options.Get(key)))); + shown.Add(key); + } + foreach (var bit in options.SnapshotBits()) + if (shown.Add(bit.Key)) rows.Add(bit); + return rows.ToArray(); } /// @@ -151,6 +470,16 @@ public sealed class RynthILTPlugin : RynthPluginBase DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2)); } + // ── ILT settings ───────────────────────────────────────────────────────── + + /// Asks the Hub to read the server's ILT features again (as "/ilt hub refresh", on the next tick). Render thread. + private bool RefreshFeatures() + { + if (!_loginComplete || _hub == null) return false; + _commands.Enqueue(new[] { "/ilt", "hub", "refresh" }); + return true; + } + public override void OnChatWindowText(string? text, int chatType, ref int eat) { if (string.IsNullOrEmpty(text)) return; @@ -201,15 +530,26 @@ public sealed class RynthILTPlugin : RynthPluginBase // ── Rendering (render thread) ──────────────────────────────────────────── - /// The Hub's floating extras (Games HUD, confirmations) in the engine's ImGui frame. + /// + /// The Hub's floating extras (Games HUD, confirmations) and the standalone ILT settings and + /// fellowship windows ("/ilt settings", "/ilt fellow") in the engine's ImGui frame. + /// public override void OnRender() { var hub = _hub; - if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return; + if (!_loginComplete || Host.ImGuiContext == IntPtr.Zero) return; + if (hub == null && !_settingsUi.WindowOpen && !_fellowshipUi.WindowOpen) return; IntPtr previous = ImGui.GetCurrentContext(); ImGui.SetCurrentContext(Host.ImGuiContext); - try { hub.Render(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); } + try + { + try { hub?.Render(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); } + try { _settingsUi.RenderWindow(); } + catch (Exception ex) { Host.Log($"[RynthILT] Settings window failed: {ex.Message}"); _settingsUi.WindowOpen = false; } + try { _fellowshipUi.RenderWindow(); } + catch (Exception ex) { Host.Log($"[RynthILT] Fellowship window failed: {ex.Message}"); _fellowshipUi.WindowOpen = false; } + } finally { ImGui.SetCurrentContext(previous); } } @@ -334,9 +674,28 @@ public sealed class RynthILTPlugin : RynthPluginBase case "hub": case "rates": break; + case "settings": + case "options": + { + // "/ilt settings [show|hide|toggle]": the ILT settings window. + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _settingsUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_settingsUi.WindowOpen }; + return; + } + case "fellow": + case "fellowship": + case "fship": + { + // "/ilt fellow [show|hide|toggle]": the ILT fellowship commands window. + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _fellowshipUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_fellowshipUi.WindowOpen }; + return; + } 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 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]."); return; default: diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj index 0ca55c4..e450edf 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj @@ -38,4 +38,9 @@ + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs index 43c25f2..8bc646e 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs @@ -383,7 +383,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase // 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)) eat = 1; + if (eat == 0 && _vault != null && _vault.ShouldEat(text, chatType)) eat = 1; } private void StartCharacter(long now, uint player, string server, string account, string character) diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs b/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs index bffee66..8eb7c07 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs @@ -4,6 +4,7 @@ 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; @@ -98,12 +99,17 @@ internal sealed class VaultFeed return false; } - /// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread. - public bool ShouldEat(string? text) + /// + /// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread. + /// is the line's eChatTypes (-1 = not known). Server lines only: a line + /// in a player's chat type, or one that doesn't start with the marker (a player's copy has their + /// name in front), is left alone, so nobody can feed the vault view or hide chat by typing "~ael1". + /// + public bool ShouldEat(string? text, int chatType = -1) { - if (string.IsNullOrEmpty(text)) return false; - int at = text.IndexOf(Prefix, StringComparison.Ordinal); - if (at >= 0) + if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false; + int at = ChatSource.ContentStart(text); + if (ChatSource.StartsWithMarker(text, Prefix)) { // Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it. if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false; @@ -111,8 +117,7 @@ internal sealed class VaultFeed return true; } // The reply of a server that has no such command: swallowed only while we wait for one. - if (_expecting && text.IndexOf("Unknown command", StringComparison.OrdinalIgnoreCase) >= 0 - && text.IndexOf("mule-data", StringComparison.OrdinalIgnoreCase) >= 0) + if (_expecting && IsUnknownCommandReply(text)) { _lines.Enqueue(UnknownMarker); return true; @@ -120,6 +125,15 @@ internal sealed class VaultFeed return false; } + /// ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed). + private static bool IsUnknownCommandReply(string text) + { + const string marker = "Unknown command:"; + if (!ChatSource.StartsWithMarker(text, marker, StringComparison.OrdinalIgnoreCase)) return false; + string named = text.Substring(ChatSource.ContentStart(text) + marker.Length).Trim().TrimStart('/', '@'); + return string.Equals(named, "mule-data", StringComparison.OrdinalIgnoreCase); + } + /// Applies what arrived and decides what to send next. Plugin tick. public void Tick(long nowMs, string account) { diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj b/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj new file mode 100644 index 0000000..7cba983 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthLeafDawn + 0.1.0 + leafdawn + LeafDawn + leafdawn.hopto.org + LeafDawn + LeafDawn only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs new file mode 100644 index 0000000..78e22f2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs @@ -0,0 +1,22 @@ +// ServerData.cs - What is known about LeafDawn (RynthLeafDawn). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE Server thats goal is to mimic end of game retail. With some custom content", + Facts = new[] + { + "End-of-retail with some custom content.", + "Not the same server as Leafdawning.", + }, + Discord = "https://discord.gg/c2QUBPwPZF", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj b/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj new file mode 100644 index 0000000..33d6188 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthLeafdawning + 0.1.0 + leafdawning + Leafdawning + leafdawning.duckdns.org + Leafdawning + Leafdawning only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs new file mode 100644 index 0000000..7114a19 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Leafdawning (RynthLeafdawning). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A standard, no-frills PvE end-of-retail ACE Asheron's Call server. Runs on dedicated hardware with the ability " + + "to host a large number of players. Enforced 3 account limit.", + Facts = new[] + { + "Standard, no-frills end-of-retail.", + "Not the same server as LeafDawn.", + }, + AccountLimit = "3 accounts (enforced)", + Discord = "https://discord.gg/sQpDgAzSXB", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs index 00be58c..8215289 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs @@ -450,6 +450,30 @@ function waitfor(cond, timeout) end return true end + +-- Lua 5.2+ gives %s any value through tostring (nil -> ""nil""); MoonSharp throws +-- ""bad argument #n to 'format' (string expected, got nil)"" instead, which stops +-- scripts written for standard Lua (a missing chat field, an unset setting). +do + local rawformat = string.format + local unpack = table.unpack or unpack + string.format = function(fmt, ...) + local n = select('#', ...) + if n == 0 or type(fmt) ~= 'string' then return rawformat(fmt, ...) end + local args = { ... } + local i = 0 + for conv in fmt:gmatch('%%[-+ #0]*%d*%.?%d*(.)') do + if conv ~= '%' then + i = i + 1 + local v = args[i] + if conv == 's' and i <= n and type(v) ~= 'string' and type(v) ~= 'number' then + args[i] = tostring(v) + end + end + end + return rawformat(fmt, unpack(args, 1, n)) + end +end ", null, "rynth-core"); } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestBook.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestBook.cs new file mode 100644 index 0000000..d1d182e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestBook.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// One character's quest notes: the quests tracked in the Quest Timers window and the rewards +/// recorded per quest (UtilityBelt ILT's quest_rewards.json, kept by RynthOracle now). Lives in +/// %APPDATA%\RynthCore\RynthOracle\characters\<world>\<character>.json, written by hand and +/// read with JsonDocument (no reflection serializer: it roots plugin types across hot reloads). +/// +/// The first time a character has no file, an existing UtilityBelt quest_rewards.json for the +/// same world and character is imported once (Documents\Decal Plugins\UtilityBelt\<world>\<character>). +/// Pump thread only. +/// +internal sealed class QuestBook +{ + public const int SchemaVersion = 1; + + private readonly List _tracked = new(); + private readonly HashSet _trackedSet = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _rewards = new(StringComparer.OrdinalIgnoreCase); + + /// The character the book belongs to ("" = none loaded: changes are not saved). + public string Character { get; private set; } = ""; + public string World { get; private set; } = ""; + /// Bumps on every change (views rebuild their caches on it). + public int Revision { get; private set; } + /// What happened at load ("imported 4 rewards from UtilityBelt"), shown once in chat; "" = nothing to say. + public string LoadNote { get; private set; } = ""; + + /// Overrides the folder (tests). + internal string? RootOverride { get; set; } + /// Overrides UtilityBelt's folder (tests); "" turns the import off. + internal string? UbRootOverride { get; set; } + + public bool Loaded => Character.Length > 0; + public IReadOnlyList Tracked => _tracked; + public int RewardCount => _rewards.Count; + + public bool IsTracked(string flag) => _trackedSet.Contains(flag); + + public bool TryGetReward(string flag, out QuestReward reward) => _rewards.TryGetValue(flag, out reward!); + + /// The recorded rewards' compact text, or "". + public string RewardText(string flag) => _rewards.TryGetValue(flag, out QuestReward? r) ? r.ShortSummary() : ""; + + private string Root => RootOverride ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "characters"); + + private string UbRoot => UbRootOverride ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt"); + + /// The file for a world and character (names made safe for a path). + public string PathFor(string world, string character) => + Path.Combine(Root, SafeName(world.Length > 0 ? world : "default"), SafeName(character) + ".json"); + + /// Loads (or starts) the book for a character; a no-op when it is already loaded. + public void Load(string world, string character) + { + world ??= ""; + character = (character ?? "").Trim(); + if (character.Length == 0) return; + if (string.Equals(character, Character, StringComparison.Ordinal) && string.Equals(world, World, StringComparison.Ordinal)) return; + + ResetData(); + Character = character; + World = world; + LoadNote = ""; + string file = PathFor(world, character); + try + { + if (File.Exists(file)) Read(File.ReadAllText(file)); + else if (ImportUb(world, character) is int n and > 0) + { + LoadNote = $"Imported {n} quest reward{(n == 1 ? "" : "s")} from UtilityBelt."; + Save(); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + // A broken file means an empty book; the next change rewrites it. + LoadNote = "Couldn't read the saved quest notes (" + ex.GetType().Name + "); starting empty."; + } + Revision++; + } + + /// Forgets the character (logout). Changes were saved as they were made. + public void Clear() + { + ResetData(); + Character = ""; + World = ""; + LoadNote = ""; + Revision++; + } + + private void ResetData() + { + _tracked.Clear(); + _trackedSet.Clear(); + _rewards.Clear(); + } + + /// Tracks or untracks a quest; returns the new state. Saved at once. + public bool SetTracked(string flag, bool tracked) + { + if (string.IsNullOrWhiteSpace(flag)) return false; + if (tracked == _trackedSet.Contains(flag)) return tracked; + if (tracked) + { + _trackedSet.Add(flag); + _tracked.Add(flag); + } + else + { + _trackedSet.Remove(flag); + _tracked.RemoveAll(f => string.Equals(f, flag, StringComparison.OrdinalIgnoreCase)); + } + Revision++; + Save(); + return tracked; + } + + public bool ToggleTracked(string flag) => SetTracked(flag, !IsTracked(flag)); + + /// Stores a quest's rewards (an empty entry removes them). Saved at once. + public void SetReward(string flag, QuestReward? reward) + { + if (string.IsNullOrWhiteSpace(flag)) return; + if (reward == null || reward.IsEmpty) _rewards.Remove(flag); + else _rewards[flag] = reward.Clone(); + Revision++; + Save(); + } + + /// Writes the book (atomic replace). Does nothing with no character loaded. + public void Save() + { + if (!Loaded) return; + try + { + string file = PathFor(World, Character); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + string tmp = file + ".tmp"; + File.WriteAllText(tmp, ToJson(), new UTF8Encoding(false)); + File.Move(tmp, file, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Notes are a convenience; a failed write keeps the old file. + } + } + + /// The book as JSON (plain ASCII: anything else is escaped). + internal string ToJson() + { + var sb = new StringBuilder(1024); + sb.Append("{\n"); + sb.Append(" \"schemaVersion\": ").Append(SchemaVersion.ToString(CultureInfo.InvariantCulture)).Append(",\n"); + sb.Append(" \"character\": ").Append(Q(Character)).Append(",\n"); + sb.Append(" \"world\": ").Append(Q(World)).Append(",\n"); + sb.Append(" \"savedAtUtc\": ").Append(Q(DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture))).Append(",\n"); + sb.Append(" \"tracked\": ["); + for (int i = 0; i < _tracked.Count; i++) + sb.Append(i > 0 ? ", " : "").Append(Q(_tracked[i])); + sb.Append("],\n"); + sb.Append(" \"rewards\": {"); + bool first = true; + var keys = new List(_rewards.Keys); + keys.Sort(StringComparer.OrdinalIgnoreCase); + foreach (string key in keys) + { + QuestReward r = _rewards[key]; + sb.Append(first ? "\n" : ",\n"); + first = false; + sb.Append(" ").Append(Q(key)).Append(": {"); + sb.Append("\"xpPercent\": ").Append(r.XpPercent.ToString("R", CultureInfo.InvariantCulture)); + sb.Append(", \"lumPercent\": ").Append(r.LumPercent.ToString("R", CultureInfo.InvariantCulture)); + sb.Append(", \"recordedLevel\": ").Append(r.RecordedLevel.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"coins\": ").Append(r.Coins.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"trinkets\": ").Append(r.Trinkets.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"medallions\": ").Append(r.Medallions.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"yellowPowder\": ").Append(r.YellowPowder.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"redPowder\": ").Append(r.RedPowder.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"bluePowder\": ").Append(r.BluePowder.ToString(CultureInfo.InvariantCulture)); + sb.Append(", \"mmd\": ").Append(r.Mmd.ToString(CultureInfo.InvariantCulture)); + sb.Append('}'); + } + sb.Append(first ? "}\n" : "\n }\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// Reads a saved book (RynthOracle's own lower-case keys, or UB's upper-case ones). + internal void Read(string json) + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return; + if (Prop(root, "tracked", out JsonElement tracked) && tracked.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement t in tracked.EnumerateArray()) + { + string flag = t.ValueKind == JsonValueKind.String ? (t.GetString() ?? "").Trim() : ""; + if (flag.Length > 0 && _trackedSet.Add(flag)) _tracked.Add(flag); + } + } + ReadRewards(root); + } + + /// The "rewards" / "Rewards" object: flag -> entry. Returns how many were kept. + private int ReadRewards(JsonElement root) + { + if (!Prop(root, "rewards", out JsonElement rewards) || rewards.ValueKind != JsonValueKind.Object) return 0; + int n = 0; + foreach (JsonProperty p in rewards.EnumerateObject()) + { + if (p.Value.ValueKind != JsonValueKind.Object || p.Name.Trim().Length == 0) continue; + JsonElement e = p.Value; + var r = new QuestReward + { + XpPercent = Math.Clamp(Dbl(e, "xpPercent"), 0, QuestReward.MaxPercent), + LumPercent = Math.Clamp(Dbl(e, "lumPercent"), 0, QuestReward.MaxPercent), + RecordedLevel = Int(e, "recordedLevel"), + Coins = Int(e, "coins"), + Trinkets = Int(e, "trinkets"), + Medallions = Int(e, "medallions"), + YellowPowder = Int(e, "yellowPowder"), + RedPowder = Int(e, "redPowder"), + BluePowder = Int(e, "bluePowder"), + Mmd = Int(e, "mmd"), + }; + if (r.IsEmpty) continue; + _rewards[p.Name.Trim()] = r; + n++; + } + return n; + } + + /// UtilityBelt ILT's quest_rewards.json for this world and character, if there is one. Returns the entries kept. + private int ImportUb(string world, string character) + { + string ubRoot = UbRoot; + if (ubRoot.Length == 0 || world.Length == 0) return 0; + // UB names the server folder after the world with its spaces removed ("InfiniteLeaftide"). + foreach (string w in new[] { world, world.Replace(" ", "") }) + { + string file = Path.Combine(ubRoot, SafeName(w), SafeName(character), "quest_rewards.json"); + if (!File.Exists(file)) continue; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(file)); + return doc.RootElement.ValueKind == JsonValueKind.Object ? ReadRewards(doc.RootElement) : 0; + } + return 0; + } + + // ── JSON helpers (keys matched without regard to case: UB writes "XpPercent") ────────────── + + private static bool Prop(JsonElement o, string name, out JsonElement value) + { + foreach (JsonProperty p in o.EnumerateObject()) + { + if (!string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) continue; + value = p.Value; + return true; + } + value = default; + return false; + } + + private static double Dbl(JsonElement o, string name) => + Prop(o, name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) && double.IsFinite(d) ? d : 0; + + private static int Int(JsonElement o, string name) + { + if (!Prop(o, name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0; + if (v.TryGetInt64(out long l)) return (int)Math.Clamp(l, 0, int.MaxValue); + return v.TryGetDouble(out double d) && double.IsFinite(d) ? (int)Math.Clamp(d, 0, int.MaxValue) : 0; + } + + /// A JSON string literal, ASCII only. + private static string Q(string s) + { + var sb = new StringBuilder(s.Length + 2); + sb.Append('"'); + 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.Append('"').ToString(); + } + + /// A name safe as one path segment (invalid characters become '_'). + internal static string SafeName(string name) + { + var sb = new StringBuilder(name.Length); + char[] bad = Path.GetInvalidFileNameChars(); + foreach (char c in name.Trim()) sb.Append(Array.IndexOf(bad, c) >= 0 ? '_' : c); + string s = sb.ToString().Trim('.', ' '); + return s.Length > 0 ? s : "_"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs index 4709d03..4323190 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs @@ -34,6 +34,9 @@ internal sealed class Quest /// The Name column: the curated name, else the one-line info, else "Unknown quest" (upstream's rule). public string DisplayName => Name.Length > 0 ? Name : Info.Length > 0 ? Info : "Unknown quest"; + /// The list label: the display name, or for a flag no list knows "(new)" and its description or flag. + public string Label => IsNew ? "(new) " + (Name.Length > 0 ? Name : Flag) : DisplayName; + /// The server is the source of truth where it has spoken (the flag's timer); else the lists. public bool IsRepeatable(QuestFlagStore flags) => flags.TryGet(Flag, out QuestFlag q) ? q.RepeatTime != TimeSpan.Zero : Repeatable; diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestRewards.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestRewards.cs new file mode 100644 index 0000000..31477f6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestRewards.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// What one quest pays this character, as the player recorded it (UtilityBelt ILT's +/// QuestRewardEntry, Lib/Quests/QuestRewardsFile.cs). XP and luminance are percentages of a +/// level's worth, so they are kept with the level they were noted at. +/// +internal sealed class QuestReward +{ + /// The largest percentage accepted (UB's clamp). + public const double MaxPercent = 1000; + + public double XpPercent; + public double LumPercent; + /// The character level the percentages were noted at; 0 = not recorded. + public int RecordedLevel; + public int Coins; + public int Trinkets; + public int Medallions; + public int YellowPowder; + public int RedPowder; + public int BluePowder; + public int Mmd; + + /// Nothing recorded (an empty entry is dropped instead of saved). + public bool IsEmpty => + XpPercent <= 0 && LumPercent <= 0 && Coins <= 0 && Trinkets <= 0 && Medallions <= 0 + && YellowPowder <= 0 && RedPowder <= 0 && BluePowder <= 0 && Mmd <= 0; + + public QuestReward Clone() => (QuestReward)MemberwiseClone(); + + /// + /// The compact column text, UB's format: "1.5%XP 2%Lum 3C 1T 2M 1Y 1R 1B 2D L275". Zero fields + /// are left out; " L<level>" follows when XP or luminance is set and the level is known. + /// + public string ShortSummary() + { + var parts = new List(10); + if (XpPercent > 0) parts.Add(Percent(XpPercent) + "%XP"); + if (LumPercent > 0) parts.Add(Percent(LumPercent) + "%Lum"); + if (Coins > 0) parts.Add(Coins.ToString(CultureInfo.InvariantCulture) + "C"); + if (Trinkets > 0) parts.Add(Trinkets.ToString(CultureInfo.InvariantCulture) + "T"); + if (Medallions > 0) parts.Add(Medallions.ToString(CultureInfo.InvariantCulture) + "M"); + if (YellowPowder > 0) parts.Add(YellowPowder.ToString(CultureInfo.InvariantCulture) + "Y"); + if (RedPowder > 0) parts.Add(RedPowder.ToString(CultureInfo.InvariantCulture) + "R"); + if (BluePowder > 0) parts.Add(BluePowder.ToString(CultureInfo.InvariantCulture) + "B"); + if (Mmd > 0) parts.Add(Mmd.ToString(CultureInfo.InvariantCulture) + "D"); + if ((XpPercent > 0 || LumPercent > 0) && RecordedLevel > 0) parts.Add("L" + RecordedLevel.ToString(CultureInfo.InvariantCulture)); + return string.Join(" ", parts); + } + + /// The long form for tooltips and chat: "1.5% XP, 2% luminance (at level 275), 3 coins, ...". + public string LongSummary() + { + var parts = new List(10); + if (XpPercent > 0) parts.Add(Percent(XpPercent) + "% XP"); + if (LumPercent > 0) parts.Add(Percent(LumPercent) + "% luminance"); + if ((XpPercent > 0 || LumPercent > 0) && RecordedLevel > 0) parts[parts.Count - 1] += $" (at level {RecordedLevel})"; + Add(parts, Coins, "coin"); + Add(parts, Trinkets, "trinket"); + Add(parts, Medallions, "medallion"); + Add(parts, YellowPowder, "yellow powder"); + Add(parts, RedPowder, "red powder"); + Add(parts, BluePowder, "blue powder"); + Add(parts, Mmd, "MMD"); + return parts.Count == 0 ? "no rewards recorded" : string.Join(", ", parts); + + static void Add(List list, int n, string what) + { + if (n <= 0) return; + bool noPlural = what.EndsWith("powder", StringComparison.Ordinal) || what == "MMD"; + list.Add($"{n} {what}{(n == 1 || noPlural ? "" : "s")}"); + } + } + + /// UB's percent format: one decimal from 10 up, two from 1 up, three below 1. + public static string Percent(double v) => + v.ToString(v >= 10 ? "0.#" : v >= 1 ? "0.##" : "0.###", CultureInfo.InvariantCulture); + + /// A typed percentage ("1.5", "1,5", "2%"); blank = 0. Clamped to 0... False when it isn't a number. + public static bool TryParsePercent(string? text, out double value) + { + value = 0; + string t = (text ?? "").Trim().TrimEnd('%').Trim().Replace(',', '.'); + if (t.Length == 0) return true; + if (!double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) || !double.IsFinite(v)) return false; + value = Math.Clamp(v, 0, MaxPercent); + return true; + } + + /// A typed count; blank = 0, negatives become 0. False when it isn't a whole number. + public static bool TryParseCount(string? text, out int value) + { + value = 0; + string t = (text ?? "").Trim().Replace(",", ""); + if (t.Length == 0) return true; + if (!long.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out long v)) return false; + value = (int)Math.Clamp(v, 0, int.MaxValue); + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimer.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimer.cs new file mode 100644 index 0000000..97a08d0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestTimer.cs @@ -0,0 +1,94 @@ +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// How a quest stands right now, for the timer columns and the Quest Timers window. +internal enum QuestTimerState +{ + /// Can be done now (never done, or the timer ran out). + Ready, + /// Waiting on its repeat timer. + Waiting, + /// A kill task still collecting kills. + InProgress, + /// Done for good: a one-time quest, a solve limit reached, or a finished kill task with no timer. + Done, +} + +/// +/// Quest timer text shared by the Quests tab and the Quest Timers window. Kill tasks follow +/// UtilityBelt ILT's rule (QuestTracker.GetKTStatusText): "N left" while counting, then the reset +/// countdown, then "done". Kill-task flags are recognised by name as RynthAi's tracker did. +/// +internal static class QuestTimer +{ + // RynthAi's / UtilityBelt's kill-task pattern (counter flags), with a solve limit set. + private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// A kill-task counter flag (its name says so and it has a solve limit). + public static bool IsKillTask(QuestFlag f) => f.MaxSolves > 0 && KillTaskRegex.IsMatch(f.Key); + + /// A quest's state; is what the column shows. + public static QuestTimerState State(Quest q, QuestFlagStore flags, DateTime utcNow, out string text) + { + if (!flags.TryGet(q.Flag, out QuestFlag f)) + { + text = "ready"; + return QuestTimerState.Ready; + } + return State(f, q.IsRepeatable(flags), utcNow, out text); + } + + /// A held flag's state (: the quest can be done again at all). + public static QuestTimerState State(QuestFlag f, bool repeatable, DateTime utcNow, out string text) + { + TimeSpan left = f.NextAvailableTime(utcNow); + if (IsKillTask(f)) + { + if (f.Solves < f.MaxSolves) + { + text = $"{f.MaxSolves - f.Solves} left"; + return QuestTimerState.InProgress; + } + if (f.RepeatTime > TimeSpan.Zero && left > TimeSpan.Zero) + { + text = TimeText.Friendly(left); + return QuestTimerState.Waiting; + } + text = "done"; + return QuestTimerState.Done; + } + if (!repeatable) + { + text = "completed"; + return QuestTimerState.Done; + } + if (f.AtSolveLimit) + { + text = "maxed"; + return QuestTimerState.Done; + } + if (left > TimeSpan.Zero) + { + text = TimeText.Friendly(left); + return QuestTimerState.Waiting; + } + text = "ready"; + return QuestTimerState.Ready; + } + + /// Sort key: ready first, then by time left, then kill tasks in progress, then done. + public static double SortKey(Quest q, QuestFlagStore flags, DateTime utcNow) + { + QuestTimerState s = State(q, flags, utcNow, out _); + return s switch + { + QuestTimerState.Ready => 0, + QuestTimerState.Waiting when flags.TryGet(q.Flag, out QuestFlag f) => 1 + Math.Max(0, f.NextAvailableTime(utcNow).TotalSeconds), + QuestTimerState.InProgress => 1e12, + _ => 2e12, + }; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs index 6ce90ea..050a628 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs @@ -1,4 +1,5 @@ using System; +using RynthCore.Plugin.Shared; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthOracle.Data; @@ -20,6 +21,8 @@ internal static class ServerTags /// only load or show where says so; untagged (retail) ones work anywhere. /// /// Sources, best first: +/// 0. Engine API v86 GetServerStateJson (ServerStateClient): RynthCore's active server, with +/// this character's overrides and the Diagnostics page's server pick applied (FromEngine). /// 1. Engine API v75 GetServerInfo: the engine's own verdict for Aelrynth (connect host, /// announced world name, Bank mod properties) and the world name the server announced /// at login. Never the launcher profile name. @@ -28,7 +31,8 @@ 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). +/// (Decal's CharacterFilter.Server). Infinite Leaftide has no RynthOracle pages: its screens are +/// RynthILT's, so RynthCore's "ilt" server gives no tag here. /// internal sealed class ServerIdentity { @@ -51,8 +55,20 @@ internal sealed class ServerIdentity Set("", "", "not logged in"); } - public void Refresh(RynthCoreHost host, uint playerId) + /// + /// 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) { + if (engine != null) + { + string fallbackWorld = host.TryGetWorldName(out string fw) ? fw.Trim() : ""; + FromEngine(engine, fallbackWorld, out string t, out string wn, out string src); + Set(t, wn, src); + return; + } + string tag, world, source; if (host.TryGetServerInfo(out bool aelrynth, out bool staging, out string announced)) { @@ -85,6 +101,59 @@ internal sealed class ServerIdentity Set(tag, world, source); } + /// + /// The identity from RynthCore's server list. An active server decides the tag (its own, or "" + /// for a server RynthOracle has nothing for). With none active, the world name may still tag a + /// server the engine doesn't know (Conquest without RynthConquest loaded), but never one the + /// engine lists: that one is off on purpose (not detected, or this character's override). + /// Pure: the tests drive it. + /// + internal static void FromEngine(EngineServerState engine, string fallbackWorld, out string tag, out string world, out string source) + { + world = engine.World.Length > 0 ? engine.World : (fallbackWorld ?? "").Trim(); + if (engine.HasActive) + { + tag = TagForEngineId(engine.Active); + EngineServer? s = engine.Find(engine.Active); + string how = engine.Picked ? "picked by hand" + : s != null && s.Force.Equals("on", StringComparison.OrdinalIgnoreCase) ? "forced on for this character" + : s != null && s.Reason.Length > 0 ? s.Reason : "detected"; + string name = engine.ActiveName.Length > 0 ? engine.ActiveName : engine.Active; + source = $"RynthCore: {name} ({how})" + (tag.Length == 0 ? " - no RynthOracle pages for it" : ""); + return; + } + + tag = TagForWorld(world); + string id = EngineIdForTag(tag); + if (tag.Length > 0 && id.Length > 0 && engine.Find(id) != null) + { + source = $"RynthCore: {tag} is off for this world (not detected, or overridden)"; + tag = ""; + return; + } + source = tag.Length > 0 + ? $"world name \"{world}\" (RynthCore has no {tag} server loaded)" + : "RynthCore: no server active (retail features only)"; + } + + /// The tag for a RynthCore server id; "" for servers without RynthOracle features. + public static string TagForEngineId(string? id) => (id ?? "").Trim().ToLowerInvariant() switch + { + EngineServerState.AelrynthId => ServerTags.Aelrynth, + "conquest" => ServerTags.Conquest, + "levistras" => ServerTags.Levistras, + _ => "", + }; + + /// The RynthCore server id for a tag; "" for none. + public static string EngineIdForTag(string? tag) => tag switch + { + ServerTags.Aelrynth => EngineServerState.AelrynthId, + ServerTags.Conquest => "conquest", + ServerTags.Levistras => "levistras", + _ => "", + }; + /// The tag for a world name; "" for servers without their own features. public static string TagForWorld(string? world) { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs index 2e71218..bc841aa 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs @@ -13,10 +13,19 @@ internal sealed class OracleContext public readonly QuestFlagStore Flags = new(); public readonly QuestCatalog Catalog = new(); public readonly QuestCatalogUpdater Updater = new(); + /// This character's tracked quests and recorded rewards (loaded once the name is known). + public readonly QuestBook Book = new(); public readonly CharacterSnapshot Character = new(); public readonly VoidTracker Void = new(); public readonly FellowshipTracker Fellowship = new(); public readonly ServerIdentity Server = new(); + /// 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. + public RynthCore.Plugin.Shared.SessionStatsV1 Session; + 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. @@ -39,6 +48,14 @@ internal sealed class OracleContext /// Set by the plugin: sends a chat command to the server as if typed (the views' buttons). public Func Send = _ => false; + /// 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: shows or hides the Quest Timers window. + public Action SetQuestTimersWindow = _ => { }; + /// Set by the plugin: whether the Quest Timers window is showing. + public Func QuestTimersWindowVisible = () => false; + public Func Props => id => Character.Int(Host, id); /// A line in the player's chat window only (nothing is sent to the server). diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs index 7fbf579..68df70f 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs @@ -23,6 +23,8 @@ internal sealed class OracleSettings /// Show the Void target window by itself for characters with Void Magic. public bool AutoShowVoidWindow = true; public bool MainWindowOpen; + /// The Quest Timers window (tracked quests) was left open; it opens again at login. + 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). @@ -44,6 +46,7 @@ internal sealed class OracleSettings 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); if (r.TryGetProperty("tabName", out JsonElement t) && t.ValueKind == JsonValueKind.String) TabName = t.GetString() ?? TabName; if (r.TryGetProperty("lastQuestListCheck", out JsonElement c) && c.ValueKind == JsonValueKind.String @@ -68,6 +71,7 @@ internal sealed class OracleSettings sb.Append(" \"lastQuestListCheck\": \"").Append(LastQuestListCheckUtc.ToString("o", CultureInfo.InvariantCulture)).Append("\",\n"); 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(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append("\"\n"); sb.Append("}\n"); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs index 939ef74..d3c9231 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs @@ -37,7 +37,8 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] public static IntPtr GetVersion() { - try { return LiteralPointer("0.2.0"u8); } + // Keep in step with RynthOraclePlugin.Version (a u8 literal can't be built from a const string). + try { return LiteralPointer("0.2.1"u8); } catch { return IntPtr.Zero; } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj index de4ae2a..b3fbe8b 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj @@ -52,6 +52,15 @@ + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs index e6fb329..1cd8e30 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs @@ -18,24 +18,33 @@ namespace RynthCore.Plugin.RynthOracle; ///
public sealed class RynthOraclePlugin : RynthPluginBase { - public const string Version = "0.2.0"; + // Previous release: 0.2.0. + public const string Version = "0.2.1"; private const long QuestReadDelayMs = 6000; // after login, before the hidden /myquests private const long CharacterReadMs = 1000; + // The Character tab's session (RynthAi): read only while that tab is on screen. + private const long CharacterExtrasReadMs = 2000; + private const long BookWorldWaitMs = 15_000; // how long the quest book waits for the world name private readonly OracleContext _c = new(); private readonly UiHost _ui = new(); - private UiWindow? _main, _void; + private UiWindow? _main, _void, _timers; private OracleView? _mainView; private VoidView? _voidView; + private QuestTimersView? _timersView; + private int _seenBookRevision = -1; private readonly ConcurrentQueue _commands = new(); private long _questReadAtMs = -1; private long _loginMs; private long _nextCharacterReadMs; + private long _nextCharacterExtrasMs; private bool _voidAutoDecided; private bool _dailyCheckStarted; private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -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; @@ -49,13 +58,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Settings.Load(); _c.RequestQuests = RequestQuests; _c.Send = cmd => _c.InWorld && Host.InvokeChatParser(cmd); + _c.RunCommand = cmd => _c.InWorld && Host.InvokeChatParser(cmd); _ui.Log = msg => Host.Log(msg); _mainView = new OracleView(_c); _voidView = new VoidView(_c); + _timersView = new QuestTimersView(_c); _main = _ui.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { - DefaultWidth = 620f, DefaultHeight = 560f, MinWidth = 420f, MinHeight = 260f, + DefaultWidth = 700f, DefaultHeight = 600f, MinWidth = 420f, MinHeight = 260f, }); // The Void window is opened from the Oracle window: no bar button (and no Scripts menu // line, which would bring back the Scripts button just for it). @@ -66,11 +77,34 @@ public sealed class RynthOraclePlugin : RynthPluginBase }); _mainView.SetVoidWindow = v => { if (_void != null) { _void.Visible = v; _void.NeedsPass = true; } }; _mainView.VoidWindowVisible = () => _void?.Visible ?? false; + // The Quest Timers window (tracked quests): opened from the Quests tab, /ro timers or the + // engine's Character menu; like the Void window it has no bar button of its own. + _timers = _ui.Add(new UiWindow("RynthOracle/QuestTimers", "Quest Timers") + { + DefaultWidth = 310f, DefaultHeight = 220f, MinWidth = 220f, MinHeight = 90f, + ShowInBar = false, + }); + _c.SetQuestTimersWindow = SetQuestTimers; + _c.QuestTimersWindowVisible = () => _timers?.Visible ?? false; Host.Log($"[RynthOracle] {Version} initialized. /ro opens the window. Based on Oracle of Dereth by Advis Eveldan - thank you!"); return 0; } + /// Shows or hides the Quest Timers window and remembers the choice for the next login. + private void SetQuestTimers(bool visible) + { + if (_timers == null) return; + _timers.Visible = visible; + _timers.NeedsPass = true; + if (_c.Settings.QuestTimersOpen != visible) + { + _c.Settings.QuestTimersOpen = visible; + _c.Settings.Save(); + } + if (_main != null) _main.NeedsPass = true; + } + // The engine calls this on a real login and on a freshly (re)loaded plugin already in game. public override void OnLoginComplete() { @@ -78,7 +112,10 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Flags.Clear(); _c.Void.Clear(); _c.Server.Reset(); - _c.Server.Refresh(Host, Host.GetPlayerId()); + _c.ServerState.Clear(); + _c.ServerState.Poll(Host, Environment.TickCount64, force: true); + _seenServerStateRevision = _c.ServerState.Revision; + _c.Server.Refresh(Host, Host.GetPlayerId(), _c.ServerState.State); _catalogTag = null; ApplyServer(); _conquestLoginRead = false; @@ -90,10 +127,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase _loginMs = now; _questReadAtMs = _c.Settings.ReadQuestsAtLogin ? now + QuestReadDelayMs : -1; _nextCharacterReadMs = now; + _nextCharacterExtrasMs = now; + ClearCharacterExtras(); _voidAutoDecided = false; _dailyCheckStarted = false; if (_main != null) { _main.Visible = _c.Settings.MainWindowOpen; _main.NeedsPass = true; } if (_void != null) { _void.Visible = false; _void.NeedsPass = true; } + // The quest book loads once the character's name (and world) are known (TickData). + _c.Book.Clear(); + if (_timers != null) { _timers.Visible = _c.Settings.QuestTimersOpen; _timers.NeedsPass = true; } } public override void OnLogout() @@ -103,14 +145,51 @@ public sealed class RynthOraclePlugin : RynthPluginBase // Closed for character select (the saved "left open" choice is kept for the next login). if (_main != null) { _main.Visible = false; _main.NeedsPass = true; } if (_void != null) { _void.Visible = false; _void.NeedsPass = true; } + if (_timers != null) { _timers.Visible = false; _timers.NeedsPass = true; } _ui.SubmitEmpty(Host); + _c.Book.Clear(); // saved as it changed _c.Flags.Clear(); _c.Void.Clear(); _c.Conquest.Clear(); _c.Boards.Clear(); _c.Server.Reset(); + _c.ServerState.Clear(); _c.TitlesKnown = false; _c.EarnedTitles.Clear(); + ClearCharacterExtras(); + } + + /// Forgets the Character tab's session (login, logout): the next character's comes fresh. + private void ClearCharacterExtras() + { + _c.Session = default; + _c.SessionKnown = false; + _c.AiSession.Reset(); + } + + /// + /// While the Character tab is on screen: RynthAi's session, every . + /// Nothing is read with the window closed or on another tab. + /// + private void ReadCharacterExtras(long now) + { + if (_main == null || _mainView == null || !_main.Visible || _mainView.Tab != OracleView.TabCharacter) return; + if (now < _nextCharacterExtrasMs) return; + _nextCharacterExtrasMs = now + CharacterExtrasReadMs; + + 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; + _c.SessionKnown = known; + _c.Session = known ? s : default; + } + + /// 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 } /// @@ -215,10 +294,27 @@ public sealed class RynthOraclePlugin : RynthPluginBase case "void": if (_void != null) { _void.Visible = !_void.Visible; _void.NeedsPass = true; } break; + case "timers": + case "timer": + if (_timers != null) SetQuestTimers(!_timers.Visible); + break; case "quests": case "refresh": RequestQuests(); break; + case "fellowship": + case "fellow": + case "fship": + // The main window on its Fellowship tab (RynthCore's Char menu and RynthAi's Mini Remote use this). + ShowTab(OracleView.TabFellowship); + 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). + // RynthAi, RynthILT and RynthCore's menus link here; it shows, never toggles off. + ShowTab(OracleView.TabCharacter); + break; case "status": string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : ""; string titles = _c.TitlesKnown ? $", {_c.EarnedTitles.Count} titles held" : ""; @@ -226,13 +322,18 @@ 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). _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 void (Void window), /ro quests (read quest flags), /ro status, /ro about"); + _c.Print("Commands: /ro (window), /ro character (Character tab: status, session), /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)"); break; } - if (arg is "" or "void" && !Host.HasUi && !_noUiLogged) + if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" + or "about" && !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."); @@ -270,6 +371,13 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Settings.MainWindowOpen = _main.Visible; _c.Settings.Save(); } + // The same for the Quest Timers window (closed with its X or opened from the engine's menu). + if (_c.InWorld && _timers != null && _timers.Visible != _c.Settings.QuestTimersOpen) + { + _c.Settings.QuestTimersOpen = _timers.Visible; + _c.Settings.Save(); + if (_main != null) _main.NeedsPass = true; + } } private void TickData(long now) @@ -280,11 +388,19 @@ public sealed class RynthOraclePlugin : RynthPluginBase _seenFlagRevision = _c.Flags.Revision; _c.Catalog.SyncDiscoveries(_c.Flags); if (_main != null) _main.NeedsPass = true; + if (_timers != null) _timers.NeedsPass = true; } if (_c.Catalog.Revision != _seenCatalogRevision) { _seenCatalogRevision = _c.Catalog.Revision; if (_main != null) _main.NeedsPass = true; + if (_timers != null) _timers.NeedsPass = true; + } + if (_c.Book.Revision != _seenBookRevision) + { + _seenBookRevision = _c.Book.Revision; + if (_main != null) _main.NeedsPass = true; + if (_timers != null) _timers.NeedsPass = true; } string? result = _c.Updater.TakeResult(out bool updated); @@ -302,6 +418,18 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (!_c.InWorld) return; + ReadCharacterExtras(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); + ApplyServer(); + if (_main != null) _main.NeedsPass = true; + } + if (_questReadAtMs >= 0 && now >= _questReadAtMs) { _questReadAtMs = -1; @@ -323,8 +451,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase _nextCharacterReadMs = now + CharacterReadMs; _c.Character.Read(Host); _c.Void.RemoveExpired(now); - _c.Server.Refresh(Host, _c.Character.PlayerId); + _c.Server.Refresh(Host, _c.Character.PlayerId, _c.ServerState.State); ApplyServer(); + LoadQuestBook(now); ReadTitles(); TickConquest(now); if (!_voidAutoDecided && _c.Character.Valid) @@ -346,6 +475,19 @@ public sealed class RynthOraclePlugin : RynthPluginBase } } + /// + /// Loads this character's quest book (tracked quests, rewards) once the name is known and the + /// world has been announced, or after without one (then filed + /// under "default"), so the file isn't picked before the world name arrives. + /// + private void LoadQuestBook(long now) + { + if (_c.Book.Loaded || !_c.Character.Valid || _c.Character.Name.Length == 0) return; + if (_c.Server.WorldName.Length == 0 && now - _loginMs < BookWorldWaitMs) return; + _c.Book.Load(_c.Server.WorldName, _c.Character.Name); + if (_c.Book.LoadNote.Length > 0) _c.Print(_c.Book.LoadNote); + } + /// The titles the character holds (engine API v75), re-read each second (cheap; changes are rare). private void ReadTitles() { @@ -395,6 +537,8 @@ public sealed class RynthOraclePlugin : RynthPluginBase } if (_void != null && _voidView != null) Record(_void, now, 500, _voidView.Draw); + if (_timers != null && _timersView != null) + Record(_timers, now, 1000, _timersView.Draw); } /// diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs index 8d59e31..3e76598 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs @@ -28,6 +28,21 @@ internal sealed partial class OracleView 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.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; + if (st.State is { } es) + { + w.TextDisabled(es.HasActive + ? $"RynthCore: {es.ActiveName} ({es.Active}){(es.Picked ? ", picked by hand" : "")}; settings from {(es.ActivePlugin.Length > 0 ? es.ActivePlugin : "no plugin")}" + : "RynthCore: no server active" + (es.Picked ? " (picked by hand)" : "")); + if (RynthCore.Plugin.Shared.ServerProfileView.Parse(st.ProfileJson) is { } prof) + w.TextDisabled($"{st.ProfilePlugin} ({RynthCore.Plugin.Shared.RynthServerProfileApiV1.InterfaceName}): {prof.Summary()}"); + else if (es.ActivePlugin.Length > 0) + w.TextDisabled($"{es.ActivePlugin} hasn't sent its server settings (an older plugin?)."); + w.TextDisabled("Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick |auto."); + } + else if (_c.Host.Version >= 75 && _c.Host.Version < 85) + 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."); w.SeparatorText("Quest list"); @@ -48,6 +63,10 @@ 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 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 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"); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs index 74c66c2..c5fe314 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs @@ -8,7 +8,9 @@ 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) and the full buff list. +/// 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). /// internal sealed partial class OracleView { @@ -54,6 +56,8 @@ internal sealed partial class OracleView Field(w, "Melee D", SkillText(c.MeleeDefense), 0f, 100f); Field(w, "Summoning", SkillText(c.Summoning), 300f, 400f); + DrawSession(w); + var list = new List(c.Enchantments); list.Sort((a, b) => a.Remaining.CompareTo(b.Remaining)); if (w.CollapsingHeader($"Buffs and debuffs ({list.Count})", "c.buffs", defaultOpen: true)) @@ -69,6 +73,38 @@ internal sealed partial class OracleView } } + /// + /// "Session": RynthAi's session (the Mini Remote's Session Stats), so every tracker shows the same + /// XP, luminance and kills. Read through "RynthAi.Hub" only while this tab is on screen. + /// + private void DrawSession(UiWindow w) + { + w.SeparatorText("Session"); + if (!_c.SessionKnown) + { + w.TextDisabled("Load RynthAi for the session rates (the Mini Remote's Session Stats)."); + return; + } + RynthCore.Plugin.Shared.SessionStatsV1 s = _c.Session; + w.TextDisabled($"From RynthAi's Mini Remote, {TimeText.Clock(Math.Max(0, s.SessionSeconds))} so far."); + Field(w, "XP", $"{TimeText.Number(s.Xp)} ({RateText(s.XpPerHour)}/h)", 0f, 100f); + Field(w, "Luminance", $"{TimeText.Number(s.Lum)} ({RateText(s.LumPerHour)}/h)", 300f, 400f); + Field(w, "Kills", $"{s.Kills} ({s.KillsPerHour:0}/h)", 0f, 100f); + Field(w, "Lum, 5 min", TimeText.Number(s.LumLast5Min), 300f, 400f); + if (s.PassUpTracked != 0) + Field(w, "Pass-up", $"{TimeText.Number(s.LumPassUp)} ({RateText(s.PassUpPerHour)}/h)", 0f, 100f); + w.SmallButton("Session Stats", "c.session.open", () => _c.RunCommand(SessionStatsCommand)); + w.Tooltip("Opens RynthCore's Mini Remote on Session Stats (reset the session there)."); + } + + /// + /// The Mini Remote's Session Stats section (RynthCore 2026-10-13). "section", not "tab": the + /// engine sends "tab char" back here (/ro character), since that tab moved to this one. + /// + internal const string SessionStatsCommand = "/rc miniremote section char"; + + private static string RateText(double perHour) => perHour > 0 ? TimeText.Number((long)Math.Round(perHour)) : "0"; + /// /// 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/FellowshipTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/FellowshipTab.cs index 2ef5655..eacc827 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/FellowshipTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/FellowshipTab.cs @@ -1,13 +1,17 @@ // Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +using System.Collections.Generic; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthOracle.Ui; namespace RynthCore.Plugin.RynthOracle.Views; /// -/// Fellowship: name, leader, open/locked, experience sharing and the members (upstream's status -/// list). Read from the client's fellowship object through RynthAi's FellowshipTracker (shared -/// source). The recruiting tools are not ported (see the port report). +/// Fellowship: name, leader, open/locked, experience sharing and the members with their levels +/// (upstream's status list). Read from the client's fellowship object through RynthAi's +/// FellowshipTracker (shared source). The Mini Remote's Fellowship view links here ("/ro fellowship"). +/// A server's own fellowship rules and commands (Infinite Leaftide's larger fellowships and /fship +/// buttons) are its server plugin's (RynthILT's Fellowship section), not drawn here. The upstream +/// recruiting tools are not ported (see the port report). /// internal sealed partial class OracleView { @@ -22,28 +26,40 @@ internal sealed partial class OracleView return; } + // One snapshot for every row: the index getters could each see a different refresh. + List<(int Id, string Name, int Level)> members = f.GetMembers(); int leaderId = f.LeaderId; - int count = f.MemberCount; + int count = System.Math.Max(f.MemberCount, members.Count); string leaderName = ""; - for (int i = 0; i < count; i++) - if (f.GetMemberId(i) == leaderId) leaderName = f.GetMemberName(i); + foreach ((int id, string name, int _) in members) + if (id == leaderId) leaderName = name; + // A server that allows more than retail's nine: no limit is shown (its server plugin knows it). + bool overRetail = count > MaxFellows; w.SeparatorText(f.FellowshipName.Length > 0 ? f.FellowshipName : "Fellowship"); Field(w, "Leader", leaderName.Length > 0 ? leaderName : "-", 0f, 110f); - Field(w, "Members", $"{count} / {MaxFellows}", 300f, 400f); + Field(w, "Members", overRetail ? count.ToString() : $"{count} / {MaxFellows}", 300f, 400f); Field(w, "Open", f.IsOpen ? "yes" : "no", 0f, 110f); Field(w, "Locked", f.IsLocked ? "yes" : "no", 300f, 400f); Field(w, "Experience", f.ShareXP ? "shared" : "not shared", 0f, 110f); - bool canRecruit = (leaderId == (int)_c.Character.PlayerId || f.IsOpen) && count < MaxFellows; - Field(w, "Recruit", count >= MaxFellows ? "fellowship full" : canRecruit ? "you can recruit" : "must be open or leader", 300f, 400f); + bool mayRecruit = leaderId == (int)_c.Character.PlayerId || f.IsOpen; + Field(w, "Recruit", !overRetail && count >= MaxFellows ? "fellowship full" : mayRecruit ? "you can recruit" : "must be open or leader", 300f, 400f); w.SeparatorText("Members"); - for (int i = 0; i < count; i++) + if (members.Count == 0) w.TextDisabled("Reading the member list..."); + // Leader first, then everyone else by name; the level (0 = not read yet) in its own column. + members.Sort((a, b) => a.Id == leaderId ? -1 : b.Id == leaderId ? 1 + : string.Compare(a.Name, b.Name, System.StringComparison.OrdinalIgnoreCase)); + foreach ((int id, string name, int level) in members) { - string name = f.GetMemberName(i); if (name.Length == 0) continue; - if (f.GetMemberId(i) == leaderId) w.TextColored(UiColors.Gold, name + " (leader)"); + if (id == leaderId) w.TextColored(UiColors.Gold, name + " (leader)"); else w.Text(name); + if (level > 0) + { + w.SameLine(260f); + w.TextDisabled("level " + level); + } } } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs new file mode 100644 index 0000000..e58ab7a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestTimersView.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// The Quest Timers window: the quests this character tracks (the * column on the Quests tab), +/// each with the time left before it can be done again, "ready", a kill task's kills left, or +/// done. Replaces RynthAi's Mini Remote quest favorites HUD and UtilityBelt ILT's favorites HUD. +/// Ready quests first, then by time left. Hovering a quest shows its flag and recorded rewards. +/// +internal sealed class QuestTimersView +{ + private const float StatusX = 190f; + private const float RemoveX = 275f; + + private readonly OracleContext _c; + private readonly List _rows = new(); + + public QuestTimersView(OracleContext c) => _c = c; + + public void Draw(UiWindow w) + { + if (!_c.InWorld) + { + w.TextDisabled("Not in the world."); + return; + } + if (!_c.Book.Loaded) + { + w.TextDisabled("Waiting for the character..."); + return; + } + QuestFlagStore flags = _c.Flags; + if (_c.Book.Tracked.Count == 0) + { + w.TextDisabled("No quests tracked."); + w.TextWrapped("Tick * next to a quest on Oracle's Quests tab (/ro) to list it here."); + return; + } + + DateTime now = _c.UtcNow; + _rows.Clear(); + foreach (string flag in _c.Book.Tracked) + _rows.Add(_c.Catalog.TryGet(flag, out Quest q) ? q : new Quest { Flag = flag, IsNew = true }); + _rows.Sort((a, b) => + { + int c = QuestTimer.SortKey(a, flags, now).CompareTo(QuestTimer.SortKey(b, flags, now)); + return c != 0 ? c : string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase); + }); + + foreach (Quest q in _rows) + { + string flag = q.Flag; + w.Text(Cut(q.Label, 26)); + string reward = _c.Book.RewardText(flag); + w.Tooltip(reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}"); + w.SameLine(StatusX); + QuestTimerState s = QuestTimer.State(q, flags, now, out string text); + bool held = flags.TryGet(flag, out _); + switch (s) + { + case QuestTimerState.Ready: w.TextColored(UiColors.Green, held ? text : "not done"); break; + case QuestTimerState.InProgress: w.TextColored(UiColors.Yellow, text); break; + case QuestTimerState.Done: w.TextColored(UiColors.Grey, text); break; + default: w.Text(text); break; + } + w.SameLine(RemoveX); + w.SmallButton("x", "qt.x." + flag, () => _c.Book.SetTracked(flag, false)); + w.Tooltip("Stop tracking this quest."); + } + + if (flags.Loading) w.TextColored(UiColors.Yellow, "Reading quest flags..."); + else if (flags.LastReadUtc == DateTime.MinValue) w.TextDisabled("Quest flags not read yet."); + w.SmallButton("Refresh", "qt.refresh", _c.RequestQuests); + w.Tooltip("Sends /myquests and reads the reply (timers count down by themselves between reads)."); + if (flags.LastReadUtc != DateTime.MinValue) + { + w.SameLine(); + w.TextDisabled($"read {flags.LastReadUtc.ToLocalTime():HH:mm}"); + } + } + + 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.RynthOracle/Views/QuestsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs index fbd6404..dbfae10 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs @@ -1,4 +1,7 @@ // 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). using System; using System.Collections.Generic; using RynthCore.Plugin.RynthOracle.Data; @@ -8,16 +11,22 @@ 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). Click a quest to print its -/// notes and wiki link in chat. +/// 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). /// internal sealed partial class OracleView { private const int QuestPageSize = 40; + private const float QuestListHeightWithPanel = 300f; private static readonly string[] QuestSorts = { "Flag", "Name", "Done first", "Not done first", "Ready soonest", "Most solves" }; + // The reward editor's fields, in QuestReward order (two percentages, then counts). + private static readonly string[] RewardLabels = + { "XP %", "Lum %", "Coins", "Trinkets", "Medallions", "Yellow powder", "Red powder", "Blue powder", "MMDs" }; + private string _questSearch = ""; - private bool _qDone, _qNotDone, _qRepeatable, _qOneTime, _qNew, _qServer; + private bool _qDone, _qNotDone, _qRepeatable, _qOneTime, _qNew, _qServer, _qTracked, _qKill; private int _questSort; private int _questPage; @@ -25,6 +34,11 @@ internal sealed partial class OracleView private string _questKey = ""; private long _questBuiltMs; + // The quest opened below the list, and its reward editor's text (kept while typing). + private string _questSel = ""; + private readonly string[] _rewardEdit = new string[RewardLabels.Length]; + private string _rewardMsg = ""; + private void DrawQuests(UiWindow w) { QuestFlagStore flags = _c.Flags; @@ -40,13 +54,17 @@ internal sealed partial class OracleView w.Button("Refresh", "q.refresh", _c.RequestQuests); w.Tooltip("Sends /myquests to the server and reads the reply."); w.SameLine(); + bool timersShown = _c.QuestTimersWindowVisible(); + w.Button(timersShown ? "Hide quest timers" : "Show quest timers", "q.timers", () => _c.SetQuestTimersWindow(!timersShown)); + w.Tooltip("A small window with the quests you track (the * column) and the time left on each."); + w.SameLine(); QuestCatalog cat = _c.Catalog; w.TextDisabled(cat.PackServer.Length > 0 ? $"{cat.RetailCount} retail quests + {cat.ServerCount} {cat.PackServer} quests" : $"{cat.RetailCount} retail quests"); 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 the quest's flag or name, e.g. \"kill task\". "); w.Checkbox("Done", "q.done", _qDone, v => { _qDone = v; _questPage = 0; }); w.SameLine(); w.Checkbox("Not done", "q.notdone", _qNotDone, v => { _qNotDone = v; _questPage = 0; }); @@ -57,6 +75,11 @@ internal sealed partial class OracleView w.SameLine(); w.Checkbox("Not in list", "q.new", _qNew, v => { _qNew = v; _questPage = 0; }); w.Tooltip("Flags this character holds that no quest list knows."); + w.Checkbox("Tracked", "q.tracked", _qTracked, v => { _qTracked = v; _questPage = 0; }); + w.Tooltip("Only the quests you track (the * column)."); + w.SameLine(); + w.Checkbox("Kill tasks", "q.kill", _qKill, v => { _qKill = v; _questPage = 0; }); + w.Tooltip("Only kill-task counters you hold: kills left, then the reset timer."); if (_c.Catalog.PackServer.Length > 0) { w.SameLine(); @@ -70,52 +93,199 @@ internal sealed partial class OracleView w.SameLine(160f); _questPage = Pager(w, "q.page", _questPage, rows.Count, QuestPageSize, p => _questPage = p); - w.BeginChild("q.list", 0f, 0f, border: true); + // 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); + w.TextDisabled("*"); + w.Tooltip("Track: list the quest in the Quest Timers window."); + w.SameLine(28f); w.TextDisabled("Done"); - w.SameLine(50f); + w.SameLine(72f); w.TextDisabled("Quest"); w.SameLine(370f); w.TextDisabled("Ready in"); - w.SameLine(480f); + w.SameLine(470f); 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."); DateTime now = _c.UtcNow; + bool canTrack = _c.Book.Loaded; int start = _questPage * QuestPageSize; for (int i = start; i < rows.Count && i < start + QuestPageSize; i++) { Quest q = rows[i]; + 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); - w.SameLine(50f); - string name = q.IsNew ? "(new) " + (q.Name.Length > 0 ? q.Name : q.Flag) : q.DisplayName; + w.SameLine(72f); Quest row = q; - w.Selectable(Cut(name, 46), "q.r." + q.Flag, false, () => PrintQuest(row), 310f); - w.Tooltip(q.Flag); + w.Selectable(Cut(q.Label, 44), "q.r." + flag, flag == _questSel, () => SelectQuest(row), 290f); + w.Tooltip(flag); w.SameLine(370f); - string status = q.Status(flags, now); - if (status == "ready" && done) w.TextColored(UiColors.Green, status); - else w.Text(status); + TimerText(w, q, flags, now, done); string solves = q.SolvesText(flags); if (solves.Length > 0) { - w.SameLine(480f); + w.SameLine(470f); w.Text(solves); } + string reward = _c.Book.RewardText(flag); + if (reward.Length > 0) + { + w.SameLine(530f); + w.Text(Cut(reward, 18)); + if (reward.Length > 18) w.Tooltip(reward); + } } - if (rows.Count == 0) w.TextDisabled("No quests match."); + 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); + } + + /// The timer column: "ready" (green once done), a countdown, "N left" (yellow) or done (grey). + private static void TimerText(UiWindow w, Quest q, QuestFlagStore flags, DateTime now, bool done) + { + QuestTimerState s = QuestTimer.State(q, flags, now, out string text); + switch (s) + { + case QuestTimerState.Ready when done: w.TextColored(UiColors.Green, text); break; + case QuestTimerState.InProgress: w.TextColored(UiColors.Yellow, text); break; + case QuestTimerState.Done: w.TextColored(UiColors.Grey, text); break; + default: w.Text(text); break; + } + } + + // ── The opened quest and its rewards ────────────────────────────────── + + private void SelectQuest(Quest q) + { + if (_questSel == q.Flag) { _questSel = ""; return; } // a second click closes it + _questSel = q.Flag; + _rewardMsg = ""; + LoadRewardEdit(q.Flag); + } + + /// Fills the editor from what is recorded (blank fields for zero). + private void LoadRewardEdit(string flag) + { + Array.Fill(_rewardEdit, ""); + if (!_c.Book.TryGetReward(flag, out QuestReward r)) return; + _rewardEdit[0] = r.XpPercent > 0 ? QuestReward.Percent(r.XpPercent) : ""; + _rewardEdit[1] = r.LumPercent > 0 ? QuestReward.Percent(r.LumPercent) : ""; + int[] counts = { r.Coins, r.Trinkets, r.Medallions, r.YellowPowder, r.RedPowder, r.BluePowder, r.Mmd }; + for (int i = 0; i < counts.Length; i++) _rewardEdit[2 + i] = counts[i] > 0 ? counts[i].ToString() : ""; + } + + private void DrawSelectedQuest(UiWindow w) + { + Quest q = _c.Catalog.TryGet(_questSel, out Quest found) ? found : new Quest { Flag = _questSel, IsNew = true }; + QuestFlagStore flags = _c.Flags; + w.SeparatorText(Cut(q.Label, 60)); + w.TextDisabled("Flag"); + w.SameLine(90f); + w.Text(q.Flag); + w.TextDisabled("Status"); + w.SameLine(90f); + TimerText(w, q, flags, _c.UtcNow, q.IsComplete(flags)); + if (flags.TryGet(q.Flag, out QuestFlag f)) + { + w.SameLine(260f); + w.TextDisabled(f.MaxSolves > 0 ? $"solves {f.Solves} of {f.MaxSolves}" : $"solves {f.Solves}"); + } + string details = q.Details(); + if (details.Length > 0) w.TextWrapped(Cut(details, 600)); + + bool loaded = _c.Book.Loaded; + bool tracked = _c.Book.IsTracked(q.Flag); + string flag = q.Flag; + w.Button(tracked ? "Untrack" : "Track", "q.sel.track", () => { if (loaded) _c.Book.ToggleTracked(flag); }); + w.Tooltip("List this quest in the Quest Timers window."); + w.SameLine(); + Quest print = q; + w.Button("Print in chat", "q.sel.print", () => PrintQuest(print)); + w.SameLine(); + w.Button("Close", "q.sel.close", () => _questSel = ""); + + w.SeparatorText("Rewards"); + if (!loaded) + { + w.TextDisabled("Waiting for the character's name before rewards can be saved."); + return; + } + int level = _c.Book.TryGetReward(flag, out QuestReward saved) && saved.RecordedLevel > 0 ? saved.RecordedLevel : _c.Character.Level; + w.TextDisabled($"Level: {level} (XP % and Lum % are for this level)"); + for (int i = 0; i < RewardLabels.Length; i++) + { + int field = i; + w.InputText(RewardLabels[i], "q.rw." + i, _rewardEdit[i], 16, s => _rewardEdit[field] = s); + } + w.Button("Save rewards", "q.rw.save", () => SaveReward(flag)); + w.SameLine(); + w.Button("Clear", "q.rw.clear", () => + { + _c.Book.SetReward(flag, null); + LoadRewardEdit(flag); + _rewardMsg = "Cleared."; + }); + if (_rewardMsg.Length > 0) + { + w.SameLine(); + w.TextDisabled(_rewardMsg); + } + } + + /// Parses the editor (UB's rules: percent 0..1000, counts 0 and up) and stores the entry. + private void SaveReward(string flag) + { + var r = new QuestReward(); + if (!QuestReward.TryParsePercent(_rewardEdit[0], out r.XpPercent)) { _rewardMsg = "XP % isn't a number."; return; } + if (!QuestReward.TryParsePercent(_rewardEdit[1], out r.LumPercent)) { _rewardMsg = "Lum % isn't a number."; return; } + var counts = new int[7]; + for (int i = 0; i < counts.Length; i++) + { + if (QuestReward.TryParseCount(_rewardEdit[2 + i], out counts[i])) continue; + _rewardMsg = RewardLabels[2 + i] + " isn't a whole number."; + return; + } + r.Coins = counts[0]; + r.Trinkets = counts[1]; + r.Medallions = counts[2]; + r.YellowPowder = counts[3]; + r.RedPowder = counts[4]; + r.BluePowder = counts[5]; + r.Mmd = counts[6]; + + // The percentages belong to the level they were noted at: keep the old level unless they changed. + bool had = _c.Book.TryGetReward(flag, out QuestReward old); + bool percentChanged = !had || old.XpPercent != r.XpPercent || old.LumPercent != r.LumPercent; + if (r.XpPercent > 0 || r.LumPercent > 0) + r.RecordedLevel = !percentChanged && old.RecordedLevel > 0 ? old.RecordedLevel : _c.Character.Level; + + _c.Book.SetReward(flag, r); + LoadRewardEdit(flag); + _rewardMsg = r.IsEmpty ? "Cleared." : "Saved: " + r.ShortSummary(); } private void PrintQuest(Quest q) { string status = q.IsComplete(_c.Flags) ? q.Status(_c.Flags, _c.UtcNow) : "not done"; PrintEntry(q.IsNew ? (q.Name.Length > 0 ? q.Name : "Not in the quest list") : q.DisplayName, q.Flag, status, q.Details(), q.Url); + if (_c.Book.TryGetReward(q.Flag, out QuestReward r)) _c.Print("Rewards: " + r.LongSummary()); } + // ── Rows ────────────────────────────────────────────────────────────── + /// The filtered, sorted rows; rebuilt when the filter or data changed (or every 5 s for timers). private List QuestRows() { - string key = $"{_questSearch}|{_qDone}{_qNotDone}{_qRepeatable}{_qOneTime}{_qNew}{_qServer}|{_questSort}|{_c.Flags.Revision}|{_c.Catalog.Revision}"; + string key = $"{_questSearch}|{_qDone}{_qNotDone}{_qRepeatable}{_qOneTime}{_qNew}{_qServer}{_qTracked}{_qKill}|{_questSort}" + + $"|{_c.Flags.Revision}|{_c.Catalog.Revision}|{(_qTracked ? _c.Book.Revision : 0)}"; bool timeSorted = _questSort == 4; if (key == _questKey && (!timeSorted || _c.NowMs - _questBuiltMs < 5000)) return _questRows; _questKey = key; @@ -128,6 +298,8 @@ internal sealed partial class OracleView { 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) @@ -170,11 +342,10 @@ internal sealed partial class OracleView } /// Held repeatables by time left (ready ones first); everything else after them. - private static double ReadyKey(Quest q, QuestFlagStore flags, DateTime now) - { - if (!flags.TryGet(q.Flag, out QuestFlag f) || !q.IsRepeatable(flags) || f.AtSolveLimit) return double.MaxValue; - return Math.Max(0, f.NextAvailableTime(now).TotalSeconds); - } + 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)) + ? QuestTimer.SortKey(q, flags, now) + : double.MaxValue; private static int Solves(Quest q, QuestFlagStore flags) => flags.TryGet(q.Flag, out QuestFlag f) && q.IsRepeatable(flags) ? f.Solves : 0; diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj b/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj new file mode 100644 index 0000000..e4e0182 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthPortalStorm + 0.1.0 + portalstorm + PortalStorm + ac.portalstorm.us.com + PortalStorm|Portal Storm + PortalStorm only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs b/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs new file mode 100644 index 0000000..164b6ce --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs @@ -0,0 +1,26 @@ +// ServerData.cs - What is known about PortalStorm (RynthPortalStorm). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + // Not the usual 9000. + Port = 9020, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "15 Tiers, 10 Enlightenments, Infinite Lum Augs, Optional Hard Mode, Custom Skills, Years of custom content.", + Facts = new[] + { + "15 loot tiers.", + "10 enlightenments and infinite luminance augmentations.", + "Optional hard mode.", + "Custom skills and years of custom content.", + "Connects on port 9020, not 9000.", + }, + Discord = "https://discord.gg/YeX6mupcf", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj b/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj new file mode 100644 index 0000000..0c7e1ef --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthReefcull + 0.1.0 + reefcull + Reefcull + reefcull.gdleac.com + Reefcull + Reefcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs new file mode 100644 index 0000000..16ad01a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs @@ -0,0 +1,21 @@ +// ServerData.cs - What is known about Reefcull (RynthReefcull). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "GDLE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE Server thats goal is to mimic end of game retail.", + Facts = new[] + { + "End-of-retail experience on GDLE (not ACE): set the launcher's emulator to Gdle.", + }, + Discord = "https://discord.gg/3ngsm6e", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj b/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj new file mode 100644 index 0000000..e6a833d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthSundering + 0.1.0 + sundering + Sundering + ace.sunderingac.com + Sundering|The Sundering + Sundering only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs b/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs new file mode 100644 index 0000000..4396287 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about Sundering (RynthSundering). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "The Sundering is a 3 active character limit, PVE server targeting an End of Retail feel with convenience " + + "modifications, custom content, and pre-planned weekend/weekday bonuses.", + Facts = new[] + { + "End-of-retail feel with convenience changes and custom content.", + "Planned weekend and weekday bonuses.", + }, + AccountLimit = "3 active characters", + Discord = "https://discord.gg/XgHpcVbmJA", + Website = "https://sunderingac.com", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj b/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj new file mode 100644 index 0000000..1bbcd5f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthThistlecrown + 0.1.0 + thistlecrown + Thistlecrown + thistlecrown.ddns.net + Thistlecrown + Thistlecrown only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs b/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs new file mode 100644 index 0000000..13a10f7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs @@ -0,0 +1,19 @@ +// ServerData.cs - What is known about Thistlecrown (RynthThistlecrown). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "Everyone welcome! 3 account limit. Recreation of TD.", + Facts = new[] { "A recreation of the retail Thistledown (TD) server." }, + AccountLimit = "3 accounts", + Discord = "https://discord.gg/uhZ3hn7", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj index d08f2ae..6ffbdeb 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj @@ -29,6 +29,9 @@ + + + diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs index 9ac9d2a..5409615 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs @@ -10,21 +10,28 @@ namespace RynthCore.Plugin.RynthTracker; // luminance (with ACECustom's bank and allegiance pass-up), luminance of the last five minutes, // kills (including a multi-target spell's extra kills found by their corpses), XP per kill, // deaths and Radiance. SessionStatsTracker reads the game and keeps the session across reloads. +// +// One session (0.4.1, 2026-10-13): with RynthAi loaded the panel shows RynthAi's own session +// (the Mini Remote's Session Stats, read through "RynthAi.Hub"), so the Tracker, the Mini Remote, +// RynthOracle and RynthILT count the same session from the same start, and Reset starts that one +// over. Without RynthAi (or before its login) the Tracker's own session, kept running all along, +// is shown instead. public sealed class RynthTrackerPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker"); - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.0"); // previous release: 0.3.0 + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.1"); // previous release: 0.4.0 private SessionStatsTracker? _session; + private readonly RynthAiSessionClient _ai = new(); private int _tickCounter; + // Set by the engine's UI thread (Reset export), acted on by the next OnTick on the pump. + private volatile bool _resetWanted; // Written on the game thread every ~0.5s, read on the engine's UI thread. // Reference reads are atomic on x86 so volatile is sufficient; no lock needed. private volatile string _snapshot = EmptySnapshot; - private const string EmptySnapshot = - "{\"ss\":0.0,\"xt\":0,\"xh\":0,\"lt\":0,\"lh\":0,\"l5\":0,\"pt\":0,\"ph\":0,\"pk\":0," - + "\"kt\":0,\"kh\":0.0,\"xk\":0,\"dt\":0,\"rt\":0,\"rh\":0,\"ml\":0}"; + private const string EmptySnapshot = TrackerSnapshot.Empty; public override int Initialize() { @@ -33,11 +40,16 @@ public sealed class RynthTrackerPlugin : RynthPluginBase return 0; } - public override void OnLoginComplete() => _session?.OnLoginComplete(); + public override void OnLoginComplete() + { + _ai.Reset(); + _session?.OnLoginComplete(); + } public override void OnLogout() { _session?.OnLogout(); + _ai.Reset(); _snapshot = EmptySnapshot; } @@ -58,39 +70,31 @@ public sealed class RynthTrackerPlugin : RynthPluginBase { var session = _session; if (session == null) return; + long nowMs = Environment.TickCount64; + if (_resetWanted) + { + _resetWanted = false; + // RynthAi's session when it is the one shown; the Tracker's own either way, so a later + // fallback doesn't jump back to an old start. + _ai.ResetSession(Host, nowMs); + session.RequestReset(); + } session.Tick(); if (++_tickCounter < 30) return; // rebuild every ~0.5s at 60Hz _tickCounter = 0; - _snapshot = session.Active ? BuildSnapshot(session.View, DateTime.UtcNow) : EmptySnapshot; + DateTime now = DateTime.UtcNow; + if (_ai.TryGet(Host, nowMs, out SessionStatsV1 s)) + { + SessionStatsMoreV1? more = _ai.TryGetMore(Host, nowMs, out SessionStatsMoreV1 m) ? m : null; + _snapshot = TrackerSnapshot.Build(TrackerSnapshot.FromRynthAi(s, more, session.Active ? session.View : null), now); + } + else + _snapshot = session.Active ? TrackerSnapshot.Build(session.View, now) : EmptySnapshot; } internal string GetSnapshot() => _snapshot; /// Called from the RynthTrackerReset export (engine UI thread): just flags a reset; /// the next OnTick performs it on the pump thread. - internal void Reset() => _session?.RequestReset(); - - private static string BuildSnapshot(SessionStatsView v, DateTime now) - { - // The session clock runs between polls; the totals and rates are the poll's. - double ss = Math.Max(0, (now - v.SessionStartUtc).TotalSeconds); - var ic = System.Globalization.CultureInfo.InvariantCulture; - return "{\"ss\":" + ss.ToString("F1", ic) - + ",\"xt\":" + v.Xp - + ",\"xh\":" + (long)v.XpPerHour - + ",\"lt\":" + v.Lum - + ",\"lh\":" + (long)v.LumPerHour - + ",\"l5\":" + v.LumLast5Min // luminance of the last five minutes - + ",\"pt\":" + v.LumPassUp // allegiance pass-up (ACECustom bank) - + ",\"ph\":" + (long)v.PassUpPerHour - + ",\"pk\":" + (v.PassUpTracked ? 1 : 0) // 1 = the bank is read, pass-up is known - + ",\"kt\":" + v.Kills - + ",\"kh\":" + v.KillsPerHour.ToString("F1", ic) - + ",\"xk\":" + v.XpPerKill // your kills only - + ",\"dt\":" + v.Deaths - + ",\"rt\":" + v.Rad // Radiance (Aelrynth); 0 elsewhere - + ",\"rh\":" + (long)v.RadPerHour - + ",\"ml\":" + (v.MaxLevel ? 1 : 0) // at the level cap: experience can't rise - + "}"; - } + internal void Reset() => _resetWanted = true; } diff --git a/Plugins/RynthCore.Plugin.RynthTracker/TrackerSnapshot.cs b/Plugins/RynthCore.Plugin.RynthTracker/TrackerSnapshot.cs new file mode 100644 index 0000000..b19e6fb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthTracker/TrackerSnapshot.cs @@ -0,0 +1,60 @@ +using System; +using System.Globalization; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthTracker; + +/// +/// The Tracker panel's snapshot JSON, and RynthAi's session turned into the same view (2026-10-13: +/// one session for every tracker). Pure, so RynthCore.TrackerSessionTests compiles it in directly. +/// +internal static class TrackerSnapshot +{ + public const string Empty = + "{\"ss\":0.0,\"xt\":0,\"xh\":0,\"lt\":0,\"lh\":0,\"l5\":0,\"pt\":0,\"ph\":0,\"pk\":0," + + "\"kt\":0,\"kh\":0.0,\"xk\":0,\"dt\":0,\"rt\":0,\"rh\":0,\"ml\":0}"; + + /// + /// RynthAi's session as the panel's view. The fields an older RynthAi doesn't send (no + /// SessionStatsMore) come from the Tracker's own session when it runs, else zero. + /// + public static SessionStatsView FromRynthAi(SessionStatsV1 s, SessionStatsMoreV1? more, SessionStatsView? own) + { + var start = new DateTime(Math.Clamp(s.StartUtcTicks, 0, DateTime.MaxValue.Ticks), DateTimeKind.Utc); + long xpPerKill = more?.XpPerKill ?? own?.XpPerKill ?? 0; + int deaths = more?.Deaths ?? own?.Deaths ?? 0; + long rad = more?.Rad ?? own?.Rad ?? 0; + double radPerHour = more?.RadPerHour ?? own?.RadPerHour ?? 0; + bool maxLevel = more is { } m ? m.MaxLevel != 0 : own?.MaxLevel ?? false; + return new SessionStatsView(start, s.SessionSeconds, s.Xp, s.XpPerHour, s.Lum, s.LumPerHour, s.LumLast5Min, + s.LumPassUp, s.PassUpPerHour, s.PassUpTracked != 0, (int)Math.Clamp(s.Kills, 0, int.MaxValue), s.KillsPerHour, + xpPerKill, deaths, rad, radPerHour, maxLevel); + } + + /// A rate per hour as a whole number: rounded (not cut off), never negative or NaN. + public static long PerHour(double v) => double.IsFinite(v) && v > 0 ? (long)Math.Round(v, MidpointRounding.AwayFromZero) : 0; + + /// The panel's JSON. The session clock runs between polls; the totals and rates are the poll's. + public static string Build(SessionStatsView v, DateTime now) + { + double ss = Math.Max(0, (now - v.SessionStartUtc).TotalSeconds); + CultureInfo ic = CultureInfo.InvariantCulture; + return "{\"ss\":" + ss.ToString("F1", ic) + + ",\"xt\":" + v.Xp.ToString(ic) + + ",\"xh\":" + PerHour(v.XpPerHour).ToString(ic) + + ",\"lt\":" + v.Lum.ToString(ic) + + ",\"lh\":" + PerHour(v.LumPerHour).ToString(ic) + + ",\"l5\":" + v.LumLast5Min.ToString(ic) // luminance of the last five minutes + + ",\"pt\":" + v.LumPassUp.ToString(ic) // allegiance pass-up (ACECustom bank) + + ",\"ph\":" + PerHour(v.PassUpPerHour).ToString(ic) + + ",\"pk\":" + (v.PassUpTracked ? 1 : 0) // 1 = the bank is read, pass-up is known + + ",\"kt\":" + v.Kills.ToString(ic) + + ",\"kh\":" + v.KillsPerHour.ToString("F1", ic) + + ",\"xk\":" + v.XpPerKill.ToString(ic) // your kills only + + ",\"dt\":" + v.Deaths.ToString(ic) + + ",\"rt\":" + v.Rad.ToString(ic) // Radiance (Aelrynth); 0 elsewhere + + ",\"rh\":" + PerHour(v.RadPerHour).ToString(ic) + + ",\"ml\":" + (v.MaxLevel ? 1 : 0) // at the level cap: experience can't rise + + "}"; + } +} diff --git a/Plugins/Shared/ChatSource.cs b/Plugins/Shared/ChatSource.cs new file mode 100644 index 0000000..7674f8d --- /dev/null +++ b/Plugins/Shared/ChatSource.cs @@ -0,0 +1,56 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ChatSource.cs +// Telling a server line from a player's imitation of one. +// +// Some chat lines are signals: "Your missile attack hit the environment." moves +// the combat target, a "~ael1 " data line feeds the vault view. Another player +// can type the same words, so a reader of a signal needs both checks here: +// - the chat type is not one a player writes in (ACE ChatMessageType, which +// is the client's eChatTypes: ACE.Entity/Enum/ChatMessageType.cs); +// - the line STARTS with the marker. The client puts the speaker in front +// of player text ("Name says, ...", "Name tells you, ...", "Name waves"), +// so a player's copy never starts with it. +// Compiled into each plugin that reads a signal (linked source). +// ============================================================================ + +using System; + +namespace RynthCore.Plugin.Shared; + +internal static class ChatSource +{ + // Chat types whose text another player writes. + public const int Speech = 0x02; + public const int Tell = 0x03; + public const int OutgoingTell = 0x04; + public const int Channel = 0x08; + public const int ChannelSend = 0x09; + public const int Social = 0x0A; + public const int SocialSend = 0x0B; + public const int Emote = 0x0C; + public const int Allegiance = 0x12; + public const int Fellowship = 0x13; + + /// + /// True when a line of this chat type is a player's words. A caller that + /// doesn't know the type passes -1 (false), and then only the anchor protects it. + /// + public static bool IsPlayerAuthored(int chatType) => chatType switch + { + Speech or Tell or OutgoingTell or Channel or ChannelSend + or Social or SocialSend or Emote or Allegiance or Fellowship => true, + _ => false, + }; + + /// The index just past 's leading whitespace. + public static int ContentStart(string line) + { + int i = 0; + while (i < line.Length && char.IsWhiteSpace(line[i])) i++; + return i; + } + + /// True when , past leading whitespace, starts with . + public static bool StartsWithMarker(string? line, string marker, StringComparison comparison = StringComparison.Ordinal) + => line != null && line.AsSpan(ContentStart(line)).StartsWith(marker.AsSpan(), comparison); +} diff --git a/Plugins/Shared/EngineServerState.cs b/Plugins/Shared/EngineServerState.cs new file mode 100644 index 0000000..6e3515b --- /dev/null +++ b/Plugins/Shared/EngineServerState.cs @@ -0,0 +1,260 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/EngineServerState.cs +// RynthCore's answer to "which server is this?" (plugin API v86, +// GetServerStateJson), parsed: every server the engine knows (built-in ILT and +// Aelrynth, plus each loaded server plugin's declaration), whether it is +// active, this character's override, and which plugin owns it (the one to ask +// for its settings through "RynthServer.Profile"; RynthILT answers it for "ilt"). +// The same verdict the Mini Remote, the menus and the Diagnostics server +// picker use, so every plugin follows one choice, overrides included. +// +// Pure (BCL only): the plugins' test tools compile it. ServerStateClient.cs +// polls the engine and the owner plugin. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace RynthCore.Plugin.Shared; + +/// One server in the engine's list. +internal sealed record EngineServer(string Id, string Name, bool Active, bool Detected, string Force, bool BuiltIn, + string Plugin, string Reason); + +/// The engine's server list at one moment (GetServerStateJson, schema 1). +internal sealed class EngineServerState +{ + /// Engine server ids with a meaning across RynthSuite. + public const string IltId = "ilt"; + public const string AelrynthId = "aelrynth"; + + public int Revision { get; private init; } + /// The connect host the client was launched with ("" when not known). + public string Host { get; private init; } = string.Empty; + /// The world name the server announced at login ("" before, or without the hook). + public string World { get; private init; } = string.Empty; + /// "auto", a server id (picked on the Diagnostics page or "/rc server pick"), or "mixed". + public string Pick { get; private init; } = "auto"; + /// The active server's id, "" when none is (a retail-like world). + public string Active { get; private init; } = string.Empty; + public string ActiveName { get; private init; } = string.Empty; + /// The plugin that owns the active server ("" when none is loaded). + public string ActivePlugin { get; private init; } = string.Empty; + public IReadOnlyList Servers { get; private init; } = Array.Empty(); + + /// True when a server is active. + public bool HasActive => Active.Length > 0; + + /// True when the active server was chosen by hand (a pick), not detected. + public bool Picked => !Pick.Equals("auto", StringComparison.OrdinalIgnoreCase); + + /// The server with , or null when the engine doesn't list it. + public EngineServer? Find(string id) + { + foreach (EngineServer s in Servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + + /// True when is the active server. + public bool IsActive(string id) => Active.Equals(id, StringComparison.OrdinalIgnoreCase) && Active.Length > 0; + + /// + /// Whether this world is one of (a user's server list, "InfiniteLeaftide, + /// Conquest"): names compare case- and space-insensitively against server ids, names and the world. + /// Without the engine ( null) the world name decides. With it, an active + /// server decides ("ilt" counts as any Leaftide name); with none active the world name still counts, + /// unless it names a server the engine lists, which is then off on purpose (not detected, or this + /// character's override). + /// + public static bool MatchesNameList(EngineServerState? engine, string? world, IReadOnlyList names) + { + bool Named(string? s) + { + string n = Norm(s); + if (n.Length == 0) return false; + foreach (string name in names) + if (Norm(name) == n) return true; + return false; + } + bool anyLeaftide = false; + foreach (string name in names) + if (Norm(name).Contains("leaftide", StringComparison.Ordinal)) anyLeaftide = true; + + if (engine == null) return Named(world); + if (engine.HasActive) + return Named(engine.Active) || Named(engine.ActiveName) || (anyLeaftide && engine.IsActive(IltId)); + if (!Named(world)) return false; + string w = Norm(world); + foreach (EngineServer s in engine.Servers) + { + if (Norm(s.Id) == w || Norm(s.Name) == w) return false; + // ILT's world names ("InfiniteLeaftide") are the engine's own ILT detection. + if (s.Id.Equals(IltId, StringComparison.OrdinalIgnoreCase) && w.Contains("leaftide", StringComparison.Ordinal)) return false; + } + return true; + } + + /// Lower case without spaces, so "Infinite Leaftide" equals "InfiniteLeaftide". + private static string Norm(string? s) => (s ?? string.Empty).Replace(" ", string.Empty).Trim().ToLowerInvariant(); + + /// + /// Parses GetServerStateJson output. Null for empty or unusable text, or another schema's. + /// Missing fields read as empty; nothing throws. + /// + public static EngineServerState? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; + if (Int(root, "schema") != 1) return null; + + var servers = new List(); + if (root.TryGetProperty("servers", out JsonElement list) && list.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in list.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + string id = Str(e, "id"); + if (id.Length == 0) continue; + servers.Add(new EngineServer(id, Str(e, "name"), Bool(e, "active"), Bool(e, "detected"), + Str(e, "force"), Bool(e, "builtIn"), Str(e, "plugin"), Str(e, "reason"))); + } + } + + return new EngineServerState + { + Revision = Int(root, "revision"), + Host = Str(root, "host"), + World = Str(root, "world"), + Pick = Str(root, "pick") is { Length: > 0 } pick ? pick : "auto", + Active = Str(root, "active"), + ActiveName = Str(root, "activeName"), + ActivePlugin = Str(root, "activePlugin"), + Servers = servers, + }; + } + catch (JsonException) + { + return null; + } + } + + internal static string Str(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty) : string.Empty; + + internal static bool Bool(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + internal static int Int(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) ? n : 0; +} + +/// +/// The headline facts of a server owner's profile JSON ("RynthServer.Profile" from the plugin that +/// owns the server), read leniently: a field the owner doesn't send stays "". +/// +internal sealed record ServerProfileView(string Id, string Name, string Plugin, string Ruleset, string Emulator, + string Botting, string BottingNote, string AccountLimit, bool Ilt, int FeaturesOn) +{ + /// Null for empty or unusable text. + public static ServerProfileView? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; + // RynthILT's profile: its feature list, state 1 = on. + int on = 0; + if (root.TryGetProperty("features", out JsonElement features) && features.ValueKind == JsonValueKind.Array) + foreach (JsonElement f in features.EnumerateArray()) + if (f.ValueKind == JsonValueKind.Object && EngineServerState.Int(f, "state") == 1) on++; + return new ServerProfileView( + EngineServerState.Str(root, "id"), EngineServerState.Str(root, "name"), EngineServerState.Str(root, "plugin"), + EngineServerState.Str(root, "ruleset"), EngineServerState.Str(root, "emulator"), + EngineServerState.Str(root, "botting"), EngineServerState.Str(root, "bottingNote"), + EngineServerState.Str(root, "accountLimit"), EngineServerState.Bool(root, "ilt"), on); + } + catch (JsonException) + { + return null; + } + } + + /// One plain-ASCII line for a status report ("PvE, ACE; botting forbidden - ..."). + public string Summary() + { + var parts = new List(); + if (Ruleset.Length > 0 || Emulator.Length > 0) + parts.Add(Ruleset.Length > 0 && Emulator.Length > 0 ? Ruleset + ", " + Emulator : Ruleset + Emulator); + if (Botting.Length > 0) parts.Add("botting " + Botting + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty)); + if (AccountLimit.Length > 0) parts.Add("accounts: " + AccountLimit); + if (Ilt || FeaturesOn > 0) parts.Add((Ilt ? "ILT world" : "not ILT") + ", " + FeaturesOn + " Leaftide features on"); + return parts.Count == 0 ? "no details" : string.Join("; ", parts); + } +} + +/// +/// One salvage from a server plugin's profile "salvage" list (ServerPackInfo.Salvage): a tinkering +/// recipe the server adds, for the Mini Remote's Crafting tab. The fields after +/// are optional in the JSON; absent, a row behaves as before them. +/// +/// "applied": an int property of the item that reads 2 once the row is on it (0 = none). +/// "prepared": the bag must first be prepared on the chosen tier's Ammunition. +/// "order": apply order (lower first); 0 = the kind-based default. +/// "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. +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) +{ + /// + /// The profile's salvage rows, read leniently: a missing list (an older plugin) is empty; a row + /// without a bench or a material id is skipped; "slot" defaults to true, the optional fields to + /// none (a stack group without a positive cap is no group). + /// + public static IReadOnlyList ParseList(string? json) + { + var rows = new List(); + if (string.IsNullOrWhiteSpace(json)) return rows; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("salvage", out JsonElement list) || list.ValueKind != JsonValueKind.Array) + return rows; + foreach (JsonElement e in list.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + string bench = EngineServerState.Str(e, "bench").Trim().ToLowerInvariant(); + int material = EngineServerState.Int(e, "material"); + if (bench.Length == 0 || material <= 0) continue; + string kind = EngineServerState.Str(e, "kind").Trim().ToLowerInvariant(); + bool slot = !(e.TryGetProperty("slot", out JsonElement s) && s.ValueKind == JsonValueKind.False); + string group = EngineServerState.Str(e, "stackGroup").Trim(); + int cap = EngineServerState.Int(e, "stackCap"); + if (cap <= 0) group = string.Empty; + rows.Add(new ServerSalvageView(bench, material, kind.Length > 0 ? kind : "tink", + EngineServerState.Str(e, "effect"), slot, EngineServerState.Str(e, "nameMatch"), + AppliedInt: EngineServerState.Int(e, "applied"), + Prepared: EngineServerState.Bool(e, "prepared"), + Order: EngineServerState.Int(e, "order"), + AfterCap: EngineServerState.Bool(e, "afterCap"), + StackGroup: group, StackCap: group.Length > 0 ? cap : 0)); + } + } + catch (JsonException) + { + rows.Clear(); + } + return rows; + } +} diff --git a/Plugins/Shared/RynthAiHubApi.cs b/Plugins/Shared/RynthAiHubApi.cs index 77de45d..404ddd7 100644 --- a/Plugins/Shared/RynthAiHubApi.cs +++ b/Plugins/Shared/RynthAiHubApi.cs @@ -75,12 +75,45 @@ public struct SessionStatsV1 public double KillsPerHour; } +/// +/// The rest of the Mini Remote's session (SessionStatsMore, appended 2026-10-13): what RynthTracker's +/// panel shows beyond , so it can show RynthAi's session whole. Blittable. +/// +[StructLayout(LayoutKind.Sequential)] +public struct SessionStatsMoreV1 +{ + /// XP per kill of your own kills (0 = none yet). + public long XpPerKill; + public int Deaths; + /// 1 at the level cap (experience can't rise). + public int MaxLevel; + /// Radiance (Aelrynth); 0 elsewhere. + public long Rad; + public double RadPerHour; +} + [StructLayout(LayoutKind.Sequential)] public unsafe struct RynthAiHubApiV1 { public const string InterfaceName = "RynthAi.Hub"; public const uint InterfaceVersion = 1; + /// + /// The table's size up to and including SessionReset, as every RynthAi 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) + 10 * sizeof(nint)); + + /// Whether a table RynthAi built is big enough to hold the function at . + public static bool Has(RynthAiHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint)); + + /// + /// The byte offset of (for ): the first function + /// appended after the base table. Sequential layout of 4-byte fields and pointers has no padding. + /// + public static int SessionStatsMoreOffset => (int)BaseStructSize; + public uint Version; // InterfaceVersion of the table RynthAi filled; 0 once it has shut down public uint StructSize; // sizeof(RynthAiHubApiV1) as RynthAi built it @@ -125,4 +158,12 @@ public unsafe struct RynthAiHubApiV1 /// SessionReset(): starts the Mini Remote's session over (as its Reset XP button). Any thread. public delegate* unmanaged[Cdecl] SessionReset; + + // ── Appended 2026-10-13 (check with Has before calling) ───────────────── + + /// + /// SessionStatsMore(more): the rest of the same session (XP per kill, deaths, Radiance, level + /// cap); 0 before login. RynthTracker shows RynthAi's session through this and SessionStats. Any thread. + /// + public delegate* unmanaged[Cdecl] SessionStatsMore; } diff --git a/Plugins/Shared/RynthAiSessionClient.cs b/Plugins/Shared/RynthAiSessionClient.cs new file mode 100644 index 0000000..2728e90 --- /dev/null +++ b/Plugins/Shared/RynthAiSessionClient.cs @@ -0,0 +1,100 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthAiSessionClient.cs +// A read-only reader of RynthAi's session stats through the "RynthAi.Hub" interface +// (Shared/RynthAiHubApi.cs, SessionStats / SessionReset). Since 2026-10-13 RynthAi's +// session is the one XP / luminance / kills session every tracker shows: the Mini Remote's +// Session Stats, RynthOracle's Character tab, RynthILT's rates and RynthTracker (which +// falls back to its own session only when RynthAi isn't loaded). +// Linked into each reader (with RynthAiHubApi.cs); pure lookup, no state beyond the table. +// +// The table is looked up through the host (API v68) at most every RecheckMs, and again at +// once when RynthAi has shut down (Version 0): RynthAi loading later, reloading or missing +// are all handled, every call then just answers "no session". Pump thread. +// ============================================================================ + +using System; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +/// RynthAi's session stats for another plugin (pump thread). +public sealed unsafe class RynthAiSessionClient +{ + private const long RecheckMs = 3000; + + private RynthAiHubApiV1* _table; + private long _nextQueryAt; + + /// RynthAi answered with its hub table (last lookup). + public bool Connected => _table != null && _table->Version >= 1; + + /// Forget the table; the next call looks it up again (login, logout). + public void Reset() + { + _table = null; + _nextQueryAt = 0; + } + + /// + /// RynthAi's session now. False without RynthAi, before its login or before it has a session, + /// so the caller can fall back to its own count. + /// + public bool TryGet(RynthCoreHost host, long now, out SessionStatsV1 stats) + { + stats = default; + RynthAiHubApiV1* t = Table(host, now); + if (t == null || t->SessionStats == null) return false; + SessionStatsV1 s = default; + try + { + if (t->SessionStats(&s) == 0) return false; + } + catch { return false; } + if (s.StartUtcTicks <= 0) return false; + stats = s; + return true; + } + + /// Starts RynthAi's session over (its Reset XP button). False without RynthAi. + public bool ResetSession(RynthCoreHost host, long now) + { + RynthAiHubApiV1* t = Table(host, now); + if (t == null || t->SessionReset == null) return false; + try { t->SessionReset(); } + catch { return false; } + return true; + } + + /// The table, re-queried when it is missing or RynthAi has shut down (Version 0). + private RynthAiHubApiV1* Table(RynthCoreHost host, long now) + { + if (_table != null && _table->Version >= 1) return _table; + _table = null; + if (now < _nextQueryAt || !host.HasGetPluginInterface) return null; + _nextQueryAt = now + RecheckMs; + var p = (RynthAiHubApiV1*)host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); + // The base size, not sizeof: an older RynthAi without the appended functions still gives SessionStats. + if (p != null && p->Version >= 1 && p->StructSize >= RynthAiHubApiV1.BaseStructSize) + _table = p; + return _table; + } + + /// + /// The rest of RynthAi's session (XP per kill, deaths, Radiance, level cap). False without + /// RynthAi, before its login, or from a RynthAi older than SessionStatsMore (2026-10-13). + /// + public bool TryGetMore(RynthCoreHost host, long now, out SessionStatsMoreV1 more) + { + more = default; + RynthAiHubApiV1* t = Table(host, now); + if (!RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SessionStatsMoreOffset) || t->SessionStatsMore == null) return false; + SessionStatsMoreV1 m = default; + try + { + if (t->SessionStatsMore(&m) == 0) return false; + } + catch { return false; } + more = m; + return true; + } +} diff --git a/Plugins/Shared/RynthIltDataApi.cs b/Plugins/Shared/RynthIltDataApi.cs new file mode 100644 index 0000000..fa34804 --- /dev/null +++ b/Plugins/Shared/RynthIltDataApi.cs @@ -0,0 +1,582 @@ +// ============================================================================ +// 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): +// - 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); +// - version 2: the pet breeding tracker (GetPetBreedingJson, PetBreedingCommand). +// Separate from "RynthServer.Profile" (the server's settings) and "RynthILT.Hub" (RynthAi's +// exact-version table) so neither 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. +// - Reading a JSON says "someone is looking": RynthILT rebuilds that snapshot on its pump +// (every couple of seconds) only while it is being read, so an idle reader costs nothing. +// +// GetCharmsJson payload (IltCharms.BuildReaderJson; read leniently): +// { "available": true, "world": "InfiniteLeaftide", "total": 28, "acquiredCount": 5, "activeCount": 3, +// "charms": [ { "name": "Mana Barrier", "effect": "...", "acquired": "carried"|"seen"|"no", +// "count": 1, "tier": 3, "maxTier": 5, "active": "on"|"off"|"unknown", +// "server": "on"|"off"|"unknown", "lastSeen": "2026-10-13", "toggleId": 1234567 } ], +// "hands": [ { "id": 1234568, "name": "Guardian Hand", "active": "on"|"off"|"unknown", +// "server": "on"|"off"|"unknown" } ] } +// "hands" are the Guardian Hands carried now (not a registry charm); "id" is their Toggle id. +// +// GetBankJson payload (IltBankExport.Build; read leniently): +// { "available": true, "enabled": 1, "world": "InfiniteLeaftide", "character": "Name", +// "characters": [ { "name": "Name", "current": true, "pyreals": 0, "luminance": 0, +// "legendaryKeys": 0, "mythicalKeys": 0, "enlightenedCoins": 0, +// "weaklyEnlightenedCoins": 0, "prestigeCoins": 0, "updated": "2026-10-13T21:25:37Z" } ], +// "deposits": ["Everything", ...], "withdrawals": [ { "label": "Pyreals", "notes": false } ], +// "transfers": [ { "label": "Pyreals", "notes": false } ], "notes": [ { "label": "MMD", "value": 250000 } ], +// "result": "Deposited ...", "transactions": [ { "when": "...", "type": "Sent", "amount": 1, +// "currency": "Pyreals", "player": "Who" } ] } +// "enabled": 1 the server has /bank, 0 it doesn't, -1 not known yet. +// +// BankCommand verbs (ASCII, space separated; the reply lands in "result"): +// refresh quiet /bank balance read +// deposit +// withdraw (amount = note count for trade notes) +// transfer +// 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 +// 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). +// +// GetPetBreedingJson payload (IltPetBreeding.BuildJson; read leniently): +// { "available": true, "world": "...", "enabled": "on"|"off"|"unknown", "maturity": "...", "bond": "...", +// "room": "landblock 0x0106 variant 2", "freeSlots": 12, "message": "...", +// "essences": [ { "id": 1234, "name": "...", "sex": "M"|"F", "tier": 150, "bond": 120, "ready": true, +// "status": "Ready (9/10)", "readyIn": 0, "charges": 9, "chargesMax": 10, "juvenile": false, +// "stage": "Adult", "kills": 300, "killsRequired": 300, "mutations": 2, "potencyMutations": 1, +// "problems": ["..."], "boosters": ["..."] } ], +// "pairs": [ { "stud": "...", "dam": "...", "chanceBest": 0.05, "chanceWorst": 0.04, "inheritMin": 0, "inheritMax": 2 } ], +// "supplies": [ { "key": "incense2", "name": "...", "effect": "...", "count": 1, "price": 2500000, "apply": true, +// "targets": [1234] } ], +// "rules": [ { "label": "...", "value": "10", "source": "seen on server", "help": "..." } ], +// "events": [ { "when": "2026-10-15 20:15", "kind": "birth", "text": "..." } ], newest first +// "debug": { "when": "...", "enabled": "on", "location": "...", "match": "valid"|"invalid"|"", "pet": "...", +// "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). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthIltDataApiV1 +{ + public const string InterfaceName = "RynthILT.Data"; + public const uint InterfaceVersion = 2; + + /// The size of a version-1 table (everything before GetPetBreedingJson) on this platform. + public static uint V1Size + { + get + { + RynthIltDataApiV1 t = default; + return (uint)((byte*)&t.GetPetBreedingJson - (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 + + /// + /// GetCharmsJson(buffer, capacity): the charms JSON (UTF-8, NUL-terminated) when it fits; returns + /// its length without the NUL (capacity or more = too small, nothing written; 0 = nothing to report). + /// + public delegate* unmanaged[Cdecl] GetCharmsJson; + + /// GetBankJson(buffer, capacity): the bank JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetBankJson; + + /// + /// ToggleCharm(objectId): uses the carried charm with that id (a "toggleId" from the charms JSON). + /// RynthILT checks it is one of the player's charms before using it. 1 = queued, 0 = refused. + /// + public delegate* unmanaged[Cdecl] ToggleCharm; + + /// BankCommand(utf8 verb line): queues a bank verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] BankCommand; + + // ── Version 2 ─────────────────────────────────────────────────────────── + + /// GetPetBreedingJson(buffer, capacity): the pet breeding JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetPetBreedingJson; + + /// PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] PetBreedingCommand; +} + +/// +/// A reader of "RynthILT.Data". Looks the table up through the host, +/// re-queried while RynthILT is missing or after it unloads (Version 0), and copies a JSON out on +/// request. Pump thread only. +/// +public sealed unsafe class RynthIltDataClient +{ + private const long RequeryMs = 10_000; + private const int MaxBuffer = 256 * 1024; + private const string PluginName = "RynthILT"; + + private RynthIltDataApiV1* _table; + private long _nextQueryAt; + private byte[] _buffer = new byte[8192]; + + /// RynthILT answered with the table (last lookup). + public bool Connected => _table != null && _table->Version >= 1; + + /// The charms JSON now ("" without RynthILT). + public string ReadCharms(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return t == null || t->GetCharmsJson == null ? "" : Read(t->GetCharmsJson); + } + + /// The bank JSON now ("" without RynthILT). + public string ReadBank(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return t == null || t->GetBankJson == null ? "" : Read(t->GetBankJson); + } + + /// The pet breeding JSON now ("" without a RynthILT that has the tracker). + public string ReadPetBreeding(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return !HasPetBreeding(t) || t->GetPetBreedingJson == null ? "" : Read(t->GetPetBreedingJson); + } + + /// The loaded RynthILT has the breeding tracker (table version 2 or later). + public bool PetBreedingSupported => HasPetBreeding(_table); + + /// Queues a breeding verb line (see the header). False without RynthILT or when it refused. + public bool PetBreedingCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (!HasPetBreeding(t) || t->PetBreedingCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->PetBreedingCommand(p) == 1; + } + catch { return false; } + } + + private static bool HasPetBreeding(RynthIltDataApiV1* t) + => t != null && t->Version >= 2 && 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) + { + RynthIltDataApiV1* t = Table(host, now); + if (t == null || t->ToggleCharm == null || objectId == 0) return false; + try { return t->ToggleCharm(objectId) == 1; } + catch { return false; } + } + + /// Queues a bank verb line (see the header). False without RynthILT or when it refused. + public bool BankCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (t == null || t->BankCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->BankCommand(p) == 1; + } + catch { return false; } + } + + /// The table, re-queried when it is missing or RynthILT has shut down (Version 0). + private RynthIltDataApiV1* 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; + // Version 1 is asked for and a version-1-sized table taken, so an older RynthILT still answers. + var p = (RynthIltDataApiV1*)host.GetPluginInterface(PluginName, RynthIltDataApiV1.InterfaceName, 1); + if (p != null && p->Version >= 1 && p->StructSize >= RynthIltDataApiV1.V1Size) + _table = p; + return _table; + } + + /// Copies a JSON out, growing the buffer once when RynthILT says it didn't fit. + private string Read(delegate* unmanaged[Cdecl] get) + { + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + try + { + fixed (byte* b = _buffer) len = get(b, _buffer.Length); + } + catch { return ""; } + 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 ""; + } +} + +/// One registry charm from the charms JSON. +public sealed record IltCharmRow(string Name, string Effect, string Acquired, int Count, int Tier, int MaxTier, + string Active, string Server, string LastSeen, uint ToggleId) +{ + /// Carried now (in the pack or equipped). + public bool Carried => Acquired == "carried"; +} + +/// A Guardian Hand carried now: its object id (the Toggle's id), name, status and the server's switch. +public sealed record IltHandRow(uint Id, string Name, string Active, string Server); + +/// The charms JSON parsed. without RynthILT; every field read leniently. +public sealed class IltCharmsView +{ + public static readonly IltCharmsView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + /// An Infinite Leaftide world (charms exist). + public bool Available { get; private init; } + public string World { get; private init; } = ""; + public int Acquired { get; private init; } + public int Active { get; private init; } + public IReadOnlyList Charms { get; private init; } = Array.Empty(); + /// The Guardian Hands carried now (none from an older RynthILT). + public IReadOnlyList Hands { get; private init; } = Array.Empty(); + + public static IltCharmsView 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(); + if (root.TryGetProperty("charms", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement c in cs.EnumerateArray()) + { + if (c.ValueKind != JsonValueKind.Object) continue; + string name = IltJson.Str(c, "name"); + if (name.Length == 0) continue; + rows.Add(new IltCharmRow(name, IltJson.Str(c, "effect"), IltJson.Str(c, "acquired", "no"), + (int)IltJson.Long(c, "count"), (int)IltJson.Long(c, "tier"), (int)IltJson.Long(c, "maxTier"), + IltJson.Str(c, "active", "unknown"), IltJson.Str(c, "server", "unknown"), IltJson.Str(c, "lastSeen"), + (uint)Math.Clamp(IltJson.Long(c, "toggleId"), 0, uint.MaxValue))); + } + } + var hands = new List(); + foreach (JsonElement h in IltJson.Array(root, "hands")) + { + uint id = (uint)Math.Clamp(IltJson.Long(h, "id"), 0, uint.MaxValue); + if (id == 0) continue; // no id = nothing a Toggle could use + hands.Add(new IltHandRow(id, IltJson.Str(h, "name", "Guardian Hand"), IltJson.Str(h, "active", "unknown"), + IltJson.Str(h, "server", "unknown"))); + } + return new IltCharmsView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Acquired = (int)IltJson.Long(root, "acquiredCount"), + Active = (int)IltJson.Long(root, "activeCount"), + Charms = rows, + Hands = hands, + }; + } + catch (JsonException) { return None; } + } +} + +/// One character's saved bank balances from the bank JSON. +public sealed record IltBankRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys, + long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime UpdatedUtc); + +/// A bank form choice: its label and whether the amount is a trade-note count. +public sealed record IltBankChoice(string Label, bool Notes); + +/// A trade-note denomination: label and pyreal value. +public sealed record IltBankNote(string Label, long Value); + +/// One logged transfer. +public sealed record IltBankTx(string When, string Type, long Amount, string Currency, string Player); + +/// The bank JSON parsed. without RynthILT; every field read leniently. +public sealed class IltBankView +{ + public static readonly IltBankView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + /// An Infinite Leaftide world (bank commands exist). + public bool Available { get; private init; } + /// 1 the server has /bank, 0 not, -1 not known yet. + public int Enabled { get; private init; } = -1; + public string World { get; private init; } = ""; + public string Character { get; private init; } = ""; + public string Result { get; private init; } = ""; + public IReadOnlyList Characters { get; private init; } = Array.Empty(); + public IReadOnlyList Deposits { get; private init; } = Array.Empty(); + public IReadOnlyList Withdrawals { get; private init; } = Array.Empty(); + public IReadOnlyList Transfers { get; private init; } = Array.Empty(); + public IReadOnlyList Notes { get; private init; } = Array.Empty(); + public IReadOnlyList Transactions { get; private init; } = Array.Empty(); + + public static IltBankView 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 chars = new List(); + foreach (JsonElement c in IltJson.Array(root, "characters")) + { + string name = IltJson.Str(c, "name"); + if (name.Length == 0) continue; + DateTime updated = DateTime.MinValue; + string when = IltJson.Str(c, "updated"); + if (when.Length > 0 + && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) + updated = t; + chars.Add(new IltBankRow(name, IltJson.Bool(c, "current"), IltJson.Long(c, "pyreals"), IltJson.Long(c, "luminance"), + IltJson.Long(c, "legendaryKeys"), IltJson.Long(c, "mythicalKeys"), IltJson.Long(c, "enlightenedCoins"), + IltJson.Long(c, "weaklyEnlightenedCoins"), IltJson.Long(c, "prestigeCoins"), updated)); + } + + var deposits = new List(); + if (root.TryGetProperty("deposits", out JsonElement ds) && ds.ValueKind == JsonValueKind.Array) + foreach (JsonElement d in ds.EnumerateArray()) + if (d.ValueKind == JsonValueKind.String) deposits.Add(d.GetString() ?? ""); + + var notes = new List(); + foreach (JsonElement n in IltJson.Array(root, "notes")) + notes.Add(new IltBankNote(IltJson.Str(n, "label"), IltJson.Long(n, "value"))); + + var tx = new List(); + foreach (JsonElement x in IltJson.Array(root, "transactions")) + tx.Add(new IltBankTx(IltJson.Str(x, "when"), IltJson.Str(x, "type"), IltJson.Long(x, "amount"), + IltJson.Str(x, "currency"), IltJson.Str(x, "player"))); + + return new IltBankView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + Enabled = (int)Math.Clamp(IltJson.Long(root, "enabled", -1), -1, 1), + World = IltJson.Str(root, "world"), + Character = IltJson.Str(root, "character"), + Result = IltJson.Str(root, "result"), + Characters = chars, + Deposits = deposits, + Withdrawals = Choices(root, "withdrawals"), + Transfers = Choices(root, "transfers"), + Notes = notes, + Transactions = tx, + }; + } + catch (JsonException) { return None; } + } + + private static List Choices(JsonElement root, string name) + { + var list = new List(); + foreach (JsonElement c in IltJson.Array(root, name)) + list.Add(new IltBankChoice(IltJson.Str(c, "label"), IltJson.Bool(c, "notes"))); + return list; + } + + /// The bank verb lines (header of this file); pure so the tests check them. + public static string RefreshVerb() => "refresh"; + public static string DepositVerb(int index) => "deposit " + index.ToString(CultureInfo.InvariantCulture); + public static string WithdrawVerb(int index, long amount, int note) + => string.Join(' ', "withdraw", index.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), + note.ToString(CultureInfo.InvariantCulture)); + public static string TransferVerb(int currency, long amount, int note, string recipient) + => string.Join(' ', "transfer", currency.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), + note.ToString(CultureInfo.InvariantCulture), (recipient ?? "").Trim()); +} + +/// One carried combat essence from the pet breeding JSON. +public sealed record IltBreedEssenceRow(int Id, string Name, bool Male, int Tier, int Bond, bool Ready, string Status, long ReadyIn, + int Charges, int ChargesMax, bool Juvenile, string Stage, int Kills, int KillsRequired, + int Mutations, int PotencyMutations, IReadOnlyList Problems, IReadOnlyList Boosters); + +/// A ready stud + dam pairing and its stat mutation odds (0..1). +public sealed record IltBreedPairRow(string Stud, string Dam, double ChanceBest, double ChanceWorst, int InheritMin, int InheritMax); + +/// A breeding supply: count carried, Ivo's price, and the essence ids the server would take it on now. +public sealed record IltBreedSupplyRow(string Key, string Name, string Effect, long Count, long Price, bool Apply, IReadOnlyList Targets); + +/// One breeding rule: its value and where it came from ("seen on server", "ILT profile", "ACE default"). +public sealed record IltBreedRuleRow(string Label, string Value, string Source, string Help); + +/// One breeding event (newest first in the view). +public sealed record IltBreedEventRow(string When, string Kind, string Text); + +/// The last "@breed-debug" reply: when, the switch, where you were, the room check, your pet, partners nearby. +public sealed record IltBreedDebugRow(string When, string Enabled, string Location, string Match, string Pet, string Sex, int Partners); + +/// The pet breeding JSON parsed. without RynthILT; every field read leniently. +public sealed class IltBreedingView +{ + public static readonly IltBreedingView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + public bool Available { get; private init; } + public string World { get; private init; } = ""; + /// "on", "off" or "unknown": the server's pet breeding switch as RynthILT knows it. + public string Enabled { get; private init; } = "unknown"; + public string Maturity { get; private init; } = "unknown"; + public string Bond { get; private init; } = "unknown"; + public string Room { get; private init; } = ""; + /// Free main-pack slots (-1 unknown). + public int FreeSlots { get; private init; } = -1; + public string Message { get; private init; } = ""; + public IReadOnlyList Essences { get; private init; } = Array.Empty(); + public IReadOnlyList Pairs { get; private init; } = Array.Empty(); + public IReadOnlyList Supplies { get; private init; } = Array.Empty(); + public IReadOnlyList Rules { get; private init; } = Array.Empty(); + public IReadOnlyList Events { get; private init; } = Array.Empty(); + public IltBreedDebugRow? Debug { get; private init; } + + public static IltBreedingView 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 essences = new List(); + foreach (JsonElement e in IltJson.Array(root, "essences")) + { + string name = IltJson.Str(e, "name"); + if (name.Length == 0) continue; + essences.Add(new IltBreedEssenceRow((int)IltJson.Long(e, "id"), name, IltJson.Str(e, "sex") == "M", + (int)IltJson.Long(e, "tier"), (int)IltJson.Long(e, "bond"), IltJson.Bool(e, "ready"), IltJson.Str(e, "status"), + IltJson.Long(e, "readyIn"), (int)IltJson.Long(e, "charges"), (int)IltJson.Long(e, "chargesMax"), + IltJson.Bool(e, "juvenile"), IltJson.Str(e, "stage"), (int)IltJson.Long(e, "kills"), (int)IltJson.Long(e, "killsRequired"), + (int)IltJson.Long(e, "mutations"), (int)IltJson.Long(e, "potencyMutations"), + IltJson.Strings(e, "problems"), IltJson.Strings(e, "boosters"))); + } + + var pairs = new List(); + foreach (JsonElement p in IltJson.Array(root, "pairs")) + pairs.Add(new IltBreedPairRow(IltJson.Str(p, "stud"), IltJson.Str(p, "dam"), IltJson.Double(p, "chanceBest"), + IltJson.Double(p, "chanceWorst"), (int)IltJson.Long(p, "inheritMin"), (int)IltJson.Long(p, "inheritMax"))); + + var supplies = new List(); + foreach (JsonElement s in IltJson.Array(root, "supplies")) + { + var targets = new List(); + if (s.TryGetProperty("targets", out JsonElement ts) && ts.ValueKind == JsonValueKind.Array) + foreach (JsonElement t in ts.EnumerateArray()) + if (t.ValueKind == JsonValueKind.Number && t.TryGetInt32(out int id)) targets.Add(id); + supplies.Add(new IltBreedSupplyRow(IltJson.Str(s, "key"), IltJson.Str(s, "name"), IltJson.Str(s, "effect"), + IltJson.Long(s, "count"), IltJson.Long(s, "price"), IltJson.Bool(s, "apply"), targets)); + } + + var rules = new List(); + foreach (JsonElement r in IltJson.Array(root, "rules")) + rules.Add(new IltBreedRuleRow(IltJson.Str(r, "label"), IltJson.Str(r, "value"), IltJson.Str(r, "source"), IltJson.Str(r, "help"))); + + var events = new List(); + foreach (JsonElement ev in IltJson.Array(root, "events")) + events.Add(new IltBreedEventRow(IltJson.Str(ev, "when"), IltJson.Str(ev, "kind"), IltJson.Str(ev, "text"))); + + IltBreedDebugRow? debug = null; + if (root.TryGetProperty("debug", out JsonElement d) && d.ValueKind == JsonValueKind.Object) + debug = new IltBreedDebugRow(IltJson.Str(d, "when"), IltJson.Str(d, "enabled", "unknown"), IltJson.Str(d, "location"), + IltJson.Str(d, "match"), IltJson.Str(d, "pet"), IltJson.Str(d, "sex"), (int)IltJson.Long(d, "partners", -1)); + + return new IltBreedingView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Enabled = IltJson.Str(root, "enabled", "unknown"), + Maturity = IltJson.Str(root, "maturity", "unknown"), + Bond = IltJson.Str(root, "bond", "unknown"), + Room = IltJson.Str(root, "room"), + FreeSlots = (int)IltJson.Long(root, "freeSlots", -1), + Message = IltJson.Str(root, "message"), + Essences = essences, + Pairs = pairs, + Supplies = supplies, + Rules = rules, + Events = events, + Debug = debug, + }; + } + catch (JsonException) { return None; } + } + + /// The breeding verb lines (header of this file); pure so the tests check them. + public static string RefreshVerb() => "refresh"; + public static string DebugVerb() => "debug"; + public static string DanceVerb() => "dance"; + public static string ApplyVerb(string supplyKey, int essenceId) + => string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture)); +} + +/// Lenient JSON field reads shared by the views above. +internal static class IltJson +{ + public static string Str(JsonElement o, string name, string fallback = "") => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? fallback : fallback; + + public static bool Bool(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + public static long Long(JsonElement o, string name, long fallback = 0) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : fallback; + + public static double Double(JsonElement o, string name, double fallback = 0) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : fallback; + + /// The string items of an array field (other kinds skipped). + public static List Strings(JsonElement o, string name) + { + var list = new List(); + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? ""); + return list; + } + + public static IEnumerable Array(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) yield return e; + } +} diff --git a/Plugins/Shared/RynthIltHubApi.cs b/Plugins/Shared/RynthIltHubApi.cs index 75b4631..91028cb 100644 --- a/Plugins/Shared/RynthIltHubApi.cs +++ b/Plugins/Shared/RynthIltHubApi.cs @@ -46,6 +46,11 @@ public static class RynthIltHub public const string SectionQuestBonus = "quests-qb"; /// Pets tab: the /pets and /shinies logs. 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. + /// + public const string SectionPetBreeding = "pets-breeding"; /// 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. @@ -56,6 +61,8 @@ public static class RynthIltHub public const string FeaturePetRefill = "pet_refill"; public const string FeatureUniversalMastery = "universal_mastery"; public const string FeatureRequireComps = "require_spell_comps"; + /// Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off). + public const string FeaturePetBreeding = "pet_breeding"; } /// One ILT tab as GetTabs hands it out. Blittable. diff --git a/Plugins/Shared/RynthServerProfileApi.cs b/Plugins/Shared/RynthServerProfileApi.cs new file mode 100644 index 0000000..6ea3375 --- /dev/null +++ b/Plugins/Shared/RynthServerProfileApi.cs @@ -0,0 +1,80 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthServerProfileApi.cs +// The "RynthServer.Profile" interface: what a server plugin (RynthColdeve, +// RynthConquest, ... - Plugins/Shared/ServerPack) knows about its game server, +// for any plugin that wants the server's settings without drawing the card. +// RynthCore says which server is active and which plugin owns it (plugin API +// v86, GetServerStateJson: "active", "activePlugin"); the reader then asks that +// plugin for this interface (host GetPluginInterface). RynthILT answers it too, +// for "ilt" (RynthILT/ProfileInterface.cs). +// Compiled into the server plugins, RynthILT and their 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 the plugin and never freed; +// shutdown sets Version to 0, and a reader re-queries when it sees that. +// +// GetProfileJson payload (schema 1; read leniently, fields may be added): +// { +// "schema": 1, "id": "coldeve", "name": "Coldeve", "plugin": "RynthColdeve", +// "version": "0.1.3", +// "active": true, // RynthCore's verdict (or the world name before one) +// "world": "Coldeve", // the world name the client reports ("" before login) +// "hosts": [ "play.coldeve.ac" ], "worldNames": [ "Coldeve" ], +// "port": 9000, "emulator": "ACE", "ruleset": "PvE", "status": "Stable", +// "botting": "unknown|allowed|restricted|forbidden", "bottingNote": "", +// "accountLimit": "", "summary": "", +// "facts": [ "..." ], "commands": [ { "command": "/x", "what": "..." } ], +// "salvage": [ { // the server's own tinkering (the Mini Remote's Crafting tab) +// "bench": "melee", // armor, melee, missile, caster, jewelry, items, trinkets +// "material": 52, "kind": "tink|imbue|once", "effect": "...", +// "slot": true, // counts toward the item's 10 tinks +// "nameMatch": "", // the bag's name must contain this +// // optional (absent = off / the default): +// "applied": 370, // item int that reads 2 once the row is on it +// "prepared": true, // the bag is first prepared on the tier's Ammunition +// "order": 10, // apply order, lower first (else imbue, tink, once) +// "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": "" +// } +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthServer.Profile" interface. +public static class RynthServerProfile +{ + /// The profile JSON's schema. + public const int Schema = 1; + + /// "botting" values in the profile JSON. + public const string BottingUnknown = "unknown"; + public const string BottingAllowed = "allowed"; + public const string BottingRestricted = "restricted"; + public const string BottingForbidden = "forbidden"; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthServerProfileApiV1 +{ + public const string InterfaceName = "RynthServer.Profile"; + public const uint InterfaceVersion = 1; + + public uint Version; // InterfaceVersion of the table the plugin filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthServerProfileApiV1) as the plugin 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 (the plugin is shutting down). Any thread. + /// + public delegate* unmanaged[Cdecl] GetProfileJson; +} diff --git a/Plugins/Shared/SafeImGui.cs b/Plugins/Shared/SafeImGui.cs new file mode 100644 index 0000000..33166f2 --- /dev/null +++ b/Plugins/Shared/SafeImGui.cs @@ -0,0 +1,45 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/SafeImGui.cs +// ImGui text calls for text that isn't a literal: chat lines, item and player +// names, server replies, settings values, interpolated strings. +// +// ImGui.NET passes the string of Text / TextColored / TextWrapped / +// TextDisabled / BulletText / SetTooltip / SetItemTooltip / LabelText to +// native ImGui as a printf format with no arguments, so a '%' in it reads +// arguments that were never passed (garbage, or a crash on %s / %n). These +// wrappers double every '%' so the text draws exactly as given. Same +// signatures as ImGui's, so a call site only changes "ImGui." to "SafeImGui.". +// Compiled into each plugin that draws (linked source). Render thread only. +// ============================================================================ + +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.Shared; + +internal static class SafeImGui +{ + /// The text as a printf format that prints it unchanged ('%' doubled); null is empty. + internal static string Escape(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + return text.IndexOf('%') < 0 ? text : text.Replace("%", "%%"); + } + + public static void Text(string? text) => ImGui.Text(Escape(text)); + + public static void TextColored(Vector4 color, string? text) => ImGui.TextColored(color, Escape(text)); + + public static void TextWrapped(string? text) => ImGui.TextWrapped(Escape(text)); + + public static void TextDisabled(string? text) => ImGui.TextDisabled(Escape(text)); + + public static void BulletText(string? text) => ImGui.BulletText(Escape(text)); + + public static void SetTooltip(string? text) => ImGui.SetTooltip(Escape(text)); + + public static void SetItemTooltip(string? text) => ImGui.SetItemTooltip(Escape(text)); + + /// The label is drawn as text, not used as a format; only the value is escaped. + public static void LabelText(string label, string? text) => ImGui.LabelText(label, Escape(text)); +} diff --git a/Plugins/Shared/ServerCommandPanel.cs b/Plugins/Shared/ServerCommandPanel.cs new file mode 100644 index 0000000..043ac2b --- /dev/null +++ b/Plugins/Shared/ServerCommandPanel.cs @@ -0,0 +1,95 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerCommandPanel.cs +// Draws a ServerCommandSet (ServerCommandShare.cs) as buttons: one name box for the +// commands that take an argument, then a wrapped row of buttons. A command flagged 'c' +// turns its button into "Confirm ..." on the first click and runs on the second (within +// ConfirmMs). Clicks hand the chat line to the caller's send, which runs it on the plugin +// tick. Compiled into each plugin that draws server commands. Render thread only. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.Shared; + +internal sealed class ServerCommandPanel +{ + private const long ConfirmMs = 4000; + + private static readonly Vector4 ColConfirm = new(0.95f, 0.45f, 0.35f, 1f); + + private readonly string _id; + private string _argument = string.Empty; + // The command waiting for its second click, and when that offer ends. + private string _armed = string.Empty; + private long _armedUntil; + private string _lastSent = string.Empty; + + /// ImGui id suffix; unique per panel drawn in the same window. + public ServerCommandPanel(string id) => _id = id; + + /// + /// Draws 's commands into the current window. + /// gets the chat line (it should queue it, not run it here) and returns false when it can't. + /// + public void Render(ServerCommandSet set, Func send, string argumentHint = "name (blank = selected player)") + { + if (set.Commands.Count == 0) return; + long now = Environment.TickCount64; + if (_armed.Length > 0 && now > _armedUntil) _armed = string.Empty; + + bool anyArgument = false; + foreach (ServerCommand c in set.Commands) + if (c.TakesArgument) { anyArgument = true; break; } + if (anyArgument) + { + ImGui.SetNextItemWidth(MathF.Min(260f, ImGui.GetContentRegionAvail().X)); + ImGui.InputTextWithHint("##scarg" + _id, argumentHint, ref _argument, (uint)ServerCommandShare.MaxArgument); + } + + ImGuiStylePtr style = ImGui.GetStyle(); + // The row's right edge, taken at the start of a line (ImGui 1.91 has no GetWindowContentRegionMax). + float right = ImGui.GetCursorScreenPos().X + ImGui.GetContentRegionAvail().X; + for (int i = 0; i < set.Commands.Count; i++) + { + ServerCommand c = set.Commands[i]; + bool armed = c.Confirm && _armed == c.Command; + string label = armed ? "Confirm " + c.Label + "?" : c.Label; + + // Wraps to a new line when this button wouldn't fit after the previous one. + if (i > 0) + { + float width = ImGui.CalcTextSize(label).X + style.FramePadding.X * 2f; + float lastRight = ImGui.GetItemRectMax().X; + if (lastRight + style.ItemSpacing.X + width <= right) ImGui.SameLine(); + } + + string? line = ServerCommandShare.Compose(c, _argument); + bool disabled = line == null; + if (disabled) ImGui.BeginDisabled(); + if (armed) ImGui.PushStyleColor(ImGuiCol.Text, ColConfirm); + bool clicked = ImGui.Button(label + "##sc" + _id + i); + if (armed) ImGui.PopStyleColor(); + if (disabled) ImGui.EndDisabled(); + + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + { + string preview = line ?? "Type a name first."; + SafeImGui.SetTooltip(c.Tooltip.Length > 0 ? c.Tooltip + "\n\n" + preview : preview); + } + if (!clicked || line == null) continue; + + if (c.Confirm && !armed) + { + _armed = c.Command; + _armedUntil = now + ConfirmMs; + continue; + } + _armed = string.Empty; + _lastSent = send(line) ? "Sent: " + line : "Couldn't send: " + line; + } + + if (_lastSent.Length > 0) SafeImGui.TextDisabled(_lastSent); + } +} diff --git a/Plugins/Shared/ServerCommandShare.cs b/Plugins/Shared/ServerCommandShare.cs new file mode 100644 index 0000000..0d0d588 --- /dev/null +++ b/Plugins/Shared/ServerCommandShare.cs @@ -0,0 +1,184 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerCommandShare.cs +// Server chat commands one plugin hands another for a RynthCore section, through the +// plugin-command broker (Host.SendPluginCommand, action "servercommands"). +// +// A server plugin (RynthILT for Infinite Leaftide's /fship) knows its server's extra +// commands and keeps them as a ServerCommandSet; it draws them itself (ServerCommandPanel.cs). +// For another plugin's view of that section (SilentKelpie's RynthAi Fellowship tab, not in +// this tree yet) the sender re-sends every few seconds while its server is active and sends +// an empty list when it isn't, so the receiver drops a list that stops arriving (the sender +// unloaded). +// +// Payload: ANSI text, one record per line, fields split by tabs: +// S section serverId serverName +// C label command flags tooltip (0..MaxCommands lines) +// Flags: 'a' takes an optional argument, 'A' needs one, 'c' asks before it runs. +// The receiver checks every field again: a command is one /word line of printable text. +// Pure (no ImGui, no host); compiled into each plugin that uses it and into the tests. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.Shared; + +/// One server command: a button label, the chat command and how it takes an argument. +internal sealed record ServerCommand(string Label, string Command, string Flags, string Tooltip) +{ + /// True when the command can take an argument (the name box). + public bool TakesArgument => Flags.IndexOf('a') >= 0 || Flags.IndexOf('A') >= 0; + + /// True when the command can't run without an argument. + public bool NeedsArgument => Flags.IndexOf('A') >= 0; + + /// True when a click asks before running (the second click runs it). + public bool Confirm => Flags.IndexOf('c') >= 0; +} + +/// The commands one server plugin gives a section; empty Commands means none. +internal sealed record ServerCommandSet(string Section, string ServerId, string ServerName, IReadOnlyList Commands); + +internal static class ServerCommandShare +{ + /// The broker action the receiver handles. + public const string Action = "servercommands"; + + /// Most commands a set carries. + public const int MaxCommands = 24; + + /// Longest section id, server id and flags field. + public const int MaxId = 32; + + /// Longest label and server name. + public const int MaxLabel = 48; + + /// Longest command (before its argument). + public const int MaxCommand = 96; + + /// Longest tooltip. + public const int MaxTooltip = 300; + + /// Longest argument (a player or fellowship name). + public const int MaxArgument = 64; + + /// The payload for ; commands that don't pass are left out. + public static string Build(ServerCommandSet set) + { + var sb = new StringBuilder(256); + sb.Append('S').Append('\t').Append(Clean(set.Section, MaxId)) + .Append('\t').Append(Clean(set.ServerId, MaxId)) + .Append('\t').Append(Clean(set.ServerName, MaxLabel)).Append('\n'); + int n = 0; + foreach (ServerCommand c in set.Commands) + { + if (n >= MaxCommands) break; + ServerCommand clean = Normalize(c); + if (!IsValid(clean)) continue; + sb.Append('C').Append('\t').Append(clean.Label) + .Append('\t').Append(clean.Command) + .Append('\t').Append(clean.Flags) + .Append('\t').Append(clean.Tooltip).Append('\n'); + n++; + } + return sb.ToString(); + } + + /// + /// The set in , or null when it has no S line with a section. + /// Bad C lines are skipped; at most are kept. + /// + public static ServerCommandSet? Parse(string? payload) + { + if (string.IsNullOrEmpty(payload) || payload.Length > 32_768) return null; + string section = string.Empty, serverId = string.Empty, serverName = string.Empty; + bool haveHeader = false; + var commands = new List(); + foreach (string raw in payload.Split('\n')) + { + string line = raw.TrimEnd('\r'); + if (line.Length < 2 || line[1] != '\t') continue; + string[] f = line.Split('\t'); + if (line[0] == 'S' && !haveHeader && f.Length >= 4) + { + section = Clean(f[1], MaxId).ToLowerInvariant(); + serverId = Clean(f[2], MaxId).ToLowerInvariant(); + serverName = Clean(f[3], MaxLabel); + haveHeader = section.Length > 0; + } + else if (line[0] == 'C' && f.Length >= 5 && commands.Count < MaxCommands) + { + ServerCommand c = Normalize(new ServerCommand(f[1], f[2], f[3], f[4])); + if (IsValid(c)) commands.Add(c); + } + } + return haveHeader ? new ServerCommandSet(section, serverId, serverName, commands) : null; + } + + /// + /// True when (normalized) can run: a label, and a command that is one + /// "/word ..." line of printable text with no quotes. + /// + public static bool IsValid(ServerCommand c) + { + if (c.Label.Length == 0 || c.Command.Length < 2 || c.Command.Length > MaxCommand) return false; + if (c.Command[0] != '/' || !char.IsLetter(c.Command[1])) return false; + foreach (char ch in c.Command) + if (char.IsControl(ch) || ch == '"') return false; + return true; + } + + /// + /// The chat line for with , or null when the + /// command needs an argument and has none. A multi-word argument is quoted (ACE's command + /// parser joins "two words"); quotes inside it are dropped. + /// + public static string? Compose(ServerCommand c, string? argument) + { + string arg = CleanArgument(argument); + if (arg.Length == 0) return c.NeedsArgument ? null : c.Command; + if (!c.TakesArgument) return c.Command; + return c.Command + " " + (arg.IndexOf(' ') >= 0 ? "\"" + arg + "\"" : arg); + } + + /// The argument with control characters and quotes removed, spaces collapsed and trimmed, at most characters. + public static string CleanArgument(string? argument) + { + if (string.IsNullOrEmpty(argument)) return string.Empty; + var sb = new StringBuilder(argument.Length); + bool space = false; + foreach (char ch in argument) + { + if (char.IsControl(ch) || ch == '"') continue; + if (char.IsWhiteSpace(ch)) { space = sb.Length > 0; continue; } + if (space) { sb.Append(' '); space = false; } + sb.Append(ch); + if (sb.Length >= MaxArgument) break; + } + return sb.ToString(); + } + + /// One field: tabs, newlines and control characters become spaces, trimmed, cut to . + public static string Clean(string? text, int max) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var sb = new StringBuilder(Math.Min(text.Length, max)); + foreach (char ch in text) + { + sb.Append(char.IsControl(ch) ? ' ' : ch); + if (sb.Length >= max) break; + } + return sb.ToString().Trim(); + } + + // Every field cleaned; flags keep only the known letters. The command is cut one past its + // limit so an over-long one fails IsValid instead of running cut short. + private static ServerCommand Normalize(ServerCommand c) + { + var flags = new StringBuilder(4); + foreach (char ch in c.Flags ?? string.Empty) + if ((ch == 'a' || ch == 'A' || ch == 'c') && flags.ToString().IndexOf(ch) < 0) flags.Append(ch); + return new ServerCommand(Clean(c.Label, MaxLabel), Clean(c.Command, MaxCommand + 1), flags.ToString(), Clean(c.Tooltip, MaxTooltip)); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackExports.cs b/Plugins/Shared/ServerPack/ServerPackExports.cs new file mode 100644 index 0000000..deaed4f --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackExports.cs @@ -0,0 +1,145 @@ +// ServerPackExports.cs - The native exports every server plugin has (compiled into each one). +// UnmanagedCallersOnly entry points can't live in a generic or shared assembly, so each server +// plugin compiles this file itself, around its own ServerPackPlugin. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.ServerPack; + +public static unsafe class ServerPackExports +{ + private static readonly RynthPluginRuntime Runtime = new(); + + /// The live plugin (null before init and after shutdown). + internal static ServerPackPlugin? Plugin => Runtime.Plugin; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + /// + /// Plugin API v68 plugin-to-plugin interfaces: "RynthServer.Profile" v1 (ServerPackInterface), + /// the server's settings for any plugin RynthCore's GetServerStateJson points at this one. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] + private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) + { + try + { + string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; + return ServerPackInterface.Query(iface, version); + } + catch + { + return IntPtr.Zero; // an exception crossing UnmanagedCallersOnly would fail-fast the client + } + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() + { + try { ServerPackInterface.Release(); } catch { } + Runtime.Shutdown(); + IntPtr old = Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero); + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + _sectionsJson = null; + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => ServerPackPlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => ServerPackPlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLogout() => Runtime.OnLogout(); + + // "/rserver ..." commands. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + + /// The standalone server card ("/rserver"). Render thread. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() + { + try { Runtime.OnRender(); } + catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ } + } + + /// + /// The engine's plugin-command broker: "servermenu" from RynthCore (2026.10.5.48+). The ANSI + /// strings are copied before returning (the caller frees them); the payload is only parsed, 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 */ } + } + + /// + /// 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. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] + public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) + { + try + { + 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 (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = wantH; + return 1; + } + catch + { + return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client + } + } + + private static IntPtr _sectionsPtr = IntPtr.Zero; + private static string? _sectionsJson; + + /// + /// RynthCore 2026.10.5.46+: the server and the card's Mini Remote spot (UTF-8 JSON, schema 1). + /// Null before login. An unchanged manifest keeps the same buffer. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + string? json = Runtime.Plugin?.BuildSectionsJson(); + if (json == null) return IntPtr.Zero; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); + IntPtr oldPtr = Interlocked.Exchange(ref _sectionsPtr, newPtr); + if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr); + return newPtr; + } + catch { return IntPtr.Zero; } + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackInfo.cs b/Plugins/Shared/ServerPack/ServerPackInfo.cs new file mode 100644 index 0000000..cb0a0f6 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackInfo.cs @@ -0,0 +1,103 @@ +// ServerPackInfo.cs - What a server plugin knows about its game server (shared by every server plugin). +// +// Identity (id, name, hosts, world names) comes from the plugin's csproj through RynthPluginInfo, the +// same values the engine reads from the embedded manifest, so detection has one source. The rest is +// what is publicly known about the server (ServerData.cs in each project): connection, rule set, +// summary, links, account limits and the botting policy. Unknown stays empty; nothing is guessed. +// Pure: RynthServerPack.Tests compiles it. +using System; + +namespace RynthCore.Plugin.ServerPack; + +/// What the server's rules say about bots (RynthAi automation). +internal enum BottingPolicy +{ + /// Not published here: check the server's own rules. + Unknown, + Allowed, + /// Allowed with limits (attended only, a client cap, ...): see . + Restricted, + /// The server forbids bots. + Forbidden, +} + +/// A chat command the server adds, and what it does. +internal sealed record ServerCommand(string Command, string What); + +/// +/// A salvage the server's own recipes apply (beyond retail tinkering), shown on the Mini Remote's +/// Crafting tab under "Server tinkering". +/// +/// The Crafting tab: "armor", "melee", "missile", "caster", "jewelry", "items" or "trinkets". +/// The bag's MaterialType (131), e.g. 64 = Steel. +/// What it does, one short line. +/// "tink" (repeatable), "imbue" (one per item) or "once" (one application). +/// Counts toward the item's 10 tinks. +/// The bag's name must contain this (bags that share a material id); "" = any. +/// An int property of the item that reads 2 once this salvage is on it (0 = none). +/// The bag must first be prepared on the chosen tier's Ammunition (its name then carries the tier). +/// Apply order on the tab (lower first); 0 = by kind (imbues, then tinks, then one-application rows). +/// Applied last, and only once the item's tink slots are full. +/// Rows with the same group share one cap per item (); "" = none. +/// The group's combined cap per item (with ). +internal sealed record ServerSalvage(string Bench, int Material, string Effect, string Kind = "tink", + bool UsesTinkSlot = true, string NameMatch = "", int AppliedInt = 0, + bool Prepared = false, int Order = 0, bool AfterCap = false, + string StackGroup = "", int StackCap = 0); + +internal sealed class ServerPackInfo +{ + public ServerPackInfo(string id, string name, string[] hosts, string[] worldNames) + { + Id = (id ?? string.Empty).Trim().ToLowerInvariant(); + Name = string.IsNullOrWhiteSpace(name) ? Id : name.Trim(); + Hosts = hosts ?? Array.Empty(); + WorldNames = worldNames ?? Array.Empty(); + } + + /// The engine's id for the server ("coldeve"); a built-in one ("ilt", "aelrynth") keeps the engine's own detection. + public string Id { get; } + public string Name { get; } + /// Connect hosts (the first is the one players are given). + public string[] Hosts { get; } + /// World names the server announces at login. + public string[] WorldNames { get; } + + public int Port { get; init; } = 9000; + /// "ACE" or "GDLE" (the launcher's emulator setting). + public string Emulator { get; init; } = "ACE"; + /// "PvE" or "PvP". + public string Ruleset { get; init; } = "PvE"; + /// "Stable", "Development", ... as the server list says. + public string Status { get; init; } = string.Empty; + /// The server's own one-paragraph description. + public string Summary { get; init; } = string.Empty; + /// Notable rules and features, one line each. + public string[] Facts { get; init; } = Array.Empty(); + /// Chat commands the server adds (only ones known to exist). + 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(); + /// "3 accounts", "3 active characters", ...; empty when not published. + public string AccountLimit { get; init; } = string.Empty; + public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown; + /// The rule in the server's words, when there is one. + public string BottingNote { get; init; } = string.Empty; + public string Discord { get; init; } = string.Empty; + public string Website { get; init; } = string.Empty; + public string Wiki { get; init; } = string.Empty; + /// Where the facts come from, and when they were checked. + public string Source { get; init; } = string.Empty; + + /// "play.coldeve.ac:9000" (the first host), or "" with none. + public string Address => Hosts.Length == 0 ? string.Empty : Hosts[0] + ":" + Port; + + /// The botting line for the card. + public string BottingText => Botting switch + { + BottingPolicy.Allowed => "Allowed" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + BottingPolicy.Restricted => "Restricted" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + BottingPolicy.Forbidden => "Forbidden" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + _ => "Not published here - check the server's rules" + (Discord.Length > 0 ? " (Discord)" : string.Empty), + }; +} diff --git a/Plugins/Shared/ServerPack/ServerPackInterface.cs b/Plugins/Shared/ServerPack/ServerPackInterface.cs new file mode 100644 index 0000000..339b749 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackInterface.cs @@ -0,0 +1,86 @@ +// ServerPackInterface.cs - A server plugin's side of "RynthServer.Profile" +// (Plugins/Shared/RynthServerProfileApi.cs): the server's settings as JSON (ServerPackProfile) for +// other plugins, answered through RynthPluginQueryInterface (ServerPackExports). +// +// The table is allocated once per loaded copy of the plugin and never freed (a plugin DLL is never +// 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.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +internal static unsafe class ServerPackInterface +{ + private static RynthServerProfileApiV1* _table; + 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 static Snapshot? _last; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); + t->StructSize = (uint)sizeof(RynthServerProfileApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthServerProfileApiV1.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. Any thread: the plugin's state is read through volatile fields. + internal static string CurrentJson(ServerPackPlugin? plugin) + { + ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo; + bool active = plugin?.Active ?? false; + string world = plugin?.World ?? string.Empty; + 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)); + return json; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + return Write(CurrentJson(ServerPackExports.Plugin), 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/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs new file mode 100644 index 0000000..7d8b951 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackModel.cs @@ -0,0 +1,224 @@ +// ServerPackModel.cs - A server plugin's view of "is this my server", and what it tells RynthCore. +// +// RynthCore owns the verdict. Each server plugin declares its server in its Mini Remote sections +// manifest (RynthPluginGetSectionsJson, "servers"), so RynthCore detects it (connect host, then the +// announced world name), applies this character's Auto / On / Off override, and pushes the result +// to the plugin as "servermenu" (RynthCore UI/ServerMenus.cs): +// V id name active 0/1 force auto|on|off detected 0/1 reason +// Other line kinds are RynthAi's menus and are skipped. Until a push arrives (an engine older than +// 2026.10.5.48), the plugin falls back to matching the world name itself. +// +// Pushes arrive on whichever thread sent them; each is parsed into one immutable view and published +// 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.Text; +using System.Threading; + +namespace RynthCore.Plugin.ServerPack; + +/// RynthCore's verdict for this plugin's server. +internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason); + +internal sealed class ServerPackModel +{ + /// Payloads longer than this are not ours (a push is a few hundred bytes). + public const int MaxPayload = 64 * 1024; + + private readonly ServerPackInfo _info; + private ServerVerdictView? _engine; + private long _engineAtMs; + + public ServerPackModel(ServerPackInfo info) => _info = info; + + public ServerPackInfo Info => _info; + + /// The last RynthCore verdict for this server (null until a push lists it). Any thread. + public ServerVerdictView? Engine => Volatile.Read(ref _engine); + + /// When the last push arrived (Environment.TickCount64), 0 for never. + public long EngineAtMs => Interlocked.Read(ref _engineAtMs); + + /// A RynthCore "servermenu" push. Any thread. False when it was not usable. + public bool ApplyEngine(string? payload, long nowMs) + { + ServerVerdictView? view = ParseEngine(payload, _info.Id, out bool listed); + if (!listed) return false; + Volatile.Write(ref _engine, view); + Interlocked.Exchange(ref _engineAtMs, nowMs); + return true; + } + + /// Logout: the next character's verdict comes fresh. + public void Clear() + { + Volatile.Write(ref _engine, null); + Interlocked.Exchange(ref _engineAtMs, 0); + } + + /// + /// True when this plugin should act: RynthCore's verdict when it sent one, else the world + /// name () against the plugin's own list. + /// + public bool IsActive(string? world) + { + ServerVerdictView? v = Engine; + return v != null ? v.Active : WorldMatches(world, _info.WorldNames); + } + + /// + /// The verdict for in a "servermenu" payload. + /// is false when the payload has no server lines at all (not a push); the view is null when it has + /// some but not this server (RynthCore hasn't read this plugin's manifest yet). + /// + public static ServerVerdictView? ParseEngine(string? payload, string serverId, out bool listed) + { + listed = false; + if (string.IsNullOrEmpty(payload) || payload.Length > MaxPayload || string.IsNullOrEmpty(serverId)) return null; + ServerVerdictView? view = null; + foreach (string raw in payload.Split('\n')) + { + string[] f = raw.TrimEnd('\r').Split('\t'); + if (f[0] != "V" || f.Length < 6) continue; + listed = true; + if (!f[1].Equals(serverId, StringComparison.OrdinalIgnoreCase)) continue; + view = new ServerVerdictView(f[2], f[3] == "1", NormalizeForce(f[4]), f[5] == "1", f.Length >= 7 ? f[6] : string.Empty); + } + return view; + } + + /// "auto", "on" or "off" (anything else reads as auto). + public static string NormalizeForce(string? text) + { + string t = (text ?? string.Empty).Trim().ToLowerInvariant(); + return t is "on" or "off" ? t : "auto"; + } + + /// "/rc server {id} {mode}" for auto / on / off; "" for anything else. + public static string ForceCommand(string serverId, string mode) + { + string m = (mode ?? string.Empty).Trim().ToLowerInvariant(); + if (m is not ("auto" or "on" or "off") || !IsSafeId(serverId)) return string.Empty; + return "/rc server " + serverId + " " + m; + } + + /// True for an id RynthCore accepts in a command: 1-32 of a-z, 0-9 and '-'. + public static bool IsSafeId(string? id) + { + if (string.IsNullOrEmpty(id) || id.Length > 32) return false; + foreach (char c in id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; + return true; + } + + /// Case-insensitive world-name match, '*' standing for any text (RynthCore's rules). + public static bool WorldMatches(string? world, string[] patterns) + { + if (string.IsNullOrWhiteSpace(world)) return false; + string w = world.Trim(); + foreach (string p in patterns) + if (!string.IsNullOrWhiteSpace(p) && Glob(w, p.Trim())) return true; + return false; + } + + private static bool Glob(string text, string pattern) + { + if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase); + string[] parts = pattern.Split('*'); + int pos = 0; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + if (part.Length == 0) continue; + if (i == 0) + { + if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; + pos = part.Length; + continue; + } + if (i == parts.Length - 1) + return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); + int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); + if (at < 0) return false; + pos = at + part.Length; + } + return true; + } + + // ── RynthPluginGetSectionsJson ──────────────────────────────────────── + + /// The Mini Remote surface of the server card. + public static string SurfaceFor(string serverId) => "section:server-" + serverId; + + /// + /// The Mini Remote section the server cards share: right after Session Stats (core order 0) and + /// before Map (100). Every server plugin declares it the same way; the first declaration wins. + /// + public const string SectionId = "server"; + public const string SectionLabel = "Server"; + public const int SectionOrder = 50; + + /// + /// The plugin's sections manifest (schema 1): its server, for RynthCore to detect, and the server + /// 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. + /// + public static string BuildSectionsJson(ServerPackInfo info, string pluginName) + { + var sb = new StringBuilder(512); + sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name)); + sb.Append(",\"worldNames\":["); + AppendList(sb, info.WorldNames); + sb.Append("],\"hosts\":["); + AppendList(sb, info.Hosts); + sb.Append("]}],\"sections\":[{\"id\":").Append(Q(SectionId)).Append(",\"label\":").Append(Q(SectionLabel)); + sb.Append(",\"order\":").Append(SectionOrder).Append("}],\"contributions\":[{\"section\":").Append(Q(SectionId)); + sb.Append(",\"server\":").Append(Q(info.Id)); + sb.Append(",\"label\":").Append(Q(info.Name + " server (" + pluginName + ")")); + sb.Append(",\"surface\":").Append(Q(SurfaceFor(info.Id))); + 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}]}"); + return sb.ToString(); + } + + private static void AppendList(StringBuilder sb, string[] values) + { + for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ",").Append(Q(values[i])); + } + + /// A JSON string literal. + public static string Q(string? s) + { + var sb = new StringBuilder((s?.Length ?? 0) + 2).Append('"'); + foreach (char c in s ?? string.Empty) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + return sb.Append('"').ToString(); + } + + // ── The launcher side ───────────────────────────────────────────────── + + /// How to set up an account for this server in the RynthCore launcher. + public static string[] LauncherSteps(ServerPackInfo info) => new[] + { + "1. Launcher > Servers > Add: pick \"" + info.Name + "\" under Known server. It fills in " + + (info.Address.Length > 0 ? info.Address : "the host and port") + " (" + info.Emulator + ").", + "2. Launcher > Accounts > Add: choose that server, then the account and character.", + "3. Launch: RynthCore loads this plugin only for clients connecting to " + info.Name + ".", + }; +} diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs new file mode 100644 index 0000000..0e0bb16 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -0,0 +1,276 @@ +// ServerPackPlugin.cs - The shared body of every server plugin (RynthColdeve, RynthAelrynth, ...), +// built like RynthILT: one plugin per game server, so each one ships and updates on its own. +// +// What it does for its server: +// * declares the server to RynthCore (RynthPluginGetSectionsJson "servers": its hosts and world +// names), so RynthCore detects it and puts this plugin's views in the right Mini Remote spots +// (contributions with "server": show only while that server is active); +// * shows the server card (ServerPackUi): RynthCore's verdict, this character's override, what is +// known about the server, and how to set an account up for it in the launcher; +// * stays quiet anywhere else. RynthCore usually doesn't even load it there: the embedded manifest +// names the server's hosts, and the engine loads only the plugin for the host the client +// connects to (PluginManifestGate.SelectServerPlugins). +// +// 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. +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi(RynthPluginInfo.Name); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi( + RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0"); + + /// The chat command every server plugin answers ("/rserver [show|hide|toggle|info]"). + internal const string ChatCommand = "/rserver"; + + /// The card's surface in RynthCore's Mini Remote sections ("section:server-coldeve"). + internal static readonly string SettingsSurface = ServerPackModel.SurfaceFor(RynthPluginInfo.ServerId); + + private readonly ServerPackModel _model; + private readonly ServerPackUi _ui; + private readonly string _sectionsJson; + // 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(); + private volatile bool _loginComplete; + private volatile string? _world; + private bool _wasActive; + + public ServerPackPlugin() + { + ServerPackInfo info = ServerData.Create(); + _model = new ServerPackModel(info); + _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world); + _sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name); + } + + internal ServerPackInfo Info => _model.Info; + + private static ServerPackInfo? _staticInfo; + + /// The server's facts before the plugin object exists ("RynthServer.Profile" asked early). + internal static ServerPackInfo StaticInfo => _staticInfo ??= ServerData.Create(); + + /// RynthCore (or the world name) says this is the plugin's server now. + internal bool Active => _loginComplete && _model.IsActive(_world); + + /// The world name the client reports ("" before login). Any thread. + internal string World => _world ?? string.Empty; + + // ── Hooks for a server's own features (implement in the server's project) ── + + partial void ServerInitialize(); + partial void ServerLoginComplete(); + partial void ServerLogout(); + partial void ServerShutdown(); + /// Every plugin tick while logged in; = this is the plugin's server. + 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); + /// Extra lines for "/rserver info". + partial void ServerInfoLines(Action line); + + public override int Initialize() + { + Host.Log($"[{RynthPluginInfo.Name}] Plugin initialized for {Info.Name} ({Info.Id})."); + ServerInitialize(); + return 0; + } + + // Also called on a freshly (re)loaded plugin while already in game. + public override void OnLoginComplete() + { + _loginComplete = true; + _wasActive = false; + RefreshWorld(); + ServerLoginComplete(); + } + + public override void OnLogout() + { + _loginComplete = false; + _world = null; + while (_commands.TryDequeue(out _)) { } + while (_engineCommands.TryDequeue(out _)) { } + _model.Clear(); + ServerLogout(); + } + + public override void Shutdown() => ServerShutdown(); + + public override void OnTick() + { + if (!_loginComplete) return; + if (_world == null) RefreshWorld(); + while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); + while (_engineCommands.TryDequeue(out string? command)) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command); + } + + bool active = Active; + if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden) + ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here."); + _wasActive = active; + ServerTick(active); + } + + /// The world name the client reports (the server's own once logged in). + private void RefreshWorld() + { + if (Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w)) + _world = w.Trim(); + } + + // ── RynthCore's verdict ────────────────────────────────────────────── + + /// RynthPluginApplyRemoteCommand: "servermenu" from RynthCore. Any thread: parsed and published only. + internal void ApplyRemoteCommand(string action, string value) + { + if (action.Equals("servermenu", StringComparison.OrdinalIgnoreCase)) + _model.ApplyEngine(value, Environment.TickCount64); + } + + /// + /// RynthPluginGetSectionsJson: the server and the card's Mini Remote spot. Always declared + /// (the manifest is static): the engine only collects it once in game, and keeping it across + /// logout and character switches stops the server dropping out of Options > Diagnostics. + /// + internal string? BuildSectionsJson() => _sectionsJson; + + // ── Drawing ────────────────────────────────────────────────────────── + + /// The standalone card window. Render thread. + public override void OnRender() + { + if (!_loginComplete || !_ui.WindowOpen || Host.ImGuiContext == IntPtr.Zero) return; + IntPtr previous = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + try { _ui.RenderWindow(); } + catch (Exception ex) { Host.Log($"[{RynthPluginInfo.Name}] Server window failed: {ex.Message}"); _ui.WindowOpen = false; } + finally { ImGui.SetCurrentContext(previous); } + } + + /// + /// RynthPluginRenderEmbed "section:server-<id>": the card in RynthCore's Mini Remote, drawn + /// 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) + { + wantHeight = 0; + if (!_loginComplete) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + try + { + float startY = ImGui.GetCursorPosY(); + _ui.RenderBody(); + wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); + return true; + } + catch (Exception ex) + { + Host.Log($"[{RynthPluginInfo.Name}] Server card failed: {ex.Message}"); + return false; + } + finally { ImGui.SetCurrentContext(previous); } + } + + // ── Commands ───────────────────────────────────────────────────────── + + public override void OnChatBarEnter(string? text, ref int eat) + { + if (!_loginComplete || string.IsNullOrEmpty(text)) return; + string trimmed = text.Trim(); + if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase) + && !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase)) + return; + string[] parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); + // "/rserver ...": only that server's plugin answers (several load when the host is unknown). + if (parts.Length >= 2 && ServerPackModel.IsSafeId(parts[1].ToLowerInvariant()) && !IsVerb(parts[1])) + { + if (!parts[1].Equals(Info.Id, StringComparison.OrdinalIgnoreCase)) return; + parts = Shift(parts); + } + eat = 1; + _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"; + + /// Drops the server id: "/rserver coldeve info" -> "/rserver info". + private static string[] Shift(string[] parts) + { + var rest = new string[parts.Length - 1]; + rest[0] = parts[0]; + Array.Copy(parts, 2, rest, 1, parts.Length - 2); + return rest; + } + + private void RunCommand(string[] parts) + { + string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "toggle"; + switch (verb) + { + case "show": + _ui.WindowOpen = true; + return; + case "hide": + _ui.WindowOpen = false; + return; + case "toggle": + _ui.WindowOpen = !_ui.WindowOpen; + return; + case "auto": + case "on": + case "off": + _engineCommands.Enqueue(ServerPackModel.ForceCommand(Info.Id, verb)); + return; + case "info": + PrintInfo(); + return; + } + + bool handled = false; + ServerChatCommand(parts, ref handled); + if (handled) return; + ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} [show|hide|toggle] - the {Info.Name} server card (also in the Mini Remote's Char section)."); + ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} info - what is known about {Info.Name}; {ChatCommand} auto|on|off - this character's override."); + } + + private void PrintInfo() + { + string tag = $"[{RynthPluginInfo.Name}] "; + ServerVerdictView? v = _model.Engine; + string verdict = v != null + ? (v.Active ? "on for this world" : "not this world") + (v.Reason.Length > 0 ? " (" + v.Reason + ")" : "") + : (_model.IsActive(_world) ? "this world, by its name" : "not this world, by its name") + " (no RynthCore verdict yet)"; + ChatLine(tag + Info.Name + ": " + verdict); + if (Info.Address.Length > 0) ChatLine(tag + "Address " + Info.Address + " (" + Info.Emulator + ", " + Info.Ruleset + ")"); + if (Info.AccountLimit.Length > 0) ChatLine(tag + "Account limit: " + Info.AccountLimit); + ChatLine(tag + "Botting: " + Info.BottingText); + ServerInfoLines(line => ChatLine(tag + line)); + } + + internal void ChatLine(string text) + { + if (Host.HasWriteToChat) Host.WriteToChat(text, 1); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackProfile.cs b/Plugins/Shared/ServerPack/ServerPackProfile.cs new file mode 100644 index 0000000..e3c3a70 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackProfile.cs @@ -0,0 +1,145 @@ +// ServerPackProfile.cs - A server plugin's settings as JSON, for other plugins ("RynthServer.Profile", +// Plugins/Shared/RynthServerProfileApi.cs, served by ServerPackExports' RynthPluginQueryInterface). +// +// RynthCore's GetServerStateJson (plugin API v86) names the active server and the plugin that owns +// it; a reader (RynthOracle, RynthAi's "/ra server", ...) asks that plugin for this profile to get +// the server's rules without knowing the server: connection, rule set, botting policy, account +// limits, commands, tinkering salvage and links. Everything ServerPackInfo holds, nothing guessed. +// +// 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.Text; + +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerPackProfile +{ + /// The profile JSON's schema (RynthServerProfile.Schema). + public const int Schema = 1; + + /// The "botting" value for a policy. + public static string BottingName(BottingPolicy policy) => policy switch + { + BottingPolicy.Allowed => "allowed", + BottingPolicy.Restricted => "restricted", + BottingPolicy.Forbidden => "forbidden", + _ => "unknown", + }; + + /// + /// The profile for : is this plugin's verdict + /// (RynthCore's when it pushed one), the world name the client reports. + /// + public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world) + { + var sb = new StringBuilder(1024); + sb.Append("{\"schema\":").Append(Schema); + Field(sb, "id", info.Id); + Field(sb, "name", info.Name); + Field(sb, "plugin", pluginName); + Field(sb, "version", pluginVersion); + sb.Append(",\"active\":").Append(active ? "true" : "false"); + Field(sb, "world", world ?? string.Empty); + List(sb, "hosts", info.Hosts); + List(sb, "worldNames", info.WorldNames); + sb.Append(",\"port\":").Append(info.Port); + Field(sb, "emulator", info.Emulator); + Field(sb, "ruleset", info.Ruleset); + Field(sb, "status", info.Status); + Field(sb, "botting", BottingName(info.Botting)); + Field(sb, "bottingNote", info.BottingNote); + Field(sb, "accountLimit", info.AccountLimit); + Field(sb, "summary", info.Summary); + List(sb, "facts", info.Facts); + sb.Append(",\"commands\":["); + for (int i = 0; i < info.Commands.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"command\":"); + Str(sb, info.Commands[i].Command); + sb.Append(",\"what\":"); + Str(sb, info.Commands[i].What); + sb.Append('}'); + } + sb.Append(']'); + // Added within schema 1: readers that don't know "salvage" skip it. The optional row fields + // (applied, prepared, order, afterCap, stackGroup + stackCap) are written only when set. + sb.Append(",\"salvage\":["); + for (int i = 0; i < info.Salvage.Length; i++) + { + ServerSalvage s = info.Salvage[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"bench\":"); + Str(sb, s.Bench); + sb.Append(",\"material\":").Append(s.Material); + sb.Append(",\"kind\":"); + Str(sb, s.Kind); + sb.Append(",\"effect\":"); + Str(sb, s.Effect); + sb.Append(",\"slot\":").Append(s.UsesTinkSlot ? "true" : "false"); + sb.Append(",\"nameMatch\":"); + Str(sb, s.NameMatch); + if (s.AppliedInt != 0) sb.Append(",\"applied\":").Append(s.AppliedInt); + if (s.Prepared) sb.Append(",\"prepared\":true"); + if (s.Order != 0) sb.Append(",\"order\":").Append(s.Order); + if (s.AfterCap) sb.Append(",\"afterCap\":true"); + if (!string.IsNullOrEmpty(s.StackGroup)) + { + sb.Append(",\"stackGroup\":"); + Str(sb, s.StackGroup); + sb.Append(",\"stackCap\":").Append(s.StackCap); + } + sb.Append('}'); + } + sb.Append(']'); + Field(sb, "discord", info.Discord); + Field(sb, "website", info.Website); + Field(sb, "wiki", info.Wiki); + Field(sb, "source", info.Source); + sb.Append('}'); + return sb.ToString(); + } + + private static void Field(StringBuilder sb, string name, string? value) + { + sb.Append(",\"").Append(name).Append("\":"); + Str(sb, value); + } + + private static void List(StringBuilder sb, string name, string[]? values) + { + sb.Append(",\"").Append(name).Append("\":["); + if (values != null) + { + for (int i = 0; i < values.Length; i++) + { + if (i > 0) sb.Append(','); + Str(sb, values[i]); + } + } + sb.Append(']'); + } + + /// 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; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs new file mode 100644 index 0000000..66ea2e9 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -0,0 +1,217 @@ +// ServerPackUi.cs - A server plugin's "server card". +// +// Drawn in two places: RynthCore's Mini Remote, the shared "Server" section, this server's area +// (the surface "section:server-" through RynthPluginRenderEmbed), and its own window ("/rserver"). +// Shows RynthCore's verdict and this character's Auto / On / Off override (read only: it is set in +// RynthCore Options > Diagnostics, 2026-10-13), what is known about the server (address, rule set, +// 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.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerPackUi +{ + private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); + private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); + private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); + private static readonly Vector4 Good = new(0.55f, 0.85f, 0.45f, 1f); + + private readonly ServerPackModel _model; + private readonly string _pluginLabel; + private readonly Func _world; + private readonly string _windowTitle; + private string _status = string.Empty; + + /// The standalone window is open ("/rserver"). + public bool WindowOpen; + + /// "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) + { + _model = model; + _pluginLabel = pluginLabel; + _world = world; + _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; + } + + /// The standalone window, while open. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(460, 520), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(_windowTitle, ref open)) RenderBody(); + ImGui.End(); + WindowOpen = open; + } + + /// The card's content, into the current window. + public void RenderBody() + { + ServerPackInfo info = _model.Info; + RenderVerdict(info); + ImGui.Separator(); + RenderFacts(info); + if (info.Commands.Length > 0) + { + ImGui.Separator(); + RenderCommands(info); + } + ImGui.Separator(); + RenderLinks(info); + ImGui.Separator(); + RenderSetup(info); + if (info.Source.Length > 0) + { + ImGui.Spacing(); + SafeImGui.TextDisabled("Server data: " + info.Source); + } + if (_status.Length > 0) + { + ImGui.Separator(); + SafeImGui.TextWrapped(_status); + } + } + + private void RenderVerdict(ServerPackInfo info) + { + ServerVerdictView? v = _model.Engine; + if (v == null) + { + bool byName = _model.IsActive(_world()); + SafeImGui.TextColored(byName ? Teal : Mute, byName + ? info.Name + ": this world (by its name)" + : info.Name + ": not this world (by its name)"); + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGui.TextWrapped("Waiting for RynthCore's verdict and the override (RynthCore 2026.10.5.48 or later sends them)."); + ImGui.PopStyleColor(); + return; + } + + SafeImGui.TextColored(v.Active ? Teal : Mute, v.Active ? info.Name + ": on for this world" : info.Name + ": not this world"); + if (v.Reason.Length > 0) + { + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(v.Reason); + ImGui.PopStyleColor(); + } + // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). + SafeImGui.TextDisabled("This character: " + ForceText(ServerPackModel.NormalizeForce(v.Force)) + + " (change it in RynthCore Options > Diagnostics)"); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\n" + + "or /rc server " + info.Id + " auto|on|off in chat."); + } + + /// The override as words: Auto (detected), On (forced on) or Off (forced off). + private static string ForceText(string force) => force switch + { + "on" => "forced on", + "off" => "forced off", + _ => "auto (detected)", + }; + + private static void RenderFacts(ServerPackInfo info) + { + if (ImGui.BeginTable("##facts_" + info.Id, 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 110); + ImGui.TableSetupColumn("Value"); + Row("Address", info.Address.Length > 0 ? info.Address : "(not published)"); + Row("Emulator", info.Emulator); + Row("Rule set", info.Ruleset); + if (info.Status.Length > 0) Row("Status", info.Status); + Row("Account limit", info.AccountLimit.Length > 0 ? info.AccountLimit : "(not published)"); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted("Botting"); + ImGui.TableNextColumn(); + Vector4 color = info.Botting switch + { + BottingPolicy.Forbidden => Warn, + BottingPolicy.Restricted => Warn, + BottingPolicy.Allowed => Good, + _ => Mute, + }; + ImGui.PushStyleColor(ImGuiCol.Text, color); + SafeImGui.TextWrapped(info.BottingText); + ImGui.PopStyleColor(); + ImGui.EndTable(); + } + + if (info.Botting == BottingPolicy.Forbidden) + SafeImGui.TextColored(Warn, "This server forbids bots: don't run RynthAi's combat, navigation or looting here."); + + if (info.Summary.Length > 0) + { + ImGui.Spacing(); + SafeImGui.TextWrapped(info.Summary); + } + foreach (string fact in info.Facts) + SafeImGui.BulletText(fact); + } + + private static void Row(string label, string value) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.Text(label); + ImGui.TableNextColumn(); + SafeImGui.TextWrapped(value); + } + + private void RenderCommands(ServerPackInfo info) + { + ImGui.TextUnformatted("Server commands"); + for (int i = 0; i < info.Commands.Length; i++) + { + ServerCommand c = info.Commands[i]; + ImGui.PushID(i); + if (ImGui.SmallButton("Copy")) Copy(c.Command); + ImGui.PopID(); + ImGui.SameLine(); + SafeImGui.Text(c.Command); + ImGui.SameLine(); + SafeImGui.TextDisabled("- " + c.What); + } + } + + private void RenderLinks(ServerPackInfo info) + { + ImGui.TextUnformatted("Links"); + bool any = false; + any |= Link("Discord", info.Discord); + any |= Link("Website", info.Website); + any |= Link("Wiki", info.Wiki); + if (!any) ImGui.TextDisabled("(none published)"); + } + + private bool Link(string label, string url) + { + if (url.Length == 0) return false; + ImGui.PushID(label); + if (ImGui.SmallButton("Copy")) Copy(url); + ImGui.PopID(); + ImGui.SameLine(); + SafeImGui.Text(label + ": " + url); + return true; + } + + private static void RenderSetup(ServerPackInfo info) + { + ImGui.TextUnformatted("Account setup (RynthCore launcher)"); + foreach (string step in ServerPackModel.LauncherSteps(info)) + SafeImGui.TextWrapped(step); + } + + private void Copy(string text) + { + ImGui.SetClipboardText(text); + _status = "Copied: " + text; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props new file mode 100644 index 0000000..540c0e5 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -0,0 +1,72 @@ + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.ServerPack + x86 + + 66 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Plugins/Shared/ServerStateClient.cs b/Plugins/Shared/ServerStateClient.cs new file mode 100644 index 0000000..7b61170 --- /dev/null +++ b/Plugins/Shared/ServerStateClient.cs @@ -0,0 +1,145 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerStateClient.cs +// A plugin's live view of "which server is this, and what are its settings": +// 1. RynthCore's server list (plugin API v86 GetServerStateJson, parsed by +// EngineServerState.cs): the active server, overrides and the Diagnostics +// pick included, and the plugin that owns it; +// 2. that plugin's profile JSON through "RynthServer.Profile" +// (RynthServerProfileApi.cs): a server plugin for its server, RynthILT +// for "ilt". +// Both are polled (every 2 s, cheap when not due) and Revision goes up when +// either changes, so a reader re-applies its server-specific state then. +// +// Needs, linked into the reader: EngineServerState.cs, RynthServerProfileApi.cs. +// Engines older than v86 report Supported = false (the reader keeps its own +// detection). +// Pump thread only. +// ============================================================================ + +using System; +using System.Text; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +internal sealed unsafe class ServerStateClient +{ + private const long PollMs = 2000; + private const long RequeryMs = 10_000; + private const int MaxBuffer = 512 * 1024; + + private long _nextPollAt, _nextQueryAt; + private string _stateJson = string.Empty; + // The owner's "RynthServer.Profile" table. + private string _tableOwner = string.Empty; + private uint* _tableVersion; + private delegate* unmanaged[Cdecl] _getProfileJson; + private byte[] _buffer = new byte[4096]; + + /// The engine has GetServerStateJson (API v86+). False until the first poll. + public bool Supported { get; private set; } + /// The engine's server list, null before the first answer (or without v86). + public EngineServerState? State { get; private set; } + /// The active server owner's profile JSON ("" when none is active, or its plugin has none). + public string ProfileJson { get; private set; } = string.Empty; + /// The plugin came from ("" with none). + public string ProfilePlugin { get; private set; } = string.Empty; + /// Goes up whenever or changes. + public int Revision { get; private set; } + + /// Logout: forget everything; the next poll reads fresh. + public void Clear() + { + _nextPollAt = 0; + _nextQueryAt = 0; + DropTable(); + bool changed = State != null || ProfileJson.Length > 0; + _stateJson = string.Empty; + State = null; + ProfileJson = ProfilePlugin = string.Empty; + if (changed) Revision++; + } + + /// Polls when due; polls now (login). Pump thread. + public void Poll(RynthCoreHost host, long now, bool force = false) + { + if (!force && now < _nextPollAt) return; + _nextPollAt = now + PollMs; + + Supported = host.HasGetServerStateJson; + bool changed = false; + string json = Supported && host.TryGetServerStateJson(out string j) ? j : string.Empty; + if (json != _stateJson) + { + _stateJson = json; + State = EngineServerState.Parse(json); + changed = true; + } + + string owner = State?.ActivePlugin ?? string.Empty; + string profile = owner.Length > 0 ? ReadProfile(host, owner, now) : string.Empty; + if (owner.Length == 0) DropTable(); + if (profile != ProfileJson) + { + ProfileJson = profile; + changed = true; + } + ProfilePlugin = profile.Length > 0 ? owner : string.Empty; + if (changed) Revision++; + } + + /// The owner's profile JSON, querying (or re-querying) its table as needed. + private string ReadProfile(RynthCoreHost host, string owner, long now) + { + if (!owner.Equals(_tableOwner, StringComparison.OrdinalIgnoreCase)) + { + DropTable(); + _tableOwner = owner; + _nextQueryAt = 0; + } + if (_tableVersion != null && *_tableVersion == 0) DropTableKeepOwner(); + if (_getProfileJson == null) + { + if (now < _nextQueryAt || !host.HasGetPluginInterface) return string.Empty; + _nextQueryAt = now + RequeryMs; + if (!Query(host, owner)) return string.Empty; + } + return Read(); + } + + private bool Query(RynthCoreHost host, string owner) + { + var p = (RynthServerProfileApiV1*)host.GetPluginInterface(owner, RynthServerProfileApiV1.InterfaceName, RynthServerProfileApiV1.InterfaceVersion); + if (p == null || p->Version < 1 || p->StructSize < (uint)sizeof(RynthServerProfileApiV1) || p->GetProfileJson == null) return false; + _tableVersion = &p->Version; + _getProfileJson = p->GetProfileJson; + return true; + } + + /// Copies the JSON out, growing the buffer once when the owner says it didn't fit. + private string Read() + { + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + fixed (byte* b = _buffer) len = _getProfileJson(b, _buffer.Length); + if (len <= 0) return string.Empty; + if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len); + if (len + 1 > MaxBuffer) return string.Empty; + _buffer = new byte[len + 1024]; + } + return string.Empty; + } + + private void DropTable() + { + DropTableKeepOwner(); + _tableOwner = string.Empty; + } + + private void DropTableKeepOwner() + { + _tableVersion = null; + _getProfileJson = null; + } +} diff --git a/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj b/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj index c789be5..c9aac25 100644 --- a/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj +++ b/Tools/RynthCore.LootEditor/RynthCore.LootEditor.csproj @@ -16,6 +16,8 @@ + + diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 13648c3..4a224f8 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -113,6 +113,7 @@ internal static class Program MeleeStallTests.Register(runner); ServerMenuTests.Register(runner); MiniRemoteMoveTests.Register(runner); + SectionsTests.Register(runner); ItemsCleanTests.Register(runner); DeathRecallTests.Register(runner); InventoryAttributeFilterTests.Register(runner); @@ -128,6 +129,11 @@ internal static class Program SaveFailureTests.Register(runner); DoorTests.Register(runner); BlankLoadTests.Register(runner); + GiveProfileTests.Register(runner); + TinkerTests.Register(runner); + LauncherSwapTests.Register(runner); + SelfRatingsTests.Register(runner); + IltClientLookupTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj index 692d7e1..5720ea5 100644 --- a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj +++ b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj @@ -55,6 +55,14 @@ + + + + + + diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/AmmoTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/AmmoTests.cs index 722c80d..1891149 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/AmmoTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/AmmoTests.cs @@ -120,6 +120,7 @@ internal static class AmmoTests InHand = unchecked((int)Bow); C.InHandOverride = () => InHand; C.OpenPackOverride = () => unchecked((int)Pack); + C.AmmoOffSettleMs = 0; // the ticks here don't wait on the wall clock Target = new WorldObject(unchecked((int)Monster), "Test Dummy", AcObjectClass.Monster); List(Bow, Crossbow); } @@ -172,7 +173,11 @@ internal static class AmmoTests Check.Eq(FakeHost.Uses.Count, 0, "nor the crossbow before the arrows are off"); Rig.Unwield(Arrows); // the arrows are in the pack - Check.False(rig.Tick(), "tick 3: the crossbow wield is sent"); + rig.C.AmmoOffSettleMs = 60_000; + Check.False(rig.Tick(), "arrows just read off: the settle"); + Check.Eq(FakeHost.Uses.Count, 0, "no crossbow inside the settle"); + rig.C.AmmoOffSettleMs = 0; + Check.False(rig.Tick(), "settled: the crossbow wield is sent"); Check.Eq(FakeHost.Uses.Count, 1, "one UseObject"); Check.Eq(FakeHost.Uses.LastOrDefault(), Crossbow, "for the crossbow"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveProfileTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveProfileTests.cs new file mode 100644 index 0000000..0c70992 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveProfileTests.cs @@ -0,0 +1,127 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// actiontrygiveprofile (security review M3, 2026-10-13): a meta someone shared must not read a +// profile from outside ItemGiver\ or hand the inventory to a player, only to an NPC or vendor. +internal static class GiveProfileTests +{ + private const uint Player = 0x50000F01, Imitator = 0x50000F02; + private const uint Npc = 0x80281000; + private const uint Mote1 = 0x80281101, Mote2 = 0x80281102; + + public static void Register(Runner r) + { + r.Add("give profile: the profile path stays inside ItemGiver (no rooted path, drive, stream or ..)", PathRules); + r.Add("give profile: gives to the NPC with AC's give action, never to a player of the same name", NpcOnly); + r.Add("give profile: a refused path returns 0 and is logged once, not every pulse", RefusedPathLoggedOnce); + } + + private static void PathRules() + { + string root = Path.Combine(Program.TempRoot, "ItemGiverPaths"); + string inside = Path.GetFullPath(root) + Path.DirectorySeparatorChar; + string? R(string a) => ExpressionEngine.ResolveGiveProfilePath(a, root); + + Check.Eq(R("salvage"), inside + "salvage.utl", "a bare name is a .utl inside"); + Check.Eq(R("salvage.utl"), inside + "salvage.utl", ".utl kept"); + Check.Eq(R("mine.json"), inside + "mine.json", ".json kept"); + Check.Eq(R(@"sub\deep.json"), inside + @"sub\deep.json", "a subfolder is fine"); + Check.Eq(R(@"sub\..\back.utl"), inside + "back.utl", ".. that stays inside is fine"); + Check.Eq(R(@"..\evil.utl"), null, "..\\ climbs out"); + Check.Eq(R(@"sub\..\..\evil"), null, "climbing out through a subfolder"); + Check.Eq(R(@"C:\Windows\win.ini"), null, "a full path"); + Check.Eq(R(@"\\server\share\x.utl"), null, "a UNC path"); + Check.Eq(R(@"\x.utl"), null, "a root-relative path"); + Check.Eq(R("C:x.utl"), null, "a drive-relative path"); + Check.Eq(R("x.utl:hidden"), null, "an alternate data stream"); + Check.Eq(R(".."), null, "the parent folder itself"); + Check.Eq(R("."), null, "the folder itself"); + Check.Eq(R(" "), null, "blank"); + } + + /// The player, two carried motes, an NPC and (optionally) a player named like it. + private static (ExpressionEngine E, WorldObjectCache Cache) World(bool withImitator, bool withNpc = true) + { + FakeHost.Reset(); + FakeHost.GiveCalls = true; + FakeHost.SalvageCalls = true; // MoveItemExternal recorded: it must not be used + FakeHost.Names[Player] = "Giver"; + FakeHost.PlayerIdValue = Player; + FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f); + FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f); + if (withImitator) + { + FakeHost.Names[Imitator] = "Town Crier"; + FakeHost.Positions[Imitator] = (0x1048002Au, 100.5f, 100f, 0f); + FakeHost.ItemTypes[Imitator] = 0x10; // a creature + FakeHost.Bitfields[Imitator] = 0x18; // BF_PLAYER | BF_ATTACKABLE + } + if (withNpc) + { + FakeHost.Names[Npc] = "Town Crier"; + FakeHost.Positions[Npc] = (0x1048002Au, 101f, 100f, 0f); + FakeHost.ItemTypes[Npc] = 0x10; + FakeHost.NotAttackable.Add(Npc); + FakeHost.Bitfields[Npc] = 0x4; // not a player, not attackable + } + foreach (uint id in new[] { Mote1, Mote2 }) + { + FakeHost.Names[id] = "Mana Mote"; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x80; + } + var host = FakeHost.Create(playerId: Player); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + foreach (uint id in new[] { Imitator, Npc, Mote1, Mote2 }) + if (FakeHost.Names.ContainsKey(id)) cache.OnCreateObject(id); + cache.Tick(); + + // One rule with no conditions keeps everything. + Directory.CreateDirectory(ExpressionEngine.ItemGiverDir); + var p = new LootProfile { Name = "give all" }; + p.Rules.Add(new LootRule { Name = "All", Action = LootAction.Keep }); + p.Save(Path.Combine(ExpressionEngine.ItemGiverDir, "giveall.json")); + + var e = ExpressionTests.Engine(host, playerId: Player); + e.SetObjectCache(cache); + return (e, cache); + } + + // Backticks: an unquoted name with a space doesn't reach the action as one argument. + private const string GiveExpr = "actiontrygiveprofile[`giveall.json`,`Town Crier`]"; + + private static void NpcOnly() + { + var (e, _) = World(withImitator: true); + Check.Eq(e.Evaluate(GiveExpr), "1", "an item was given"); + Check.True(FakeHost.Gives.Count == 1 && FakeHost.Gives[0].Target == Npc, "to the NPC, past the player of that name"); + Check.True(FakeHost.Gives.Count == 1 && FakeHost.Gives[0].Amount == 0, "the whole object"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "never MoveItemExternal (an NPC ignores it)"); + + var (e2, _) = World(withImitator: true, withNpc: false); + Check.Eq(e2.Evaluate(GiveExpr), "0", "only a player has the name: nothing"); + Check.Eq(FakeHost.Gives.Count, 0, "nothing given to the player"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nor moved to them"); + } + + private static void RefusedPathLoggedOnce() + { + var (e, _) = World(withImitator: false); + // The profile exists one folder up: only the path rule refuses it. + File.Copy(Path.Combine(ExpressionEngine.ItemGiverDir, "giveall.json"), + Path.Combine(ExpressionEngine.ItemGiverDir, "..", "giveall.json"), overwrite: true); + for (int i = 0; i < 3; i++) + Check.Eq(e.Evaluate("actiontrygiveprofile[`../giveall.json`,`Town Crier`]"), "0", $"pulse {i + 1}: refused"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("refused profile '../giveall.json'")), 1, "logged once, with the argument"); + Check.Eq(FakeHost.Gives.Count, 0, "nothing given"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs new file mode 100644 index 0000000..e3c8390 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs @@ -0,0 +1,39 @@ +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/LauncherSwapTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LauncherSwapTests.cs new file mode 100644 index 0000000..9635ed3 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LauncherSwapTests.cs @@ -0,0 +1,277 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Mixed launchers (2026-10-12): a crossbow with quarrels to a bow with arrows. The log of +// 2026-10-11 14:45:11-17 took 6.4 s and flickered the stance Missile/peace/Melee: combat asked +// for Missile mode while the bow (or its arrows) wasn't on, and each step waited the swap gate's +// full 3 s. Now no stance request goes out until the launcher and its ammo are on, and the +// launcher goes 400 ms after the quarrels read off. +internal static class LauncherSwapTests +{ + private const uint Player = 0x50000C01; + private const uint Monster = 0x80001001; + private const uint Wcid = 434344; + private const uint Crossbow = 0x80000601, Bow = 0x80000602, Quarrels = 0x80000603, Arrows = 0x80000604; + private const uint Pack = 0x80000501; + private const int MissileSlot = 0x00400000, AmmoSlot = 0x00800000; + private const int PropAmmoType = 50, PropStack = 12, PropMaxStack = 11; + + public static void Register(Runner r) + { + r.Add("launcher swap: no stance request until the launcher and its ammo are on", NoStanceMidSwap); + r.Add("launcher swap: the launcher goes once the old ammo reads off (not 3 s + 2 s)", ShortWaitAfterAmmoOff); + r.Add("launcher swap: from peace mode the dequip still holds the stance", PeaceStartHoldsStance); + r.Add("swap gate: MoveDone lets the next swap go on the server's answers", GateMoveDone); + r.Add("swap holds: a nearly dead target keeps the crossbow (nothing of the swap started)", LowHealthKeepsLauncher); + r.Add("swap holds: a swap under way finishes even when the target gets low (quarrels already off)", LowHealthMidSwapFinishes); + r.Add("swap holds: a lock after a kill swaps at once; a switch from a live target waits", SettleOnlyAfterSwitch); + } + + /// + /// WeaponSwapSettleMs (2026-10-15): Kelpie's logs had 22 of 25 settle holds swap anyway within + /// 3 s, nearly all on a fresh lock after a kill. Only a switch from another live target waits. + /// + private static void SettleOnlyAfterSwitch() + { + var rig = new Rig(CombatMode.Missile); + rig.Lock(Monster, wasSwitch: false); + Check.False(rig.Tick(0), "fresh lock 0 ms ago: the swap starts"); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "the quarrels go into the pack at once"); + Check.False(FakeHost.Logs.Any(l => l.Contains("not swapping")), "no settle hold logged"); + + rig = new Rig(CombatMode.Missile); + rig.Lock(Monster, wasSwitch: true); + Check.False(rig.Tick(0), "switched 0 ms ago: the attack waits for the target to settle"); + Check.Eq(FakeHost.Moves.Count, 0, "nothing of the swap started"); + Check.Eq(FakeHost.Uses.Count, 0, "no bow wield"); + Check.True(FakeHost.Logs.Any(l => l.Contains("not swapping") && l.Contains("target switched")), "the hold says why"); + + rig.S.WeaponSwapSettleMs = 0; + rig.Tick(100); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "setting 0: the swap starts"); + } + + /// WeaponSwapMinHealthPct: no swap starts onto a target at 25% or less. + private static void LowHealthKeepsLauncher() + { + var rig = new Rig(CombatMode.Missile); + rig.Cache.OnUpdateHealth(Monster, 0.2f); + Check.True(rig.Tick(0), "target at 20%: fight on with the crossbow"); + Check.Eq(FakeHost.Moves.Count, 0, "the quarrels stay on"); + Check.Eq(FakeHost.Uses.Count, 0, "no bow wield"); + Check.True(FakeHost.Logs.Any(l => l.Contains("not swapping") && l.Contains("20% health")), "the hold is logged"); + + rig.S.WeaponSwapMinHealthPct = 0; + rig.Tick(100); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "setting off: the swap starts"); + } + + /// + /// The ammo fix (2026-10-12) must hold: once the quarrels went into the pack, a hold rule may + /// not keep the crossbow (it would stand there with no ammo on); the bow goes on as planned. + /// + private static void LowHealthMidSwapFinishes() + { + var rig = new Rig(CombatMode.Missile); + rig.C.AmmoOffSettleMs = 0; + Check.False(rig.Tick(0), "full health: the swap starts"); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "the quarrels go into the pack"); + + rig.Cache.OnUpdateHealth(Monster, 0.1f); + Rig.Unwield(Quarrels); + FakeHost.CombatModeValue = CombatMode.NonCombat; + Check.False(rig.Tick(500), "quarrels off, target at 10%: still not ready"); + Check.Eq(FakeHost.Uses.LastOrDefault(), Bow, "the bow goes on anyway"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request until the bow and arrows are on"); + + rig.Landed(Bow, Crossbow, MissileSlot); + rig.Tick(1000); + Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "then its arrows"); + } + + // ── The rig ─────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S = new(); + public readonly CombatManager C; + public readonly MonsterDamageStore Store = new(); + public readonly WorldObject Target; + public readonly WeaponSwapGate Gate; + public readonly WorldObjectCache Cache; + public long T; + public int InHand; + private readonly MethodInfo _equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", BindingFlags.Instance | BindingFlags.NonPublic)!; + + public Rig(int startMode) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = startMode; + Item(Crossbow, "Heavy Crossbow", MissileSlot, ammoType: 2); + Item(Bow, "Longbow", MissileSlot, ammoType: 1); + Item(Quarrels, "Quarrel", AmmoSlot, ammoType: 2, stack: true); + Item(Arrows, "Arrow", AmmoSlot, ammoType: 1, stack: true); + Wield(Crossbow, MissileSlot); + Wield(Quarrels, AmmoSlot); + FakeHost.Wcids[Monster] = Wcid; + var host = FakeHost.Create(); + var cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, Bow, Quarrels, Arrows }); + Cache = cache; + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, Store); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + C.SetCharacterSkills(skills); + C.CanCastOverride = _ => false; + InHand = unchecked((int)Crossbow); + C.InHandOverride = () => InHand; + C.OpenPackOverride = () => unchecked((int)Pack); + C.OffhandReadMs = 0; + C.SwapTracker.MinDwellMs = 0; + // The live gate's settings, on a test clock; the server answers at once. + Gate = new WeaponSwapGate { MinIntervalMs = 3000, NowMs = () => T, ServerIdle = () => true, IsWielded = _ => false }; + C.SetWeaponSwapGate(Gate); + Target = new WorldObject(unchecked((int)Monster), "Test Dummy", AcObjectClass.Monster); + S.ItemRules = new[] { Crossbow, Bow }.Select(i => new ItemRule + { + Id = unchecked((int)i), Name = FakeHost.Names[i], Element = "", ElementSource = "", Action = "Weapon", + }).ToList(); + Store.SetManualWeapon(Wcid, Bow); // the Damage tab says the bow + } + + private static void Item(uint id, string name, int validSlots, int ammoType, bool stack = false) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = 0x100; // MissileWeapon + FakeHost.Ints[(id, 9)] = validSlots; + FakeHost.Ints[(id, PropAmmoType)] = ammoType; + if (stack) { FakeHost.Ints[(id, PropStack)] = 100; FakeHost.Ints[(id, PropMaxStack)] = 250; } + } + + public static void Wield(uint id, int slot) => FakeHost.Ints[(id, 10)] = slot; + public static void Unwield(uint id) => FakeHost.Ints.Remove((id, 10)); + + /// One combat equip tick at on the gate's clock; true = ready to attack. + public bool Tick(long atMs) + { + T = atMs; + return (bool)_equip.Invoke(C, new object[] { Target, "Auto" })!; + } + + /// Combat locked just now (a switch from another live target or not). + public void Lock(uint target, bool wasSwitch) + { + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(CombatManager).GetField("_lockedTargetId", F)!.SetValue(C, unchecked((int)target)); + typeof(CombatManager).GetField("_targetLockedAt", F)!.SetValue(C, DateTime.Now); + typeof(CombatManager).GetField("_lockWasSwitch", F)!.SetValue(C, wasSwitch); + } + + public void Landed(uint weapon, uint old, int slot) + { + Unwield(old); + Wield(weapon, slot); + InHand = unchecked((int)weapon); + } + } + + // ── Tests ──────────────────────────────────────────────────────────────── + + private static void NoStanceMidSwap() + { + var rig = new Rig(CombatMode.Missile); + rig.C.AmmoOffSettleMs = 0; + + Check.False(rig.Tick(0), "tick 1: not ready"); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "the quarrels go into the pack first"); + Check.Eq(FakeHost.Uses.Count, 0, "no bow wield with the quarrels on"); + + // The server takes the quarrels and drops the character to peace mode. + Rig.Unwield(Quarrels); + FakeHost.CombatModeValue = CombatMode.NonCombat; + Check.False(rig.Tick(500), "quarrels off: the bow wield goes out"); + Check.Eq(FakeHost.Uses.LastOrDefault(), Bow, "UseObject(bow)"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request with the bow not on (was the flicker)"); + for (int i = 1; i <= 3; i++) rig.Tick(500 + i * 100); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "none while the bow's wield is in flight"); + + rig.Landed(Bow, Crossbow, MissileSlot); + Check.False(rig.Tick(1000), "bow in hand: the arrows go on"); + Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "UseObject(arrows)"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request before the arrows are on"); + + Rig.Wield(Arrows, AmmoSlot); + Check.False(rig.Tick(1500), "bow and arrows: the stance goes out"); + Check.True(FakeHost.CombatModeRequests.SequenceEqual(new[] { CombatMode.Missile }), "exactly one Missile request, after the arrows"); + FakeHost.CombatModeValue = CombatMode.Missile; + Check.True(rig.Tick(2500), "in Missile mode: ready to shoot"); + } + + private static void ShortWaitAfterAmmoOff() + { + var rig = new Rig(CombatMode.Missile); + rig.Tick(0); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "the quarrels go into the pack"); + + Rig.Unwield(Quarrels); + FakeHost.CombatModeValue = CombatMode.NonCombat; + rig.Tick(150); + Check.Eq(FakeHost.Uses.Count, 0, "just read off: the 400 ms settle"); + + // The settle passed (the test can't wait on the wall clock): the launcher goes far inside + // the gate's 3 s and the old 2 s equip pacing. + rig.C.AmmoOffSettleMs = 0; + rig.Tick(600); + Check.Eq(FakeHost.Uses.LastOrDefault(), Bow, "the bow at 0.6 s (was 3.0 s)"); + + rig.Landed(Bow, Crossbow, MissileSlot); + rig.Tick(1100); + Check.Eq(FakeHost.Uses.LastOrDefault(), Arrows, "the arrows at 1.1 s (was 6.0 s)"); + Check.Eq(FakeHost.Moves.Count, 1, "one pack move in all"); + } + + private static void PeaceStartHoldsStance() + { + // Peace mode with the crossbow and quarrels on: the not-wielded branch dequips; its stance + // request (sent with any wield before) is held for the whole swap. + var rig = new Rig(CombatMode.NonCombat); + rig.C.AmmoOffSettleMs = 0; + Check.False(rig.Tick(0), "not ready"); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Quarrels, "the quarrels go into the pack"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request with the wrong ammo on"); + Check.True(FakeHost.Logs.Any(l => l.Contains("stance held")), "the hold is logged"); + + Rig.Unwield(Quarrels); + rig.Tick(500); + Check.Eq(FakeHost.Uses.LastOrDefault(), Bow, "then the bow"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "still no Missile request"); + } + + private static void GateMoveDone() + { + long t = 0; + var g = new WeaponSwapGate { NowMs = () => t, ServerIdle = () => true, IsWielded = _ => false }; + Check.True(g.TryBeginSwap("ammo off"), "first swap"); + g.NoteMove(7, wieldedNow: true); + t = 500; + Check.False(g.TryBeginSwap("launcher"), "a noted move: held"); + g.MoveDone(8); + Check.False(g.TryBeginSwap("launcher"), "another item's MoveDone changes nothing"); + g.MoveDone(7); + Check.True(g.TryBeginSwap("launcher"), "MoveDone: the launcher goes at 0.5 s"); + t = 700; + Check.False(g.TryBeginSwap("ammo"), "under the 400 ms floor"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs index 0ae474c..52c83a7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs @@ -49,12 +49,16 @@ internal static class LootCorpseTests r.Add("loot chain: without GetContainerContents an unseen item stays unseen (no crash)", UnseenItemOldEngine); r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation); r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce); + r.Add("boost loot: our kill holds the next target until its corpse is looted (one kill, one loot)", BoostLootOneKillOneLoot); + r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits); + r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse); r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot); r.Add("corpse close: a finished corpse is closed once (CloseContainer, API v76)", FinishedCorpseClosedOnce); r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine); r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed); r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse); r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation); + r.Add("loot: a pack that takes none of an item's tries is left out; the item tries another, else looting stops", RefusingPackIsLeftOut); r.Add("loot pacing: no pickup (first or retry) while the server owes an answer to a cast; it goes on the UseDone", PickupWaitsForCastAnswer); r.Add("corpse close: not while the last item is between the corpse and the pack - it closes once the item is in the inventory", CloseWaitsForInventory); r.Add("loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait", MergedPickupConfirmedQuickly); @@ -396,6 +400,113 @@ internal static class LootCorpseTests Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "so looting has the tick without needing a starved turn"); } + // ── Boost Loot Priority: one kill, one loot (2026-10-14, Kelpie: the next target was locked + // 6 ms after each kill, the corpse came 3 s later, and corpses were looted in batches) ── + + /// + /// A monster away, Boost Loot Priority on, and combat's + /// HoldNewTarget wired to the plugin. The corpse is created only with . + /// + private static Bot BoostWorld(float monsterMeters, bool withCorpse, out CombatManager combat, bool boost = true) + { + BaseWorld(corpsePositioned: true); + FakeHost.Names[Monster] = "Ancient Water Elemental"; + FakeHost.ItemTypes[Monster] = ItemTypeCreature; + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + monsterMeters, Me0.Y + 0.5f, Me0.Z); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.EnableCombat = true; + bot.S.MonsterRange = 50; + bot.S.BoostLootPriority = boost; + if (withCorpse) bot.Cache.OnCreateObject(Corpse); + _ = bot.Cache[unchecked((int)Monster)]; + bot.Cache.OnUpdateHealth(Monster, 1f); + bot.Cache.Tick(); + combat = new CombatManager(host, bot.S, bot.Cache); + combat.SetPlayerId(Player); + typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue); + combat.ScanNearbyTargets(); + bot.Set("_combatManager", combat); + combat.HoldNewTarget = () => (bool)bot.Call("BoostLootHoldsNewTarget")!; + return bot; + } + + private static void BoostLootOneKillOneLoot() + { + var bot = BoostWorld(15f, withCorpse: false, out var combat); + Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "no kill, no corpse: nothing to wait for"); + + // The kill lands; the corpse doesn't exist yet (ACE creates it after the death animation). + bot.Call("NoteBoostLootKill"); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, 0, "the next monster (15 m) is not locked while the corpse forms"); + Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] next target waits: Boost Loot Priority")), "said once"); + Check.True(bot.HasLootWork(), "the forming corpse is loot work"); + Check.False(combat.IsUnderCloseAttack, "nothing locked, nothing close: not engaged"); + var waiting = new ArbiterInputs(true, false, combat.HasEngageableTarget, true, false, true, + combatEngaged: combat.IsUnderCloseAttack, boostLoot: true); + Check.Eq(ActivityArbiter.Decide(in waiting), BotActivity.Looting, "so the arbiter gives Looting the tick"); + + // The corpse arrives: it is claimed and opened before the next fight. + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + Check.True(bot.HasLootWork(), "the kill's corpse is lootable"); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, 0, "still no new target with the corpse in range"); + bot.Tick(BotActivity.Looting); + Check.Eq(bot.Get("_targetCorpseId"), unchecked((int)Corpse), "the corpse is claimed"); + Check.True(FakeHost.Uses.Contains(Corpse), "and opened"); + } + + private static void BoostLootHoldLimits() + { + // The corpse never comes: the wait runs out and the next monster is locked. + var bot = BoostWorld(15f, withCorpse: false, out var combat); + bot.Call("NoteBoostLootKill"); + bot.Set("_boostLootKillAt", Environment.TickCount64 - RynthAiPlugin.BoostLootKillWaitMs - 1); + Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "past BoostLootKillWaitMs: no hold"); + combat.HandleCombatTrigger(); + Check.Eq(combat.activeTargetId, unchecked((int)Monster), "the next monster is locked"); + + // A monster within 5 yd is fought at once. + var close = BoostWorld(2f, withCorpse: false, out var combat2); + close.Call("NoteBoostLootKill"); + combat2.HandleCombatTrigger(); + Check.Eq(combat2.activeTargetId, unchecked((int)Monster), "a monster at 2 m: locked, the corpse waits"); + + // Boost Loot off: the old order (combat first) is unchanged. + var off = BoostWorld(15f, withCorpse: false, out var combat3, boost: false); + off.Call("NoteBoostLootKill"); + Check.False(off.HasLootWork(), "no forming-corpse loot work without Boost Loot"); + combat3.HandleCombatTrigger(); + Check.Eq(combat3.activeTargetId, unchecked((int)Monster), "the next monster is locked at once"); + + // Rare-only looting: most kills leave nothing to wait for. + var rare = BoostWorld(15f, withCorpse: false, out var combat4); + rare.S.LootOnlyRareCorpses = true; + rare.Call("NoteBoostLootKill"); + combat4.HandleCombatTrigger(); + Check.Eq(combat4.activeTargetId, unchecked((int)Monster), "Loot Only Rare Corpses: no wait"); + } + + private static void BoostLootWaitEndsOnKillCorpse() + { + var bot = BoostWorld(15f, withCorpse: false, out _); + var waiting = bot.Get>("_corpseWaitingSince"); + const int Older = 0x0BADC0DE, Fresh = 0x0BADF00D; + + bot.Call("NoteBoostLootKill"); + long kill = bot.Get("_boostLootKillAt"); + waiting[Older] = kill - 5000; + bot.Call("EndBoostLootKillWait", Older); + Check.Eq(bot.Get("_boostLootKillAt"), kill, "a corpse from an earlier kill doesn't end the wait"); + + waiting[Fresh] = kill + 1500; + bot.Call("EndBoostLootKillWait", Fresh); + Check.Eq(bot.Get("_boostLootKillAt"), 0L, "the kill's corpse (first seen after it) ends the wait"); + Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "so combat goes on at once"); + } + private static void HeldByCombatLoggedOnce() { var bot = StarvationWorld(15f, out _); @@ -541,20 +652,58 @@ internal static class LootCorpseTests } Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes out once the character is still"); + // The bot's Loot Retry Timeout (the LootBaseline default). + int retryWindowMs = bot.S.LootRetryTimeoutMs; + // Its own bend-down plays for longer than 3 retry windows: no retry, no give-up. FakeHost.CastBusy = 1; - TickFor(bot, 1800); + TickFor(bot, retryWindowMs * 3 + 300); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while the pickup animates"); Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "the item is not given up on"); // Still again and the item still on the corpse: the retry window starts now. FakeHost.CastBusy = 0; - TickFor(bot, 250); + TickFor(bot, retryWindowMs / 2); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still"); - TickFor(bot, 500); + TickFor(bot, retryWindowMs); Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry"); } + // 2026-10-15, Drakkon: every item went to one pack the server wouldn't take loot into (its + // contents unknown to the client), 3 tries each, and every item on every corpse was skipped. + // A pack that takes none of an item's tries now counts as full for a while: the item gets one + // more round into another pack, and with none left looting stops with the pack-full message. + private static void RefusingPackIsLeftOut() + { + var refusals = new RynthCore.Plugin.RynthAi.Loot.PackRefusals(); + refusals.Refuse(7, 1000); + Check.True(refusals.IsRefused(7, 1000 + RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs - 1), "refused for the hold"); + Check.False(refusals.IsRefused(7, 1000 + RynthCore.Plugin.RynthAi.Loot.PackRefusals.HoldMs), "then tried again"); + refusals.Refuse(8, 0); + refusals.Accepted(8); + Check.False(refusals.IsRefused(8, 1), "an item landing there ends the hold"); + + BaseWorld(corpsePositioned: true); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.Cache.OnCreateObject(Corpse); + bot.Cache.Tick(); + bot.Tick(BotActivity.Looting); + bot.Cache.OnCreateObject(Gem); + bot.Cache.Tick(); + bot.P.OnViewObjectContents(Corpse); + + // The main pack (the only destination here) never takes the gem: it stays on the corpse. + int retryWindowMs = bot.S.LootRetryTimeoutMs; + TickFor(bot, retryWindowMs * 4 + 600); + Check.True(FakeHost.ExternalMoves.Count(m => m.Id == Gem) >= 3, "three tries into the main pack"); + Check.True(FakeHost.ExternalMoves.Where(m => m.Id == Gem).All(m => m.Target == Player), "all into the main pack"); + Check.True(FakeHost.Logs.Any(l => l.Contains("took none of 3 tries") && l.Contains("trying another pack")), "the refusing pack is left out, said once"); + Check.True(FakeHost.Logs.Any(l => l.Contains("no pack has a free slot")), "no other pack: the corpse is left"); + Check.True(FakeHost.Chat.Any(l => l.Contains("Pack full")), "and the player is told"); + Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "not three more wasted tries into the same pack"); + } + // A pickup sent while Bloodstone Bolt VII was unanswered came back // "too busy" (ACE refuses a pickup while IsBusy); the assess-timeout path skips the busy gate. private static void PickupWaitsForCastAnswer() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs index 3daf2e5..f56e441 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs @@ -21,6 +21,9 @@ 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 }, @@ -35,7 +38,7 @@ 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; ILT verbs say RynthILT is needed", Commands); + 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: the pyreal refill path never spends without RynthILT's confirmation", RefillNeedsIlt); 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); @@ -123,9 +126,30 @@ internal static class MiniRemoteMoveTests Check.True(c.HandleCommand("pets", new[] { "show" }), "pets show"); 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.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"); + 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"); + 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 quests|pets")), "and lists what RynthAi still has"); + 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"); + 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"); + Check.True(FakeHost.Chat.Any(x => x.Contains("RynthOracle") && x.Contains("/ro timers")), "it points to RynthOracle"); + FakeHost.Chat.Clear(); + Check.True(c.HandleCommand("quests", new[] { "window" }), "quests window is answered"); + Check.True(FakeHost.Chat.Any(x => x.Contains("RynthOracle")), "with the same note"); + FakeHost.Chat.Clear(); + 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"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs index 9c52b8e..25ab972 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs @@ -40,6 +40,7 @@ internal static class PluginFixTests r.Add("selection: creature classes are Monster, Player, Npc and CombatPet only", CreatureClasses); r.Add("fellowship name read: ReadableBytesFrom ends at the page whose neighbour is PAGE_NOACCESS", ReadableBytesAtGuardPage); r.Add("fellowship name read: it stops at 64 characters and at the end of the probed bytes", NameReadBounded); + r.Add("fellowship table: an ACECustom 29-member fellowship is read, torn headers are not", FellowshipTableSizes); } // -- Selection ------------------------------------------------------------ @@ -161,6 +162,20 @@ internal static class PluginFixTests finally { Marshal.FreeHGlobal(buf); } } + private static void FellowshipTableSizes() + { + const int Buckets = 0x1000; // any non-zero bucket array address + Check.True(FellowshipTracker.IsPlausibleTable(Buckets, 16, 9), "a full retail fellowship (9)"); + Check.True(FellowshipTracker.IsPlausibleTable(Buckets, 64, 29), "an Infinite Leaftide fellowship (29, ACECustom MaxFellows)"); + Check.True(FellowshipTracker.IsPlausibleTable(Buckets, 1, 1), "one member, one bucket"); + Check.False(FellowshipTracker.IsPlausibleTable(0, 16, 3), "no bucket array"); + Check.False(FellowshipTracker.IsPlausibleTable(Buckets, 0, 3), "no buckets"); + Check.False(FellowshipTracker.IsPlausibleTable(Buckets, 16, 0), "no members"); + Check.False(FellowshipTracker.IsPlausibleTable(Buckets, FellowshipTracker.MaxBuckets + 1, 3), "a torn bucket count"); + Check.False(FellowshipTracker.IsPlausibleTable(Buckets, 16, FellowshipTracker.MaxMembers + 1), "a torn member count"); + Check.False(FellowshipTracker.IsPlausibleTable(Buckets, -5, 3), "a negative bucket count"); + } + private static void Land(uint id, string name) { FakeHost.Names[id] = name; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs new file mode 100644 index 0000000..37679d1 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using System.Linq; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthAi.Huds; +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.RynthAiTests.Harness; + +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. +internal static class SectionsTests +{ + public static void Register(Runner r) + { + r.Add("sections: V and X lines parse; groups unchanged", ParsesVerdicts); + r.Add("sections: the engine verdict is looked up case-insensitively, and goes away with an older payload", VerdictLookup); + r.Add("sections: RynthAi's manifest passes the engine parser unchanged", ManifestRoundTrip); + r.Add("sections: the engine catalog places RynthAi's views by server", CatalogPlacement); + r.Add("sections: tab surfaces map back to their tabs; foreign ids are refused", SurfaceRoundTrip); + r.Add("sections: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedTabRedirects); + } + + private static void MovedTabRedirects() + { + foreach (string tab in new[] { "character", "Char", " rates " }) + Check.Eq(MovedTabs.CommandFor(tab), MovedTabs.OracleCharacter, tab + " -> RynthOracle's Character tab"); + foreach (string tab in new[] { "charms", "banking", "gear", "games", "pets", "crafting", "", null }) + Check.True(MovedTabs.CommandFor(tab) == null, (tab ?? "null") + " is still a Mini Remote tab (or none)"); + Check.Eq(MovedTabs.OracleCharacter, "/ro character", "the Oracle command"); + Check.Eq(MovedTabs.Diagnostics, "/rc diagnostics", "the engine's Diagnostics command"); + } + + private const string Payload = + "V\tilt\tInfinite Leaftide\t1\ton\t0\n" + + "V\taelrynth\tAelrynth\t0\tauto\t0\n" + + "X\tchar\tChar\n" + + "X\tgames\tGames\n" + + "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); + Check.Eq(p.Servers.Length, 2, "two verdicts"); + Check.Eq(p.Servers[0].Id, "ilt", "first verdict id"); + Check.True(p.Servers[0].Active, "ILT active"); + Check.Eq(p.Servers[0].Force, "on", "ILT forced on"); + Check.False(p.Servers[0].Detected, "ILT not detected (forced)"); + Check.False(p.Servers[1].Active, "Aelrynth inactive"); + Check.Eq(p.Sections.Length, 2, "two sections"); + Check.Eq(p.Sections[1].Id, "games", "rail order kept"); + Check.Eq(p.Groups.Length, 1, "one server group"); + Check.Eq(p.Groups[0].Items.Single().Command, "/rc progression", "the group's item"); + + ServerMenuPayload junk = ServerMenuModel.ParsePayload("V\tilt\n" + "X\t\t\n" + "V\tx\ty\tmaybe\tauto\t1\n"); + Check.Eq(junk.Groups.Length, 0, "no groups from junk"); + Check.True(junk.Servers.Length <= 1, "short verdict lines skipped"); + } + + private static void VerdictLookup() + { + try + { + ServerMenuModel.Apply(Payload.Replace("V\tilt\tInfinite Leaftide\t1\ton\t0", "V\tilt\tInfinite Leaftide\t0\toff\t1")); + Check.Eq(ServerMenuModel.ServerActive("ILT"), false, "verdict lookup is case-insensitive"); + Check.Eq(ServerMenuModel.Server("ilt")?.Force, "off", "the override comes with it"); + + ServerMenuModel.Apply(Payload); + Check.Eq(ServerMenuModel.ServerActive("ilt"), true, "forced on"); + + // An older RynthCore: groups only, no verdicts (a server is forced in RynthCore's + // Options > Diagnostics, not from the Mini Remote, since 2026-10-13). + ServerMenuModel.Apply("S\tilt\tInfinite Leaftide\t1\t/rc ilt on\n"); + Check.True(ServerMenuModel.ServerActive("ilt") == null, "no verdicts: none to follow"); + } + finally { ServerMenuModel.Apply(string.Empty); } + } + + private static List SomeViews() => SectionsManifest.Views(IltTabs); + + 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"); + + 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"); + for (int i = 0; i < views.Count; i++) + { + SectionsManifest.View v = views[i]; + SectionContribution c = m.Contributions.Single(x => x.Surface == v.Surface && x.Section == v.Section); + Check.Eq(c.Label, v.Label, "label " + v.Surface); + Check.Eq(c.Server, v.Server, "server " + v.Surface); + Check.Eq(c.Primary, v.Primary, "primary " + v.Surface); + 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() + { + SectionManifest m = SectionManifestParser.Parse("RynthAi", SectionsManifest.Build(SomeViews(), SectionsManifest.OwnSections), out _); + var iltOn = new ServerState("ilt", "Infinite Leaftide", true, true, ServerForce.Auto, true, ""); + var iltOff = iltOn with { Active = false }; + + List off = SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOff }); + Check.True(off.Single(v => v.Id == "pets").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.PetsSurface), + "Pets everywhere"); + Check.True(off.Single(v => v.Id == "crafting").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.CraftingSurface), + "Crafting everywhere"); + Check.False(off.Any(v => v.Id == "quests"), "no Quests section of RynthAi's"); + Check.False(off.Any(v => v.Id == "games"), "no Games off ILT"); + SectionView charOff = off.Single(v => v.Id == "char"); + Check.Eq(charOff.Label, SectionCatalog.SessionStatsLabel, "the char section is Session Stats"); + Check.True(charOff.Panes.Length == 1 && charOff.Panes[0].Contribution?.Surface == SectionsManifest.SessionSurface, + "Session Stats: RynthAi's session view replaces the engine overview"); + + 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.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"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SelfRatingsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SelfRatingsTests.cs new file mode 100644 index 0000000..fad3a30 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SelfRatingsTests.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Item Info on yourself (/ra iteminfo me, select or click yourself): the rating totals the server +// puts in a self-identify (AppraiseInfo.AddRatings) and the login-sent luminance augs, as chat lines. +internal static class SelfRatingsTests +{ + public static void Register(Runner r) + { + r.Add("self ratings: totals, other ratings and lum augs in Item Info's tags", Totals); + r.Add("self ratings: zeros are left out; nothing known still prints a header", Empty); + r.Add("self ratings: not identified is flagged; one-line layout joins with |", NotIdentifiedOneLine); + } + + private static System.Func Reader(Dictionary ints) + => stype => ints.TryGetValue(stype, out int v) ? v : 0; + + private static void Totals() + { + var ints = new Dictionary + { + [307] = 45, [308] = 30, [313] = 10, [314] = 20, [315] = 5, [316] = 15, + [323] = 8, [331] = 12, [351] = 4, + [333] = 5, [334] = 5, [341] = 50, + }; + List lines = SelfRatings.Build("Silentkelpie", Reader(ints), identified: true, oneLine: false); + Check.Eq(lines.Count, 3, "header, other ratings, lum augs (no PK line)"); + Check.Eq(lines[0], "Silentkelpie's ratings: D 45, DR 30, C 10, CD 20, CR 5, CDR 15", "combat totals in Item Info order"); + Check.Eq(lines[1], "HB 8, NR 12, LR 4", "healing and resists"); + Check.Eq(lines[2], "Lum augs (in the totals): D +5, DR +5, V +50", "lum augs signed"); + foreach (string l in lines) + foreach (char c in l) + Check.True(c >= 0x20 && c <= 0x7E, "plain ASCII: " + l); + } + + private static void Empty() + { + List lines = SelfRatings.Build("", Reader(new Dictionary { [307] = 0 }), identified: true, oneLine: false); + Check.Eq(lines.Count, 1, "only the header"); + Check.Eq(lines[0], "Your ratings: no combat ratings", "no name: 'Your'"); + + List pk = SelfRatings.Build("Pk", Reader(new Dictionary { [381] = 3, [382] = -2 }), true, false); + Check.Eq(pk[1], "PK: PKD 3, PKDR -2", "PK line, negative kept"); + } + + private static void NotIdentifiedOneLine() + { + var ints = new Dictionary { [307] = 7, [337] = 2 }; + List lines = SelfRatings.Build("Me", Reader(ints), identified: false, oneLine: true); + Check.Eq(lines.Count, 1, "one line"); + Check.Eq(lines[0], "Me's ratings: D 7 (not identified - totals may be incomplete) | Lum augs (in the totals): SE +2", + "flag on the header, parts joined"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs index ecc70ad..78a521a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs @@ -13,15 +13,16 @@ internal static class ServerMenuTests r.Add("server menu: sections and items parse in order", ParsesSections); r.Add("server menu: malformed lines are skipped, never thrown", SkipsMalformed); r.Add("server menu: tab features name the Mini Remote tab", TabFeature); - r.Add("mini remote tabs: Quests and Pets are RynthAi's and first; the ILT tabs come from RynthILT", UniversalTabs); + r.Add("mini remote tabs: Pets and Crafting are RynthAi's and first (Quests moved to RynthOracle); the ILT tabs come from RynthILT", UniversalTabs); } private static void UniversalTabs() { var tabs = RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteTabs.Universal; - Check.Eq(tabs.Length, 2, "RynthAi's own tabs: Quests and Pets (the ILT tabs are RynthILT's)"); - Check.Eq(tabs[0], "quests", "Quests leads the tab bar"); - Check.Eq(tabs[1], "pets", "Pets second"); + Check.Eq(tabs.Length, 2, "RynthAi's own tabs: Pets and Crafting (the ILT tabs are RynthILT's)"); + Check.Eq(tabs[0], "pets", "Pets leads the tab bar"); + Check.Eq(tabs[1], "crafting", "Crafting second (tinker benches and Rings work on any server)"); + Check.Null(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteTabs.Parse("quests"), "no Quests tab: RynthOracle has it (2026-10-13)"); Check.Eq(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteTabs.Parse("Pet"), "pets", "aliases parse"); Check.Null(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteTabs.Parse("banking"), "an ILT tab isn't RynthAi's"); Check.Null(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteTabs.Parse("guardian"), "nor the Guardian panel"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs new file mode 100644 index 0000000..495d46e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.Plugin.RynthAi.MiniRemote.Crafting; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Crafting tab's tinkering (SilentKelpie's, 2026-10-12): ACE's retail chance +// (RecipeManager.GetTinkerChance), the planner's caps and order (imbue once, rend last), bag +// matching / choice, and the universal Crafting tab id. Server rows come from the server plugin's +// profile ("salvage", ServerSalvageView) and carry their own rules, checked here on rows shaped +// like Infinite Leaftide's (RynthILT serves those; RynthILT.Tests checks its data): no tink slot, +// applied ints, stack groups (Steel + Serpentine 10), after-cap rows (Leather), an own order, and +// prepared rows (tier bags, Ammunition). +internal static class TinkerTests +{ + public static void Register(Runner r) + { + r.Add("tinker: retail difficulty and chance (ACE GetTinkerChance)", Chance); + r.Add("tinker: slot cap, one imbue, attempts this run", SlotsAndImbue); + r.Add("tinker: damage-type rend and rend last", Rend); + r.Add("tinker: server weapon rows (no slot, an after-cap row last only when the slots are full)", AfterCap); + r.Add("tinker: server jewelry rows (applied ints skip, a stack group shares one cap)", StackAndApplied); + r.Add("tinker: item rows (Moonstone, Leather, Sandstone)", ItemRows); + r.Add("tinker: scan filters", Filters); + r.Add("tinker: bag matching (full, Abyssal, Foolproof)", Bags); + r.Add("tinker: bag choice by chance and minimum", BagChoice); + r.Add("tinker: Crafting is a universal Mini Remote tab", Section); + r.Add("tinker: prepared server rows (applied ints, order, tier bags, Ammunition)", Trinkets); + r.Add("tinker: a server plugin's salvage (per tab, own keys, own order, no rules unless asked)", PluginSalvage); + } + + private static TinkerBenchSettings Settings(params (string Key, int Count)[] counts) + { + var s = new TinkerBenchSettings { MaxTinks = 10 }; + foreach (var (k, n) in counts) s.Counts[k] = n; + return s; + } + + private static TinkerItemFacts Item(AcObjectClass oc, int tinks = 0, bool imbued = false, int damageType = 0, + double work = 6, Func? flags = null) + => new() { Id = 1, Name = "Test Item", Class = oc, Tinks = tinks, Imbued = imbued, DamageType = damageType, + Workmanship = work, FlagInt = flags ?? (_ => 0) }; + + private static List Mats(List plan) => plan.Select(p => p.Material).ToList(); + + private static ServerSalvageView Row(string bench, int material, string kind, bool slot = false, string nameMatch = "", + int applied = 0, bool prepared = false, int order = 0, bool afterCap = false, + string group = "", int cap = 0) + => new(bench, material, kind, "server row", slot, nameMatch, applied, prepared, order, afterCap, group, cap); + + /// The tab's rows with these server rows (as the Crafting tab builds them). + private static List WithServer(TinkerBench bench, params ServerSalvageView[] server) + => TinkerPlanner.Rows(bench, TinkerCatalog.FromServerPlugin(bench, server), null); + + // ILT-shaped rows (RynthILT's Hub/IltSalvage.cs has the real ones). + private const int JewelSilverInt = 374, TrinketDiamondInt = 384, TrinketGromnieInt = 386; + + private static readonly ServerSalvageView[] Weapon = + { + Row("melee", TinkerCatalog.YellowGarnet, "once", order: 70), + Row("melee", TinkerCatalog.BlackGarnet, "once", slot: true, nameMatch: "Abyssal", order: 100), + Row("melee", TinkerCatalog.Leather, "once", order: 995, afterCap: true), + }; + + private static readonly ServerSalvageView[] Jewelry = + { + Row("jewelry", TinkerCatalog.Silver, "once", applied: JewelSilverInt, order: 10), + Row("jewelry", TinkerCatalog.Copper, "once", applied: 370, order: 20), + Row("jewelry", TinkerCatalog.Serpentine, "tink", order: 50, group: "jewelry-stack", cap: 10), + Row("jewelry", TinkerCatalog.Steel, "tink", order: 60, group: "jewelry-stack", cap: 10), + }; + + private static readonly ServerSalvageView[] TrinketRows = + { + Row("trinkets", TinkerCatalog.Diamond, "once", applied: TrinketDiamondInt, prepared: true, order: 10), + Row("trinkets", TinkerCatalog.Ruby, "once", applied: 385, prepared: true, order: 20), + Row("trinkets", TinkerCatalog.GromnieHide, "once", applied: TrinketGromnieInt, prepared: true, order: 30), + Row("trinkets", TinkerCatalog.Pyreal, "once", applied: 387, prepared: true, order: 40), + }; + + /// A plan's materials as "a,b,c" (Check.Eq compares lists by reference). + private static string Seq(List plan) => string.Join(",", Mats(plan)); + + private static string Seq(params int[] ids) => string.Join(",", ids); + + private static void Chance() + { + // Steel (mod 12), item 5, bag 6 (>= item: wkMod 2): 60 + 120 - 28.8 = 151.2. + Check.Eq(TinkerMath.Difficulty(TinkerCatalog.Steel, 5, 6, 0), 151, "steel difficulty, first tink"); + Check.Eq(TinkerMath.Difficulty(TinkerCatalog.Steel, 5, 6, 3), 241, "fourth tink: x1.6"); + // Gold (mod 10), item 10, bag 3 (< item: wkMod 1): 50 + 200 - 6 = 244. + Check.Eq(TinkerMath.Difficulty(TinkerCatalog.Gold, 10, 3, 0), 244, "gold, weaker bag"); + Check.Eq(TinkerMath.Difficulty(TinkerCatalog.Iron, 5, 5, 10), int.MaxValue, "no 11th tink"); + Check.True(Math.Abs(TinkerMath.SkillChance(200, 200) - 0.5) < 1e-9, "skill = difficulty is 50%"); + Check.Eq(TinkerMath.Percent(TinkerMath.Chance(TinkerCatalog.Steel, 300, 5, 6, 0, false, false)), 99, "300 skill vs 151"); + double plain = TinkerMath.Chance(TinkerCatalog.BlackOpal, 250, 6, 6, 0, false, false); + double imbue = TinkerMath.Chance(TinkerCatalog.BlackOpal, 250, 6, 6, 0, true, false); + Check.True(Math.Abs(imbue - plain / 3) < 1e-9, "imbues are a third"); + Check.Eq(TinkerMath.Chance(TinkerCatalog.BlackOpal, 1, 10, 1, 9, true, true), 1.0, "foolproof always lands"); + Check.Eq(TinkerMath.SalvageMod(TinkerCatalog.RoseQuartz), 25.0, "gem cantrips are mod 25"); + Check.Eq(TinkerMath.SalvageMod(TinkerCatalog.WhiteQuartz), 20.0, "default mod 20"); + Check.Eq(TinkerMath.BagWorkmanship(600, 100), 6.0, "bag workmanship is the average"); + } + + private static void SlotsAndImbue() + { + var rows = TinkerPlanner.Rows(TinkerBench.Melee, null, null); + var s = Settings(("r" + TinkerCatalog.Iron, 10), ("r" + TinkerCatalog.BlackOpal, 1), ("r" + TinkerCatalog.FireOpal, 1)); + var plan = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 6), s, rows); + Check.Eq(Mats(plan).Count(m => m == TinkerCatalog.BlackOpal), 1, "first imbue in order"); + Check.Eq(Mats(plan).Count(m => m == TinkerCatalog.FireOpal), 0, "second imbue refused"); + Check.Eq(Mats(plan).Count(m => m == TinkerCatalog.Iron), 3, "imbue takes a slot: 4 free - 1"); + Check.Eq(plan[0].Material, TinkerCatalog.BlackOpal, "imbue before stat tinks"); + + var imbued = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 6, imbued: true), s, rows); + Check.Eq(Mats(imbued).Count(m => m == TinkerCatalog.BlackOpal), 0, "already imbued"); + Check.Eq(imbued.Count, 4, "four Irons fill the free slots"); + + var tried = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 0, imbued: true), + Settings(("r" + TinkerCatalog.Iron, 3)), rows, k => k == "r" + TinkerCatalog.Iron ? 2 : 0); + Check.Eq(tried.Count, 1, "two of three Irons already tried this run"); + Check.Eq(TinkerPlanner.Summary(imbued), "Iron x4", "summary groups repeats"); + } + + private static void Rend() + { + Check.Eq(TinkerCatalog.RendFor(3, false), TinkerCatalog.ImperialTopaz, "slash/pierce: slash"); + Check.Eq(TinkerCatalog.RendFor(3, true), TinkerCatalog.BlackGarnet, "slash/pierce: pierce"); + Check.Eq(TinkerCatalog.RendFor(4, false), TinkerCatalog.WhiteSapphire, "bludgeon"); + Check.Eq(TinkerCatalog.RendFor(16, false), TinkerCatalog.RedGarnet, "fire"); + Check.Eq(TinkerCatalog.RendFor(0x400, false), TinkerCatalog.Onyx, "nether"); + Check.Eq(TinkerCatalog.RendFor(0, false), 0, "no damage type, no rend"); + + var rows = TinkerPlanner.Rows(TinkerBench.Melee, null, null); + var s = Settings(("r" + TinkerCatalog.RendId, 1), ("r" + TinkerCatalog.Iron, 2)); + var first = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, damageType: 32), s, rows); + Check.Eq(first[0].Material, TinkerCatalog.Emerald, "acid weapon: Emerald first"); + s.RendLast = true; + var last = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, damageType: 32), s, rows); + Check.Eq(last[^1].Material, TinkerCatalog.Emerald, "rend last"); + Check.Eq(last.Count, 3, "rend + 2 Iron"); + } + + /// + /// Rows from a server plugin's profile (ServerPackInfo.Salvage): only the tab's own, in kind order + /// unless a row gives its own, keyed "p" (never sharing a count with retail "r"), and with no rule + /// the row doesn't ask for (a Leather without "afterCap" doesn't wait for the 10 ordinary tinks). + /// + private static void PluginSalvage() + { + var salvage = new List + { + new("melee", TinkerCatalog.Leather, "once", "server Leather", false, ""), + new("melee", TinkerCatalog.Iron, "tink", "server Iron", true, ""), + new("melee", TinkerCatalog.Emerald, "imbue", "server imbue", true, ""), + new("melee", TinkerCatalog.Steel, "bogus", "unknown kind", true, ""), + new("armor", TinkerCatalog.Steel, "tink", "other tab", true, ""), + }; + var server = TinkerCatalog.FromServerPlugin(TinkerBench.Melee, salvage); + Check.Eq(server.Count, 3, "this tab's rows; the unknown kind is left out"); + Check.True(server.All(r => r.Origin == TinkerOrigin.Plugin), "plugin origin"); + Check.Eq(TinkerCatalog.Key(server[0]), "p" + TinkerCatalog.Leather, "own key"); + Check.Eq(server[0].Name, TinkerCatalog.MaterialName(TinkerCatalog.Leather), "material name"); + Check.Eq(TinkerCatalog.FromServerPlugin(TinkerBench.Melee, null).Count, 0, "nothing defined, no rows"); + + var rows = TinkerPlanner.Rows(TinkerBench.Melee, server, null); + var s = Settings(("p" + TinkerCatalog.Leather, 1), ("p" + TinkerCatalog.Iron, 2), ("p" + TinkerCatalog.Emerald, 1)); + var plan = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 5), s, rows); + Check.Eq(Seq(plan), Seq(TinkerCatalog.Emerald, TinkerCatalog.Iron, TinkerCatalog.Iron, TinkerCatalog.Leather), + "imbue, tinks, then once; Leather doesn't wait for the cap"); + Check.True(server.All(r => !r.AfterCap && r.StackGroup.Length == 0 && r.AppliedInt == 0 && !r.Prepared), "no rules unless asked"); + + // A row's own order: this once-row runs before the retail imbues (101) and the plugin's tinks. + var ordered = TinkerCatalog.FromServerPlugin(TinkerBench.Melee, new[] + { + Row("melee", TinkerCatalog.Iron, "tink", slot: true), + Row("melee", TinkerCatalog.Turquoise, "once", order: 80), + }); + Check.Eq(ordered[1].Order, 80, "the row's order"); + Check.Eq(ordered[0].Order, 400, "no order: the kind's default"); + var first = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon), + Settings(("r" + TinkerCatalog.BlackOpal, 1), ("p" + TinkerCatalog.Iron, 1), ("p" + TinkerCatalog.Turquoise, 1)), + TinkerPlanner.Rows(TinkerBench.Melee, ordered, null)); + Check.Eq(Seq(first), Seq(TinkerCatalog.Turquoise, TinkerCatalog.BlackOpal, TinkerCatalog.Iron), "order 80 goes first"); + + // The optional fields map onto the planner's row. + var mapped = TinkerCatalog.FromServerPlugin(TinkerBench.Jewelry, Jewelry.Concat(new[] + { + Row("jewelry", TinkerCatalog.Moonstone, "tink", group: "no-cap"), + })); + Check.Eq(mapped[0].AppliedInt, JewelSilverInt, "applied int"); + Check.Eq(mapped[2].StackGroup + "/" + mapped[2].StackCap, "jewelry-stack/10", "stack group and cap"); + Check.Eq(mapped[4].StackGroup, "", "a group without a cap is no group"); + Check.True(TinkerCatalog.FromServerPlugin(TinkerBench.Melee, Weapon)[2].AfterCap, "after cap"); + Check.True(TinkerCatalog.FromServerPlugin(TinkerBench.Trinkets, TrinketRows).All(r => r.Prepared), "prepared"); + } + + private static void AfterCap() + { + var rows = WithServer(TinkerBench.Melee, Weapon); + var s = Settings(("p" + TinkerCatalog.YellowGarnet, 1), ("r" + TinkerCatalog.Iron, 10), ("p" + TinkerCatalog.Leather, 1)); + var full = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 10), s, rows); + Check.Eq(Seq(full), Seq(TinkerCatalog.YellowGarnet, TinkerCatalog.Leather), "capped item: no-slot rows, then Leather"); + + var some = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 5), s, rows); + Check.Eq(some[^1].Material, TinkerCatalog.Leather, "Irons fill the last 5 slots, then Leather"); + Check.Eq(Mats(some).Count(m => m == TinkerCatalog.Iron), 5, "five Irons"); + Check.Eq(Mats(some).Count(m => m == TinkerCatalog.Leather), 1, "Leather once"); + + var open = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 5), + Settings(("p" + TinkerCatalog.Leather, 1), ("r" + TinkerCatalog.Iron, 2)), rows); + Check.True(!Mats(open).Contains(TinkerCatalog.Leather), "Leather waits for the 10 ordinary tinks"); + + var retailOnly = TinkerPlanner.Plan(TinkerBench.Melee, Item(AcObjectClass.MeleeWeapon, tinks: 10), s, + TinkerPlanner.Rows(TinkerBench.Melee, null, null)); + Check.Eq(retailOnly.Count, 0, "no server rows: nothing offered past the cap"); + } + + private static void StackAndApplied() + { + var rows = WithServer(TinkerBench.Jewelry, Jewelry); + var s = Settings(("p" + TinkerCatalog.Serpentine, 8), ("p" + TinkerCatalog.Steel, 8), + ("p" + TinkerCatalog.Silver, 1), ("p" + TinkerCatalog.Copper, 1)); + var plan = TinkerPlanner.Plan(TinkerBench.Jewelry, Item(AcObjectClass.Jewelry, tinks: 0, + flags: k => k == JewelSilverInt ? 2 : 0), s, rows); + var m = Mats(plan); + Check.Eq(m.Count(x => x == TinkerCatalog.Serpentine), 8, "8 Serpentine"); + Check.Eq(m.Count(x => x == TinkerCatalog.Steel), 2, "Steel stops at 10 combined"); + Check.True(!m.Contains(TinkerCatalog.Silver), "Silver's applied int already reads 2"); + Check.Eq(m[0], TinkerCatalog.Copper, "flag rows first (their order)"); + + // Two groups don't share; a row outside any group isn't capped. + var split = WithServer(TinkerBench.Jewelry, + Row("jewelry", TinkerCatalog.Serpentine, "tink", order: 50, group: "a", cap: 3), + Row("jewelry", TinkerCatalog.Steel, "tink", order: 60, group: "b", cap: 4), + Row("jewelry", TinkerCatalog.Iron, "tink", order: 70)); + var p2 = Mats(TinkerPlanner.Plan(TinkerBench.Jewelry, Item(AcObjectClass.Jewelry), + Settings(("p" + TinkerCatalog.Serpentine, 9), ("p" + TinkerCatalog.Steel, 9), ("p" + TinkerCatalog.Iron, 9)), split)); + 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"); + } + + private static void ItemRows() + { + var rows = TinkerPlanner.Rows(TinkerBench.Items, null, null); + var s = Settings(("r" + TinkerCatalog.Moonstone, 2), ("r" + TinkerCatalog.Leather, 1), ("r" + TinkerCatalog.Sandstone, 1)); + var noMana = TinkerPlanner.Plan(TinkerBench.Items, Item(AcObjectClass.Armor), s, rows); + Check.Eq(Seq(noMana), Seq(TinkerCatalog.Leather), "no mana: no Moonstone; not retained: Leather, not Sandstone"); + + var mana = new TinkerItemFacts { Class = AcObjectClass.Armor, Workmanship = 5, MaxMana = 800, Retained = true, Tinks = 10 }; + var retained = TinkerPlanner.Plan(TinkerBench.Items, mana, s, rows); + Check.Eq(Seq(retained), Seq(TinkerCatalog.Sandstone), "capped + retained: only Sandstone (no slot)"); + } + + private static void Filters() + { + var s = Settings(); + s.MaxTinks = 8; + s.MinFreeTinks = 3; + s.SkipImbued = true; + Check.Eq(TinkerPlanner.Excluded(Item(AcObjectClass.Armor, tinks: 9), s), "9 tinks (max 8)", "max tinks"); + Check.Eq(TinkerPlanner.Excluded(Item(AcObjectClass.Armor, tinks: 8), s), "fewer than 3 free tinks", "min free"); + Check.Eq(TinkerPlanner.Excluded(Item(AcObjectClass.Armor, imbued: true), s), "imbued", "skip imbued"); + Check.Eq(TinkerPlanner.Excluded(Item(AcObjectClass.Armor, work: 0), s), "no workmanship", "untinkerable"); + var worn = Item(AcObjectClass.Armor); + worn.Equipped = true; + Check.Eq(TinkerPlanner.Excluded(worn, s), "equipped", "worn items left alone"); + Check.Eq(TinkerPlanner.Excluded(Item(AcObjectClass.Armor, tinks: 2), s), "", "eligible"); + Check.True(TinkerCatalog.Targets(TinkerBench.Caster, AcObjectClass.WandStaffOrb) + && !TinkerCatalog.Targets(TinkerBench.Items, AcObjectClass.Salvage), "bench targets"); + } + + private static void Bags() + { + var melee = WithServer(TinkerBench.Melee, Weapon); + var rend = new TinkerStep(melee.First(r => r.Id == TinkerCatalog.RendId), TinkerCatalog.BlackGarnet); + var abyssal = new TinkerStep(melee.First(r => r.NameMatch == "Abyssal"), TinkerCatalog.BlackGarnet); + var iron = new TinkerStep(melee.First(r => r.Id == TinkerCatalog.Iron), TinkerCatalog.Iron); + + Check.True(TinkerPlanner.BagMatches(iron, "Salvage (100)", TinkerCatalog.Iron, 100), "full Iron bag"); + Check.True(!TinkerPlanner.BagMatches(iron, "Salvage (60)", TinkerCatalog.Iron, 60), "partial bag refused"); + Check.True(TinkerPlanner.BagMatches(rend, "Salvage (100)", TinkerCatalog.BlackGarnet, 100), "Black Garnet rend bag"); + Check.True(!TinkerPlanner.BagMatches(rend, "Bag of Abyssal-Touched Gems", TinkerCatalog.BlackGarnet, 100), "Abyssal isn't a rend"); + Check.True(TinkerPlanner.BagMatches(abyssal, "Bag of Abyssal-Touched Gems", TinkerCatalog.BlackGarnet, 100), "Abyssal row by name"); + Check.True(TinkerPlanner.BagMatches(rend, "Foolproof Black Garnet", 0, 100), "Foolproof rend by name"); + Check.True(!TinkerPlanner.BagMatches(rend, "Foolproof Black Opal", 0, 100), "Black Opal isn't Black Garnet"); + Check.True(TinkerPlanner.IsFoolproof("Foolproof Imperial Topaz"), "foolproof name"); + } + + private static void BagChoice() + { + var bags = new List { new(1, 4, 0.60), new(2, 7, 0.85), new(3, 9, 0.95) }; + Check.Eq(TinkerPlanner.SelectBag(bags, 0), 2, "no minimum: best chance"); + Check.Eq(TinkerPlanner.SelectBag(bags, 80), 1, "minimum 80: the cheapest bag that reaches it"); + Check.Eq(TinkerPlanner.SelectBag(bags, 99), -1, "nothing reaches 99"); + var server = new List { new(1, 5, null), new(2, 8, null) }; + Check.Eq(TinkerPlanner.SelectBag(server, 50), 1, "unknown chance: best workmanship"); + var tie = new List { new(1, 9, 1.0), new(2, 3, 1.0) }; + Check.Eq(TinkerPlanner.SelectBag(tie, 0), 1, "tie: keep the better bag"); + } + + private static void Section() + { + // Crafting is one of the Mini Remote's universal tabs (every server), after Quests and Pets. + Check.Eq(MiniRemoteTabs.Parse("tinker"), MiniRemoteTabs.Crafting, "/ra hub open tinker"); + Check.Eq(MiniRemoteTabs.Parse("crafting"), MiniRemoteTabs.Crafting, "crafting id"); + Check.Eq(MiniRemoteTabs.Crafting, "crafting", "tab id the engine menu sends"); + Check.True(MiniRemoteTabs.Universal.Contains(MiniRemoteTabs.Crafting), "on the tab bar, every server"); + Check.Eq(MiniRemoteTabs.Label(MiniRemoteTabs.Crafting), "Crafting", "tab label"); + } + + private static void Trinkets() + { + Check.Eq(TinkerPlanner.Rows(TinkerBench.Trinkets, null, null).Count, 0, "retail has no trinket rows"); + var rows = WithServer(TinkerBench.Trinkets, TrinketRows); + var s = Settings(("p" + TinkerCatalog.Pyreal, 1), ("p" + TinkerCatalog.Diamond, 1), ("p" + TinkerCatalog.Ruby, 1), + ("p" + TinkerCatalog.GromnieHide, 1)); + var all = TinkerPlanner.Plan(TinkerBench.Trinkets, Item(AcObjectClass.Jewelry), s, rows); + Check.Eq(Seq(all), Seq(TinkerCatalog.Diamond, TinkerCatalog.Ruby, TinkerCatalog.GromnieHide, TinkerCatalog.Pyreal), + "the rows' order: Diamond, Ruby, Gromnie Hide, Pyreal"); + var some = TinkerPlanner.Plan(TinkerBench.Trinkets, Item(AcObjectClass.Jewelry, + flags: k => k is TrinketDiamondInt or TrinketGromnieInt ? 2 : 0), s, rows); + Check.Eq(Seq(some), Seq(TinkerCatalog.Ruby, TinkerCatalog.Pyreal), "applied ints 384 / 386 already 2"); + var capped = TinkerPlanner.Plan(TinkerBench.Trinkets, Item(AcObjectClass.Jewelry, tinks: 10), s, rows); + Check.Eq(capped.Count, 4, "no-slot rows ignore the tink cap"); + + var diamond = new TinkerStep(rows.First(r => r.Id == TinkerCatalog.Diamond), TinkerCatalog.Diamond); + Check.True(TinkerPlanner.BagMatches(diamond, "Major Diamond Salvage", TinkerCatalog.Diamond, 100, 2), "Major bag at Major"); + Check.True(!TinkerPlanner.BagMatches(diamond, "Minor Diamond Salvage", TinkerCatalog.Diamond, 100, 2), "Minor bag at Major"); + Check.True(!TinkerPlanner.BagMatches(diamond, "Salvage (100)", TinkerCatalog.Diamond, 100, 0), "raw bag isn't prepared"); + Check.True(!TinkerPlanner.BagMatches(diamond, "Major Ruby Salvage", TinkerCatalog.Ruby, 100, 2), "other material"); + Check.True(TinkerPlanner.IsRawTrinketBag(TinkerCatalog.Diamond, "Salvage (100)", TinkerCatalog.Diamond, 100), "raw bag"); + Check.True(!TinkerPlanner.IsRawTrinketBag(TinkerCatalog.Diamond, "Moderate Diamond Salvage", TinkerCatalog.Diamond, 100), "prepared isn't raw"); + Check.True(!TinkerPlanner.IsRawTrinketBag(TinkerCatalog.Diamond, "Salvage (55)", TinkerCatalog.Diamond, 55), "partial raw bag"); + Check.True(TinkerPlanner.IsTierAmmunition("Moderate Ammunition", 1), "Moderate Ammunition"); + Check.True(!TinkerPlanner.IsTierAmmunition("Major Ammunition", 1), "wrong tier"); + Check.True(!TinkerPlanner.IsTierAmmunition("Moderate Diamond Salvage", 1), "not Ammunition"); + 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)"); + Check.True(TinkerCatalog.Targets(TinkerBench.Trinkets, AcObjectClass.Jewelry), "trinkets are jewelry"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs index 73f0fa9..866ffc6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs @@ -56,6 +56,10 @@ internal static class WeaponTests r.Add("weapon swap: no flip-flop between two weapons", SwapNoFlipFlop); r.Add("weapon swap: a new target that wants the weapon just swapped away from gets it at once (Drakkon 2026-10-12)", SwapBackForNewTarget); r.Add("weapon swap: a server refusal counts as a failed try", SwapRefused); + r.Add("weapon swap: 'too busy' is no try, and a portal or recall ends the rest (Kelpie 2026-10-15)", SwapBusyNotCounted); + r.Add("weapon swap: combat reads ACE's busy answer (0x1D then SaveFailed 0) as busy, a real refusal as a try", CombatReadsBusyWield); + r.Add("weapon swap: a wield that lands after the choice moved still counts (no swap straight back)", SwapLandsWhenChoiceMoved); + r.Add("element choice: a weakness swap must beat the weapon in hand by the min gain", ChoiceMinSwapGain); r.Add("tester's case: Dragon's Isle, an unlisted fire wand and Blades", TesterDragonsIsle); } @@ -905,6 +909,57 @@ internal static class WeaponTests Check.Eq(tr2.Next(next, hand, u.AddSeconds(5), forKey: 0x8010), WeaponSwapTracker.Step.Hold, "a fifth swap inside a minute: held"); } + /// + /// Kelpie 2026-10-14 11:41:06-08: Fire -> Piercing sent, the target changed and the plan + /// wanted Fire again while Piercing reached the hand. The landing must count, so the swap + /// straight back is held (before: "not seen in hand", no landing, swapped back 2.5 s later). + /// + private static void SwapLandsWhenChoiceMoved() + { + var tr = new WeaponSwapTracker(); + DateTime t = new(2026, 10, 14, 11, 41, 6); + const int fire = 1, piercing = 2; + Check.Eq(tr.Next(piercing, fire, t), WeaponSwapTracker.Step.Swap, "Piercing chosen: swap"); + tr.Sent(piercing, fire, t); + Check.Eq(tr.Next(fire, piercing, t.AddMilliseconds(2500)), WeaponSwapTracker.Step.Hold, + "Piercing landed while Fire is wanted again: the swap back is held"); + Check.Eq(tr.PendingId, 0, "nothing in flight once it landed"); + Check.Eq(tr.TriesFor(piercing), 0, "the landed weapon's tries are cleared"); + Check.Eq(tr.Notice, null, "no give-up notice: it didn't fail"); + + // A third weapon is not the one just swapped away from: allowed. + Check.Eq(tr.Next(3, piercing, t.AddMilliseconds(3000)), WeaponSwapTracker.Step.Swap, "another weapon may still swap"); + } + + /// WeaponPlanner.KeepInHand: a weakness swap must beat the hand by the min gain. + private static void ChoiceMinSwapGain() + { + var bows = new List + { + new(1, "Fire Bow", CombatMode.Missile, "Fire", "", InHand: true), + new(2, "Cold Bow", CombatMode.Missile, "Cold", "", InHand: false), + }; + var close = Rank(("Cold", 1.1), ("Fire", 1.0)); + var off = WeaponPlanner.Choose(bows, "", close, All); + Check.Eq(off.WeaponId, 2, "threshold off: the weakest element wins as before"); + var keep = WeaponPlanner.Choose(bows, "", close, All, minSwapGain: 0.2); + Check.Eq(keep.WeaponId, 1, "Cold only 10% better than Fire in hand: keep the Fire bow"); + Check.Eq(keep.Element, "Fire", "and its element"); + Check.True(keep.Source.Contains("within 20%"), "source says why: " + keep.Source); + + var far = Rank(("Cold", 1.5), ("Fire", 1.0)); + Check.Eq(WeaponPlanner.Choose(bows, "", far, All, minSwapGain: 0.2).WeaponId, 2, "Cold 50% better: swap"); + + var learned = new CreatureWeakness.Ranking { Source = "learned", Order = { ("Cold", double.NaN), ("Fire", double.NaN) } }; + Check.Eq(WeaponPlanner.Choose(bows, "", learned, All, minSwapGain: 0.2).WeaponId, 2, "order only (learned): no threshold, swap"); + + var immune = Rank(("Cold", 1.0), ("Fire", 0.0)); + Check.Eq(WeaponPlanner.Choose(bows, "", immune, All, minSwapGain: 0.5).WeaponId, 2, "the hand does nothing to it: swap"); + + // An explicit Monsters rule element is never held back. + Check.Eq(WeaponPlanner.Choose(bows, "Cold", close, All, minSwapGain: 0.5).WeaponId, 2, "the rule's Cold: swap"); + } + private static void SwapRefused() { var tr = new WeaponSwapTracker { MaxTries = 2 }; @@ -918,6 +973,92 @@ internal static class WeaponTests Check.Eq(tr.Next(2, 1, t.AddMilliseconds(500)), WeaponSwapTracker.Step.Hold, "second refusal with MaxTries 2: rest"); } + /// + /// Kelpie 2026-10-15 00:44:22-32: a house recall right after the wield; the server answered + /// all 3 tries 'too busy' and the Frost crossbow was benched for 2 min. A busy answer is no + /// try (bounded by MaxBusyRefunds), and a portal or recall ends every rest. + /// + private static void SwapBusyNotCounted() + { + var tr = new WeaponSwapTracker(); + DateTime t = new(2026, 10, 15, 0, 44, 22); + for (int i = 0; i < 5; i++) + { + Check.Eq(tr.Next(2, 1, t), WeaponSwapTracker.Step.Swap, $"busy round {i}: swap"); + tr.Sent(2, 1, t); + tr.Busy(t.AddMilliseconds(100)); + Check.Eq(tr.PendingId, 0, "a busy answer ends the swap in flight"); + Check.Eq(tr.TriesFor(2), 0, "and gives the try back"); + Check.Eq(tr.Next(2, 1, t.AddMilliseconds(500)), WeaponSwapTracker.Step.Wait, "the wield waits out the busy pause"); + t = t.AddMilliseconds(100 + tr.BusyRetryMs); + } + Check.Eq(tr.Notice, null, "no give-up while the server is only busy"); + Check.Eq(tr.Next(2, 2, t), WeaponSwapTracker.Step.InHand, "once the server is free the weapon lands"); + + // A weapon the server always calls busy still gets rested, after MaxBusyRefunds. + var tr2 = new WeaponSwapTracker { MaxTries = 1, MaxBusyRefunds = 2 }; + DateTime u = t; + for (int i = 0; i < 2; i++) + { + tr2.Next(3, 1, u); tr2.Sent(3, 1, u); + tr2.Busy(u); + u = u.AddMilliseconds(tr2.BusyRetryMs); + } + tr2.Next(3, 1, u); tr2.Sent(3, 1, u); + tr2.Busy(u); + Check.True(tr2.Notice != null && tr2.Notice.Contains("server too busy"), "past the refunds it counts: rested"); + Check.Eq(tr2.Next(3, 1, u.AddSeconds(5)), WeaponSwapTracker.Step.Hold, "resting"); + + // A portal or recall ends the rest. + tr2.NewPlace(); + Check.Eq(tr2.Next(3, 1, u.AddSeconds(10)), WeaponSwapTracker.Step.Swap, "after a portal: try again at once"); + Check.Eq(tr2.TriesFor(3), 0, "with a fresh count"); + } + + /// + /// Combat reads ACE's busy answer to a wield: WeenieError 0x1D, then InventoryServerSaveFailed + /// with no error. The engine keeps only the last record, so the SaveFailed alone must read as + /// busy (before: "error 0", no answer, the try ran into the timeout and counted). + /// + private static void CombatReadsBusyWield() + { + const uint Old = 0x7000B001, New = 0x7000B002; + FakeHost.Reset(); + FakeHost.WeenieErrorCalls = true; + FakeHost.Names[Old] = "Fire Crossbow"; FakeHost.Names[New] = "Frost Compound Crossbow"; + var host = FakeHost.Create(); + var cache = FakeHost.MakeCache(host, Player, new[] { Old, New }); + var c = new CombatManager(host, new LegacyUiSettings(), cache); + c.SetPlayerId(Player); + const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic; + var send = typeof(CombatManager).GetMethod("MarkWieldSent", F)!; + var step = typeof(CombatManager).GetMethod("SwapStep", F)!; + int oldId = unchecked((int)Old), newId = unchecked((int)New); + + send.Invoke(c, new object[] { newId, oldId }); + FakeHost.WeenieError(0x1D); + FakeHost.WeenieError(0, 0x00A0, Old); + var s = (WeaponSwapTracker.Step)step.Invoke(c, new object[] { newId, oldId })!; + Check.Eq(s, WeaponSwapTracker.Step.Wait, "busy: wait out the pause, then wield again"); + Check.Eq(c.SwapTracker.PendingId, 0, "the wield in flight is over"); + Check.Eq(c.SwapTracker.TriesFor(newId), 0, "and not counted"); + Check.True(FakeHost.Logs.Any(l => l.Contains("answered 'too busy': not counted")), "logged"); + + // A real refusal (a specific error) still counts. + c.SwapTracker.NewPlace(); + send.Invoke(c, new object[] { newId, oldId }); + FakeHost.WeenieError(0x0036); + step.Invoke(c, new object[] { newId, oldId }); + Check.Eq(c.SwapTracker.TriesFor(newId), 1, "a refusal is a try"); + + // Leaving portal space ends tries and rests. + FakeHost.Portaling = true; + c.OnHeartbeat(); + FakeHost.Portaling = false; + c.OnHeartbeat(); + Check.Eq(c.SwapTracker.TriesFor(newId), 0, "after the portal: a fresh count"); + } + // ── The tester's case ───────────────────────────────────────────────────── /// diff --git a/Tools/RynthCore.RynthAiTests/Program.cs b/Tools/RynthCore.RynthAiTests/Program.cs index 300e68b..8aac1ad 100644 --- a/Tools/RynthCore.RynthAiTests/Program.cs +++ b/Tools/RynthCore.RynthAiTests/Program.cs @@ -19,6 +19,7 @@ internal static class Program CombatStallWatchdogTests.Register(runner); CreatureWeaknessTests.Register(runner); MonsterDamageTierTests.Register(runner); + LootBaselineTests.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 c94947d..7406700 100644 --- a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj +++ b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj @@ -21,12 +21,15 @@ + + + diff --git a/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs b/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs index ecbd079..77158ec 100644 --- a/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs +++ b/Tools/RynthCore.RynthAiTests/Tests/CombatStallWatchdogTests.cs @@ -22,6 +22,53 @@ internal static class CombatStallWatchdogTests r.Add("stall: a tick gap starts the count over", TickGapResets); r.Add("stall: ineligible never acts", Ineligible); r.Add("stall: Unfire takes a step back - the same step is due again next tick, not 3 s later", UnfireRetries); + r.Add("stall: a missile target at point blank starts the ladder at 3.5 s", PointBlank); + r.Add("point blank facing: one snap only for a close target behind, after a full shot cycle", PointBlankFacingRules); + } + + /// + /// PointBlankFacing (Kelpie 2026-10-14/15: crossbow at 1.7 m, target 177 degrees behind, no + /// shots until the target was dropped): snap only within 3 m, more than 90 degrees off, after + /// 2.5 s with no shot, once per 3 s per target, then hold 300 ms. + /// + private static void PointBlankFacingRules() + { + var f = new PointBlankFacing(); + DateTime shot = T0; + DateTime now = T0.AddMilliseconds(2600); + Check.True(f.ShouldSnap(now, 7, 1.7, 177, shot), "1.7 m, 177 degrees off, 2.6 s since a shot: snap"); + Check.False(f.ShouldSnap(T0.AddMilliseconds(2000), 7, 1.7, 177, shot), "a shot 2 s ago may still be in flight: wait"); + Check.False(f.ShouldSnap(now, 7, 3.5, 177, shot), "beyond 3 m the server turns the character itself"); + Check.False(f.ShouldSnap(now, 7, 1.7, 80, shot), "80 degrees off: left to the server"); + Check.False(f.ShouldSnap(now, 0, 1.7, 177, shot), "no target"); + Check.True(f.ShouldSnap(now, 7, 1.7, 177, NoEvidence), "no shot ever: snap"); + + f.Snapped(now, 7); + Check.True(f.Settling(now.AddMilliseconds(200), 7), "the attack waits 300 ms after the snap"); + Check.False(f.Settling(now.AddMilliseconds(350), 7), "then goes"); + Check.False(f.Settling(now.AddMilliseconds(200), 8), "another target isn't held"); + Check.False(f.ShouldSnap(now.AddMilliseconds(2000), 7, 1.7, 177, shot), "no second snap for the same target within 3 s"); + Check.True(f.ShouldSnap(now.AddMilliseconds(3100), 7, 1.7, 177, shot), "after 3 s it may snap again"); + Check.True(f.ShouldSnap(now.AddMilliseconds(500), 8, 1.7, 177, shot), "a new target may snap at once"); + Check.Eq(f.Snaps, 1, "one snap counted"); + } + + /// The caller passes PointBlankStallMs for a missile target within 3 m (Kelpie 2026-10-14). + private static void PointBlank() + { + var w = new CombatStallWatchdog(); + Act first = Act.None; + int at = -1; + for (int t = 0; t <= 10_000 && first == Act.None; t += TickMs) + { + first = w.Tick(T0.AddMilliseconds(t), eligible: true, NoEvidence, out _, + stallAfterMs: CombatStallWatchdog.PointBlankStallMs); + if (first != Act.None) at = t; + } + Check.Eq((first, at), (Act.Reissue, 3500), "step 1 after 3.5 s at point blank"); + + var normal = new CombatStallWatchdog(); + Check.Eq(RunUntilAction(normal, 0, 10_000, NoEvidence), (Act.Reissue, 6000), "the default is still 6 s"); } /// Ticks every 500 ms from to diff --git a/Tools/RynthCore.RynthAiTests/Tests/LootBaselineTests.cs b/Tools/RynthCore.RynthAiTests/Tests/LootBaselineTests.cs new file mode 100644 index 0000000..cfa034f --- /dev/null +++ b/Tools/RynthCore.RynthAiTests/Tests/LootBaselineTests.cs @@ -0,0 +1,71 @@ +using RynthCore.Plugin.RynthAi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiTests.Tests; + +// The loot-timer baseline (LootBaseline.cs) and the [LootSettings] line the corpse looting logs: +// each timer marked baseline or custom, floors noted, and the approach range's Min-above-Max note. +// Kelpie's and Storm's saved timers on 2026-10-14 are the real-world cases. +internal static class LootBaselineTests +{ + public static void Register(Runner r) + { + r.Add("loot baseline: the measured values", Values); + r.Add("loot baseline: all baseline is said once", AllBaseline); + r.Add("loot baseline: Kelpie's custom timers and his Min-above-Max range", Kelpie); + r.Add("loot baseline: a timer below the code's floor says what it acts as", Storm); + r.Add("loot baseline: legacy fractional ranges are read as 240 yd fractions", FractionalRange); + } + + private static void Values() + { + LootBaseline.Timers b = LootBaseline.Values; + Check.Eq(b, new LootBaseline.Timers(100, 300, 300, 1000, 1500, 12000), "baseline timers"); + // Above the measured 95th percentile of appraisal replies (256 ms). + Check.True(LootBaseline.AssessWindowMs > 256, "assess window covers the 95th percentile"); + foreach (LootBaseline.Entry e in LootBaseline.Compare(b)) + Check.False(e.BelowFloor, $"{e.Label} baseline is not below its floor"); + } + + private static void AllBaseline() + { + string line = LootBaseline.Describe(LootBaseline.Values, 10, 2); + Check.True(line.StartsWith("[LootSettings] Content Settle 100 ms baseline"), line); + Check.True(line.Contains("-- all baseline"), "summary says all baseline: " + line); + Check.False(line.Contains("custom"), "no timer is custom: " + line); + Check.False(line.Contains("Approach Range"), "a sane range adds no note: " + line); + } + + private static void Kelpie() + { + var kelpie = new LootBaseline.Timers(125, 550, 450, 1000, 1200, 12000); + string line = LootBaseline.Describe(kelpie, 40, 240); + Check.True(line.Contains("Content Settle 125 ms custom (baseline 100)"), line); + Check.True(line.Contains("Empty Corpse Wait 550 ms custom (baseline 300)"), line); + Check.True(line.Contains("Assess Window 450 ms custom (baseline 300)"), line); + Check.True(line.Contains("Loot Retry Timeout 1000 ms baseline"), line); + Check.True(line.Contains("Corpse Open Retry 1200 ms custom (baseline 1500)"), line); + Check.True(line.Contains("Corpse Timeout 12000 ms baseline"), line); + Check.True(line.Contains("-- 4 of 6 custom"), line); + Check.True(line.Contains("Approach Range Min 240 yd is above Max 40 yd, so Min acts as 40 yd"), line); + } + + /// Storm's saved timers, with Empty Corpse Wait lowered from 200 to 150 to go under its floor. + private static void Storm() + { + var storm = new LootBaseline.Timers(100, 150, 150, 300, 1500, 8500); + string line = LootBaseline.Describe(storm, 6.5, 2); + Check.True(line.Contains("Empty Corpse Wait 150 ms custom (baseline 300) [acts as 200]"), line); + Check.False(line.Contains("Assess Window 150 ms custom (baseline 300) [acts"), "150 is above the 100 floor: " + line); + Check.True(line.Contains("-- 4 of 6 custom"), line); + } + + private static void FractionalRange() + { + // 0.05 of 240 yd = 12 yd Max; Min 20 yd is above it. + string line = LootBaseline.Describe(LootBaseline.Values, 0.05, 20); + Check.True(line.Contains("Min 20 yd is above Max 12 yd"), line); + // Unset values fall back to 10 / 2 yd, which is fine. + Check.False(LootBaseline.Describe(LootBaseline.Values, 0, 0).Contains("Approach Range"), "unset range adds no note"); + } +} diff --git a/Tools/RynthCore.TrackerSessionTests/Program.cs b/Tools/RynthCore.TrackerSessionTests/Program.cs index 25e40fa..d7bd87c 100644 --- a/Tools/RynthCore.TrackerSessionTests/Program.cs +++ b/Tools/RynthCore.TrackerSessionTests/Program.cs @@ -47,6 +47,7 @@ internal static partial class Program TestCleanup(); TestKillCounter(); TestSessionStats(); + TestRynthAiSnapshot(); Console.WriteLine($"\n{_asserts} assertions, {_fails} failed."); if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; } @@ -56,6 +57,50 @@ internal static partial class Program private static readonly DateTime Now = new(2026, 10, 1, 3, 0, 0, DateTimeKind.Utc); + /// + /// One session (2026-10-13): RynthTracker shows RynthAi's session ("RynthAi.Hub" SessionStats and + /// SessionStatsMore) when RynthAi answers; its rates are rounded, not cut off. + /// + private static void TestRynthAiSnapshot() + { + Console.WriteLine("-- RynthAi's session in the Tracker panel"); + var s = new RynthCore.Plugin.Shared.SessionStatsV1 + { + StartUtcTicks = Now.AddHours(-2).Ticks, SessionSeconds = 7200, Xp = 5_000_000, XpPerHour = 2_499_999.6, + Lum = 9000, LumPerHour = 4500.5, LumLast5Min = 120, PassUpTracked = 1, LumPassUp = 300, PassUpPerHour = 149.4, + Kills = 40, KillsPerHour = 20, + }; + var more = new RynthCore.Plugin.Shared.SessionStatsMoreV1 { XpPerKill = 125_000, Deaths = 1, MaxLevel = 0, Rad = 77, RadPerHour = 38.5 }; + var v = RynthCore.Plugin.RynthTracker.TrackerSnapshot.FromRynthAi(s, more, null); + Eq(v.SessionStartUtc, Now.AddHours(-2), "RynthAi's session start"); + Check(v.Xp == 5_000_000 && v.Lum == 9000 && v.Kills == 40 && v.PassUpTracked && v.LumPassUp == 300, "RynthAi's totals"); + Check(v.XpPerKill == 125_000 && v.Deaths == 1 && v.Rad == 77 && !v.MaxLevel, "and the rest from SessionStatsMore"); + + string json = RynthCore.Plugin.RynthTracker.TrackerSnapshot.Build(v, Now); + Check(json.Contains("\"ss\":7200.0"), "the clock runs from RynthAi's start: " + json); + Check(json.Contains("\"xh\":2500000") && json.Contains("\"lh\":4501") && json.Contains("\"ph\":149") && json.Contains("\"rh\":39"), + "rates rounded, not cut off: " + json); + Check(json.Contains("\"kt\":40") && json.Contains("\"xk\":125000") && json.Contains("\"dt\":1") && json.Contains("\"pk\":1"), "panel fields: " + json); + + // An older RynthAi (no SessionStatsMore): those fields from the Tracker's own session, else zero. + var own = new SessionStatsView(Now.AddHours(-1), 3600, 1, 1, 1, 1, 0, 0, 0, false, 3, 3, 999, 4, 5, 6, true); + var old = RynthCore.Plugin.RynthTracker.TrackerSnapshot.FromRynthAi(s, null, own); + Check(old.Xp == 5_000_000 && old.XpPerKill == 999 && old.Deaths == 4 && old.Rad == 5 && old.MaxLevel, + "older RynthAi: RynthAi's totals, the Tracker's own deaths / Radiance / XP per kill"); + var bare = RynthCore.Plugin.RynthTracker.TrackerSnapshot.FromRynthAi(s, null, null); + Check(bare.XpPerKill == 0 && bare.Deaths == 0 && bare.Rad == 0 && !bare.MaxLevel, "and zero with no own session"); + + Eq(RynthCore.Plugin.RynthTracker.TrackerSnapshot.PerHour(double.NaN), 0L, "NaN rate is 0"); + Eq(RynthCore.Plugin.RynthTracker.TrackerSnapshot.PerHour(-5), 0L, "negative rate is 0"); + Eq(RynthCore.Plugin.RynthTracker.TrackerSnapshot.PerHour(0.5), 1L, "half rounds up"); + unsafe + { + Eq(RynthCore.Plugin.Shared.RynthAiHubApiV1.BaseStructSize, (uint)(8 + 10 * sizeof(nint)), "the hub table's base size (10 functions)"); + Eq((uint)sizeof(RynthCore.Plugin.Shared.RynthAiHubApiV1), RynthCore.Plugin.Shared.RynthAiHubApiV1.BaseStructSize + (uint)sizeof(nint), + "SessionStatsMore appended right after the base"); + } + } + private static TrackerSessionState Sample() => new() { ProcessId = 4321, diff --git a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj index 133bfa9..c336278 100644 --- a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj +++ b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj @@ -13,9 +13,14 @@ net10.0 enable RynthCore.TrackerSessionTests + + true + + + diff --git a/Tools/RynthILT.Tests/AetheriaChunkTests.cs b/Tools/RynthILT.Tests/AetheriaChunkTests.cs new file mode 100644 index 0000000..7cfdb38 --- /dev/null +++ b/Tools/RynthILT.Tests/AetheriaChunkTests.cs @@ -0,0 +1,42 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to +// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off. +internal static class AetheriaChunkTests +{ + public static void Register(Runner r) + { + r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap); + r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings); + } + + private static void Cap() + { + Check.Eq(IltInventory.AetheriaMaxLevel, 10, "ILT max aetheria level"); + Check.Eq(IltChunkClap.ClampUnderLevel(0), 1, "below 1 clamps to 1"); + Check.Eq(IltChunkClap.ClampUnderLevel(7), 7, "7 (retail clamp was 6) is allowed"); + Check.Eq(IltChunkClap.ClampUnderLevel(11), 11, "11 chunks every level"); + Check.Eq(IltChunkClap.ClampUnderLevel(50), 11, "above 11 clamps to 11"); + Check.Eq(new IltGearState().ChunkAetheriaUnderLevel, 4, "the default cap is unchanged"); + } + + private static void Ratings() + { + var g = new IltGearState(); + Check.True(g.KeepAetheriaWithCrit && g.KeepAetheriaWithCritDamage && g.KeepAetheriaWithCritDamageResist, "all keep switches on by default"); + Check.False(IltChunkClap.KeptForRatings(g, 0, 0, 0), "no rating: chunkable"); + Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C kept"); + Check.True(IltChunkClap.KeptForRatings(g, 0, 1, 0), "CD kept"); + Check.True(IltChunkClap.KeptForRatings(g, 0, 0, 3), "CDR kept"); + + g.KeepAetheriaWithCrit = false; + Check.False(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C chunkable with its switch off"); + Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 3), "CDR still keeps a C+CDR sigil"); + g.KeepAetheriaWithCritDamage = false; + g.KeepAetheriaWithCritDamageResist = false; + Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect"); + } +} diff --git a/Tools/RynthILT.Tests/AttributeRaiserTests.cs b/Tools/RynthILT.Tests/AttributeRaiserTests.cs index 2a24847..8776360 100644 --- a/Tools/RynthILT.Tests/AttributeRaiserTests.cs +++ b/Tools/RynthILT.Tests/AttributeRaiserTests.cs @@ -30,6 +30,7 @@ internal static class AttributeRaiserTests r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety); r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced); r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner); + r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines); r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel); r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings); } @@ -196,6 +197,34 @@ internal static class AttributeRaiserTests Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug"); } + /// + /// Refresh current must not finish on the /aug banner alone (chat-hold lag used to leave Current at 0). + /// + private static void AugRefreshWaitsForLevelLines() + { + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "aug-refresh-idle", out _); + var prog = hub.Progression; + // Seed so EnsureAugs does not queue its own /aug ahead of our Refresh. + prog.ApplyAugLines(new List { "Creature: 1" }); + + prog.HandleRemote(new[] { "augload" }); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Refresh current sends /aug"); + Reply(hub, "---------------------------", "Advanced Augmentation Levels:"); + // Longer than IdleEndMs (2s): without ArmsIdle this used to ApplyAugLines([]) and clear the status. + var until = DateTime.UtcNow.AddMilliseconds(2500); + while (DateTime.UtcNow < until) { hub.Tick(); Thread.Sleep(25); } + Check.True(FakeHost.ChatCommands.Count(x => x == "/aug") == 1, "still waiting on the same /aug (banner did not end it)"); + + Reply(hub, "Creature:4,300", "Item:100", "Specialize: 2"); + Check.True(TickUntil(hub, () => + { + var sb = new System.Text.StringBuilder(); + prog.AppendSnapshotJson(sb); + return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal); + }), "Current updates once Creature:/Item: lines arrive"); + } + private static void Patterns() { Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact"); diff --git a/Tools/RynthILT.Tests/BankCommandTests.cs b/Tools/RynthILT.Tests/BankCommandTests.cs index c641d82..99c99b8 100644 --- a/Tools/RynthILT.Tests/BankCommandTests.cs +++ b/Tools/RynthILT.Tests/BankCommandTests.cs @@ -13,6 +13,60 @@ internal static class BankCommandTests r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals); r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals); r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies); + r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable); + r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers); + r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies); + } + + private static int TransferIndex(string code) => + System.Array.FindIndex(IltBankCommands.Transfers, t => t.Code == code); + + private static void ItemTable() + { + string Codes(System.Collections.Generic.IEnumerable codes) => string.Join(",", codes); + // ACECustom HandleBank (upstream 976606695): deposit everything; withdraw all but peas and + // luminance tokens; transfer all but those and the bound prestige coins. + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Deposits, d => d.Args)), ",p,ps,l,lum,k,mk,e,we,pc,n", "deposits"); + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Withdrawals, w => w.Code)), "p,l,k,mk,e,we,pc,n", "withdrawals"); + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Transfers, t => t.Code)), "p,l,k,mk,e,we,n", "transfers"); + Check.Eq(TransferIndex("pc"), -1, "prestige coins are bound: never offered for transfer"); + Check.Eq(TransferIndex("ps"), -1, "pyreal peas: deposit only"); + Check.Eq(IltBanking.Currencies.Length, IltBankCommands.Transfers.Length, "the transfer form uses the table"); + Check.Eq(IltBanking.Currencies[0].Code, "p", "saved transfer index 0 is still pyreals"); + Check.Eq(IltBanking.Currencies[5].Code, "we", "saved transfer indexes 0-5 keep their currency"); + } + + private static void Transfers() + { + int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 250_000, -1, "Bob", out _), "/bank t p 250000 Bob", "pyreals"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("mk"), 3, -1, " Bob ", out _), "/bank t mk 3 Bob", "name trimmed"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("l"), 10, -1, "Some Name", out _), "/bank t l 10 \"Some Name\"", + "a name with a space is quoted (the server reads one argument)"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, mmd, "Bob", out _), "/bank t n mmd 4 Bob", "four 250K notes"); + Check.True(IltBankCommands.IsNoteTransfer(TransferIndex("n")), "notes transfer by denomination"); + Check.False(IltBankCommands.IsNoteTransfer(TransferIndex("p")), "pyreals don't"); + Check.Eq(IltBankCommands.NoteValue(mmd, 4), 1_000_000L, "4 x 250K"); + + Check.Eq(IltBankCommands.Transfer(-1, 10, -1, "Bob", out string e1), "", "no currency refused"); + Check.Eq(e1, "Pick a currency.", "why"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 0, -1, "Bob", out _), "", "zero refused"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, " ", out string e2), "", "no recipient refused"); + Check.Eq(e2, "Enter a recipient.", "why"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, "Bob\" x", out _), "", "a quote can't break out of the name"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, 99, "Bob", out _), "", "bad denomination refused"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), IltBankCommands.MaxNoteCount + 1, mmd, "Bob", out _), "", "too many notes refused"); + } + + private static void TransferReplies() + { + Check.True(IltBankCommands.IsTransferReply("Transferred 1,000,000 Pyreals to Bob"), "result"); + Check.True(IltBankCommands.IsTransferReply("(Equivalent to 4x MMD notes)"), "trade-note equivalent"); + Check.True(IltBankCommands.IsTransferReply("[BANK] Prestige Coins are bound to you and cannot be transferred."), "bound coins"); + Check.True(IltBankCommands.IsTransferReply("[Transfer] This command may only be run once every 5 seconds."), "throttled"); + Check.True(IltBankCommands.IsTransferReply("Invalid denomination. Use: i(100), v(500)"), "bad denomination"); + Check.False(IltBankCommands.IsTransferReply("[BANK] Pyreals: 1,000"), "a balance line is not"); + Check.False(IltBankCommands.IsTransferReply("Bob tells you, \"Transferred 5\""), "a tell is not"); } private static int DepositIndex(string args) => diff --git a/Tools/RynthILT.Tests/BreedingTests.cs b/Tools/RynthILT.Tests/BreedingTests.cs new file mode 100644 index 0000000..07b4b7d --- /dev/null +++ b/Tools/RynthILT.Tests/BreedingTests.cs @@ -0,0 +1,376 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +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. +internal static class BreedingTests +{ + public static void Register(Runner r) + { + r.Add("breeding: tier table has one WCID per tier in every family, no repeats", TierTable); + r.Add("breeding: rules come from the server, else the ILT profile, else ACE", RuleSources); + r.Add("breeding: stat mutation odds follow ACE's decay, floor and incense cap", MutationOdds); + r.Add("breeding: appraisal text gives the stud's charges, refill window and growth", AppraisalParse); + r.Add("breeding: chat lines give charges, the guardian, growth stages and events", ChatParse); + r.Add("breeding: @breed-debug reply is captured whole or line by line and parsed", DebugParse); + 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: saved state survives the hub.json source-generated serializer", StateJson); + r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion); + } + + private static IltBreedingRules Rules() => new(new IltBreedingState()); + + /// A healthy adult essence's facts (tier 150, bond 120, appraised). + private static BreedEssenceFacts Facts(int id, bool male, uint wcid = 48946) => new() + { + Id = id, + Name = (male ? "Stud " : "Dam ") + id, + Wcid = wcid, + HasId = true, + Bond = 120, + MaleOverride = male, + }; + + private static void TierTable() + { + var seen = new HashSet(); + foreach (uint[] row in IltBreedingEssence.Families) + { + Check.Eq(row.Length, IltBreedingEssence.Tiers.Length, "row " + row[0]); + foreach (uint w in row) Check.True(seen.Add(w), "WCID " + w + " appears once"); + } + Check.Eq(IltBreedingEssence.Families.Length, 36, "36 combat pet families"); + Check.Eq(IltBreedingEssence.TierOf(48942), 50, "first fire skeleton is tier 50"); + Check.Eq(IltBreedingEssence.TierOf(49212), 200, "an out-of-run WCID keeps its slot (tier 200)"); + Check.Eq(IltBreedingEssence.TierOf(787801072), 300, "the last tier-300 essence"); + Check.Eq(IltBreedingEssence.TierOf(12345, 125), 125, "unknown WCID: a tier-valued level requirement"); + Check.Eq(IltBreedingEssence.TierOf(12345, 126), 0, "unknown WCID, odd level: unknown tier"); + Check.True(IltBreedingEssence.IsCombatEssence(49551), "range end is included"); + } + + private static void RuleSources() + { + IltBreedingRules r = Rules(); + Check.Eq(r.Value(IltBreedingRules.MinTier).Source, BreedRuleSource.AceDefault, "min tier: ACE default"); + Check.Eq(r.GetInt(IltBreedingRules.MinTier), 100, "min tier 100"); + Check.Eq(r.Value(IltBreedingRules.MutationDecay).Source, BreedRuleSource.IltProfile, "decay: ILT profile"); + Check.Near(r.Get(IltBreedingRules.MutationDecay), 0.1, 1e-9, "ILT decay 0.1"); + Check.Near(r.Get(IltBreedingRules.GuardianEnabled), 1, 1e-9, "ILT runs the mating guardian"); + + DateTime t = new(2026, 10, 15, 12, 0, 0, DateTimeKind.Utc); + Check.True(r.Learn(IltBreedingRules.MaleCharges, 12, t), "a new value is a change"); + Check.False(r.Learn(IltBreedingRules.MaleCharges, 12, t), "the same value again isn't"); + Check.Eq(r.Value(IltBreedingRules.MaleCharges).Source, BreedRuleSource.Server, "learned: seen on server"); + Check.Eq(r.GetInt(IltBreedingRules.MaleCharges), 12, "learned value wins"); + Check.False(r.Learn("not_a_rule", 1, t), "unknown keys are ignored"); + Check.Eq(r.RoomText(), "landblock 0x0106 variant 2", "Seedy Motel room"); + + IltBreedingRules frozen = r.Frozen(); + r.Learn(IltBreedingRules.MaleCharges, 8, t); + Check.Eq(frozen.GetInt(IltBreedingRules.MaleCharges), 12, "a frozen copy doesn't follow later learning"); + + Check.Eq(r.StageName(2), "Whelp", "default stage names"); + Check.True(r.LearnStageName(2, "Pup"), "a server's own stage name"); + Check.Eq(r.StageName(2), "Pup", "seen name wins"); + for (int i = 0; i < IltBreedingRules.MaxEvents + 5; i++) r.AddEvent("x", "e" + i, t); + Check.Eq(r.State.Log.Count, IltBreedingRules.MaxEvents, "event log is capped"); + Check.Eq(r.State.Log[^1].Text, "e" + (IltBreedingRules.MaxEvents + 4), "newest kept last"); + } + + private static void MutationOdds() + { + IltBreedingRules r = Rules(); + Check.Near(r.StatMutationChance(0, 0), 0.05, 1e-9, "base 5%"); + Check.Near(r.StatMutationChance(4, 0), 0.05 / 1.4, 1e-9, "decay 0.1 x 4 mutations"); + Check.Near(r.StatMutationChance(0, 0.10), 0.15, 1e-9, "exquisite incense adds 10%"); + Check.Near(r.CombinedIncense(0.4, 0.3), 0.5, 1e-9, "both parents' incense capped at 50%"); + r.Learn(IltBreedingRules.MutationDecay, 10, DateTime.UtcNow); + Check.Near(r.StatMutationChance(4, 0), 0.02, 1e-9, "never below the 2% floor"); + } + + private static void AppraisalParse() + { + double now = 1_800_000_000; + double lastRefill = now - (20 * 3600 + 50 * 60); + string desc = "A fire skeleton essence.\nSex: Male (9/12 breeding charges today) - refills in 3h 10m\nBond: Unbound (imprints on first summon)"; + var seen = IltBreedingRules.FromAppraisal(desc, lastRefill, now); + Check.True(seen.Contains((IltBreedingRules.MaleCharges, 12)), "max charges from the stud line"); + Check.True(seen.Contains((IltBreedingRules.MaleRefillHours, 24)), "refill window from the countdown"); + + string growth = "Sex: Female (ready to breed)\nGrowth: Whelp 2/5 - 75 kills to Juvenile, 195 to Adult"; + Check.True(IltBreedingRules.FromAppraisal(growth, 0, now).Contains((IltBreedingRules.MaturityStages, 5)), "stage count"); + Check.True(IltBreedingRules.TryParseGrowth(growth, out string name, out int stage, out int stages, out int toNext, out string next, out int toAdult), "growth line"); + Check.Eq(name, "Whelp", "stage name"); + Check.Eq(stage, 2, "stage"); + Check.Eq(stages, 5, "stages"); + Check.Eq(toNext, 75, "to next"); + Check.Eq(next, "Juvenile", "next stage"); + Check.Eq(toAdult, 195, "to adult"); + + Check.True(IltBreedingRules.TryParseGrowth("Growth: Young Adult 5/5 - 60 kills to Adult", out name, out stage, out _, out toNext, out next, out toAdult), "last stage"); + Check.Eq(name, "Young Adult", "two-word stage name"); + Check.Eq(next, "Adult", "last stage leads to Adult"); + Check.Eq(toAdult, 60, "last stage: to adult = to next"); + Check.False(IltBreedingRules.TryParseGrowth("Growth: Adult", out _, out _, out _, out _, out _, out _), "an adult has no countdown"); + } + + private static void ChatParse() + { + var a = IltBreedingRules.FromChat("[Breeding] Fire Skeleton Essence spent a breeding charge: 7/12 left today."); + Check.True(a.Contains((IltBreedingRules.MaleCharges, 12)), "charge line gives the max"); + var g = IltBreedingRules.FromChat("The union stirs something... Mating Spirit rises before A and B! Only the two parents can harm it. They have 120s to bring it down together."); + Check.True(g.Contains((IltBreedingRules.GuardianEnabled, 1)), "guardian on"); + Check.True(g.Contains((IltBreedingRules.GuardianSeconds, 120)), "guardian timer"); + var d = IltBreedingRules.FromChat("[Breeding] Your pet performs the courtship dance, waiting for a partner... (Your partner must have their pet summoned in the same room and *dance* within 5 seconds)."); + Check.True(d.Contains((IltBreedingRules.DanceWindow, 5)), "dance window"); + Check.Eq(IltBreedingRules.FromChat("You say, \"hello\"").Count, 0, "ordinary chat says nothing"); + + Check.True(IltBreedingRules.TryParseGrownInto("Pup has grown into a Whelp! Its body swells with new strength. (2/5)", out int stage, out string name), "growth line"); + Check.Eq(stage, 2, "stage number"); + Check.Eq(name, "Whelp", "stage name"); + + Check.Eq(IltPetBreeding.EventKind("The mating ritual has begun between A and B..."), "ritual", "ritual"); + Check.Eq(IltPetBreeding.EventKind("Congratulations! A baby pet has been born: Pup! Placed in Bob's inventory."), "birth", "birth"); + Check.Eq(IltPetBreeding.EventKind("A baby pet has been born: Pup! Bob's packs are full, so the baby has been tucked away"), "birth", "deferred birth"); + Check.Eq(IltPetBreeding.EventKind("Pup has reached adulthood! It stands at its full size"), "adult", "adulthood"); + Check.Eq(IltPetBreeding.EventKind("Pup has imprinted on you. It is now bound to this character"), "imprint", "imprint"); + Check.Eq(IltPetBreeding.EventKind("[Breeding] The spectral guardian dissolves back into the ether..."), "guardian", "guardian lost"); + Check.Eq(IltPetBreeding.EventKind("Bob tells you, \"breed?\""), null, "not a breeding line"); + } + + private const string DebugReply = + "=== PET BREEDING DIAGNOSTICS ===\n" + + "Breeding System Enabled: True\n" + + "Your Location: Landblock=0x0106, Cell=0x01060186, Variant=2\n" + + "Allowed Target: whole landblock 0x106, Variant=2 => Location Match: VALID (Room OK)\n" + + "Your Active Pet: Fire Skeleton (WCID 48900) | Device: Fire Skeleton Essence\n" + + " Sex: Male (9/10 charges)\n" + + "Eligible breeding partners nearby: 1\n" + + "================================\n"; + + private static void DebugParse() + { + Check.True(IltBreedingRules.IsDebugLine(DebugReply.TrimEnd('\n')), "whole message is a reply line"); + Check.True(IltBreedingRules.IsDebugEnd(DebugReply.TrimEnd('\n')), "whole message ends the reply"); + Check.True(IltBreedingRules.IsDebugEnd("================================"), "rule line alone ends it"); + Check.False(IltBreedingRules.IsDebugEnd("=== PET BREEDING DIAGNOSTICS ==="), "the header doesn't"); + Check.False(IltBreedingRules.IsDebugLine("Bob says, \"hi\""), "chat isn't"); + + BreedDebugInfo whole = IltBreedingRules.ParseDebug(new[] { DebugReply }); + BreedDebugInfo split = IltBreedingRules.ParseDebug(DebugReply.Split('\n')); + foreach (BreedDebugInfo d in new[] { whole, split }) + { + Check.Eq(d.Enabled, (bool?)true, "enabled"); + Check.Eq(d.AllowedLandblock, 0x106u, "landblock"); + Check.Eq(d.AllowedVariant, 2, "variant"); + Check.Eq(d.AllowedKind, "whole landblock", "kind"); + Check.Eq(d.LocationOk, (bool?)true, "in the room"); + Check.Eq(d.Partners, 1, "partners"); + Check.Eq(d.PetSex, "Male (9/10 charges)", "pet sex line"); + } + var rules = IltBreedingRules.FromChat(DebugReply); + Check.True(rules.Contains((IltBreedingRules.Landblock, 0x106)), "room landblock learned"); + Check.True(rules.Contains((IltBreedingRules.Variant, 2)), "room variant learned"); + } + + private static void Gates() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + + BreedEssence full = IltBreedingEssence.Evaluate(Facts(1, true), r, now); + Check.True(full.Ready, "a stud that never bred is full"); + Check.Eq(full.Charges, 10, "10 charges"); + Check.Eq(full.Tier, 125, "48946 is tier 125"); + + var spent = Facts(2, true); + spent.MaleCharges = 0; + spent.MaleRefreshUnix = now - 2 * 3600; + BreedEssence noCharge = IltBreedingEssence.Evaluate(spent, r, now); + Check.Eq(noCharge.Gate, BreedGate.NoCharges, "no charges"); + Check.Near(noCharge.ReadyAtUnix, now + 22 * 3600, 1, "refills 24h after the last refill"); + + spent.MaleRefreshUnix = now - 25 * 3600; + Check.True(IltBreedingEssence.Evaluate(spent, r, now).Ready, "refilled once the window passed (the server refills on read)"); + + var dam = Facts(3, false); + dam.NextBreedUnix = now + 3600 + 300; + BreedEssence resting = IltBreedingEssence.Evaluate(dam, r, now); + Check.Eq(resting.Gate, BreedGate.Resting, "resting dam"); + Check.Eq(resting.Status, "Rest 1h 05m", "rest countdown"); + + var neut = Facts(4, false); + neut.Neutered = true; + Check.Eq(IltBreedingEssence.Evaluate(neut, r, now).Gate, BreedGate.Neutered, "neutered"); + + var shiny = Facts(5, true); + shiny.LongDesc = "Sex: Male (shiny - cannot breed)"; + Check.Eq(IltBreedingEssence.Evaluate(shiny, r, now).Gate, BreedGate.Shiny, "shiny"); + + var baby = Facts(6, false); + baby.JuvenileFlag = true; + baby.MaturityKills = 130; + BreedEssence growing = IltBreedingEssence.Evaluate(baby, r, now); + Check.Eq(growing.Gate, BreedGate.Growing, "juvenile"); + Check.Eq(growing.Stage, 3, "130 kills of 300 over 5 stages: stage 3"); + Check.Eq(growing.StageName, "Juvenile", "stage 3 name"); + Check.Eq(growing.KillsToNext, 50, "50 kills to stage 4"); + + var weak = Facts(7, true); + weak.Bond = 40; + Check.Eq(IltBreedingEssence.Evaluate(weak, r, now).Gate, BreedGate.LowBond, "bond under 100"); + + BreedEssence low = IltBreedingEssence.Evaluate(Facts(8, true, 48944), r, now); + Check.Eq(low.Gate, BreedGate.LowTier, "tier 80 is under the minimum"); + + var unread = Facts(9, true); + unread.HasId = false; + Check.Eq(IltBreedingEssence.Evaluate(unread, r, now).Gate, BreedGate.NeedsId, "not appraised yet"); + + var boosted = Facts(10, false); + boosted.Incense = 0.05; + boosted.Catalyst = true; + BreedEssence b = IltBreedingEssence.Evaluate(boosted, r, now); + Check.Eq(string.Join("|", b.Boosters), "Refined incense +5%|Chromatic Catalyst", "boosters listed"); + } + + private static void Planner() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + var sf = Facts(1, true); + sf.MutDamage = 2; + sf.MutCrit = 1; + sf.Incense = 0.10; + var df = Facts(2, false); + df.MutDamage = 0; + df.MutCrit = 3; + BreedEssence stud = IltBreedingEssence.Evaluate(sf, r, now), dam = IltBreedingEssence.Evaluate(df, r, now); + + BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, r); + Check.True(p.CanBreed, "both ready"); + Check.Eq(p.InheritMin, 1, "lower lines: damage 0 + crit 1"); + Check.Eq(p.InheritMax, 5, "higher lines: damage 2 + crit 3"); + Check.Near(p.ChanceBest, 0.15 / 1.1, 1e-9, "best: 1 mutation, incense 10%"); + Check.Near(p.ChanceWorst, 0.15 / 1.5, 1e-9, "worst: 5 mutations"); + Check.Near(p.PotencyChance, 0.03, 1e-9, "potency 3%"); + + BreedPairPlan wrong = IltBreedingPlanner.Plan(dam, stud, r); + Check.False(wrong.CanBreed, "swapped sexes"); + Check.True(wrong.Blockers.Any(b => b.Contains("must be male")), "says the stud must be male"); + } + + private static void Supplies() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + BreedSupplyDef lesser = IltBreedingSupplies.Find(IltBreedingSupplies.LesserIncense)!; + BreedSupplyDef exquisite = IltBreedingSupplies.Find(IltBreedingSupplies.ExquisiteIncense)!; + BreedSupplyDef draught = IltBreedingSupplies.Find(IltBreedingSupplies.Draught)!; + BreedSupplyDef offering = IltBreedingSupplies.Find(IltBreedingSupplies.Offering)!; + BreedSupplyDef neuter = IltBreedingSupplies.Find(IltBreedingSupplies.NeuteringKit)!; + + var f = Facts(1, false); + f.Incense = 0.05; + BreedEssence primed = IltBreedingEssence.Evaluate(f, r, now); + Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, primed, r), "weaker incense refused"); + Check.Null(IltBreedingSupplies.RefuseReason(exquisite, primed, r), "stronger incense taken"); + Check.True(IltBreedingSupplies.Warning(exquisite, primed).Contains("+5%"), "and warns the +5% is lost"); + + var n = Facts(2, false); + n.Neutered = true; + Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, IltBreedingEssence.Evaluate(n, r, now), r), "no incense on a neutered essence"); + + BreedEssence adult = IltBreedingEssence.Evaluate(Facts(3, true), r, now); + Check.NotNull(IltBreedingSupplies.RefuseReason(draught, adult, r), "draught: juveniles only"); + var j = Facts(4, true); + j.JuvenileFlag = true; + j.MaturityKills = 0; + Check.Null(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "draught on a juvenile"); + j.MaturityXpMult = 2.0; + Check.NotNull(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "not twice"); + + Check.Null(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering with the guardian on"); + r.Learn(IltBreedingRules.GuardianEnabled, 0, DateTime.UtcNow); + Check.NotNull(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering refused with the guardian off"); + Check.NotNull(IltBreedingSupplies.RefuseReason(neuter, adult, r), "the neutering kit is never used from here"); + Check.Eq(IltBreedingSupplies.PriceText(1_250_000), "1.25M", "price text"); + } + + private static void ReaderJson() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + var stud = IltBreedingEssence.Evaluate(Facts(11, true), r, now); + var dam = IltBreedingEssence.Evaluate(Facts(12, false), r, now); + var events = new[] { new IltBreedingEvent { Utc = new DateTime(2026, 10, 15, 20, 0, 0, DateTimeKind.Utc), Kind = "birth", Text = "A \"baby\" was born" } }; + var supplies = IltBreedingSupplies.All.Select(s => (s, s.Key == IltBreedingSupplies.RefinedIncense ? 2L : 0L)).ToList(); + var snap = new BreedingSnapshot(new[] { stud, dam }, supplies, r.All(), events, + IltBreedingRules.ParseDebug(new[] { DebugReply }), DateTime.UtcNow, IltTri.On, IltTri.On, IltTri.On, + r.RoomText(), 5, "hello", now, true, r.Frozen()); + + string json = IltPetBreeding.BuildJson(snap, r, "InfiniteLeaftide"); + using (JsonDocument.Parse(json)) { } // well-formed + IltBreedingView v = IltBreedingView.Parse(json); + Check.True(v.Loaded && v.Available, "loaded"); + Check.Eq(v.Enabled, "on", "enabled"); + Check.Eq(v.Room, "landblock 0x0106 variant 2", "room"); + Check.Eq(v.FreeSlots, 5, "free slots"); + Check.Eq(v.Essences.Count, 2, "two essences"); + Check.True(v.Essences[0].Male && v.Essences[0].Ready, "stud row"); + Check.Eq(v.Pairs.Count, 1, "one ready pairing"); + Check.Near(v.Pairs[0].ChanceBest, 0.05, 1e-6, "pair odds"); + IltBreedSupplyRow refined = v.Supplies.First(s => s.Key == IltBreedingSupplies.RefinedIncense); + Check.Eq(refined.Count, 2L, "supply count"); + Check.Eq(refined.Targets.Count, 2, "both essences can take it"); + Check.Eq(v.Supplies.First(s => s.Key == IltBreedingSupplies.LesserIncense).Targets.Count, 0, "none carried: no targets"); + Check.Eq(v.Rules.Count, IltBreedingRules.Defs.Length, "every rule"); + Check.Eq(v.Events[0].Text, "A \"baby\" was born", "quotes escaped and read back"); + Check.Eq(v.Debug?.Match, "valid", "diagnostics"); + Check.Eq(IltBreedingView.ApplyVerb(" incense2 ", 12), "apply incense2 12", "apply verb"); + } + + private static void StateJson() + { + var state = new IltHubState(); + var rules = new IltBreedingRules(state.Pet.Breeding); + rules.Learn(IltBreedingRules.MaleCharges, 12, new DateTime(2026, 10, 15, 0, 0, 0, DateTimeKind.Utc)); + rules.LearnStageName(1, "Hatchling"); + rules.AddEvent("birth", "born", DateTime.UtcNow); + string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState); + IltHubState back = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState)!; + var again = new IltBreedingRules(back.Pet.Breeding); + Check.Eq(again.GetInt(IltBreedingRules.MaleCharges), 12, "learned rule saved"); + Check.Eq(again.StageName(1), "Hatchling", "stage name saved"); + Check.Eq(back.Pet.Breeding.Log.Count, 1, "event saved"); + + IltHubState old = JsonSerializer.Deserialize("{\"Pet\":{\"PetLog\":[\"a\"]}}", IltHubJsonContext.Default.IltHubState)!; + Check.NotNull(old.Pet.Breeding, "a hub.json from before the tracker gets an empty breeding state"); + } + + private static unsafe void DataApiVersion() + { + Check.Eq(RynthIltDataApiV1.InterfaceVersion, 2u, "version 2"); + Check.True(RynthIltDataApiV1.V1Size < (uint)sizeof(RynthIltDataApiV1), "v2 appends to v1"); + 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"); + 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/ChunkTests.cs b/Tools/RynthILT.Tests/ChunkTests.cs new file mode 100644 index 0000000..0d8c931 --- /dev/null +++ b/Tools/RynthILT.Tests/ChunkTests.cs @@ -0,0 +1,36 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Lugian-hammer chunking (Hub/IltChunkClap.cs): only the Lugian Aetheria Hammer is the tool, and +// ILT's result lines name the item and the tool. Ported from SilentKelpie's fix (2026-10-15). +internal static class ChunkTests +{ + public static void Register(Runner r) + { + r.Add("chunk: only the Lugian Aetheria Hammer is the tool, never a Lugian Hammer weapon", HammerOnly); + r.Add("chunk: ILT's result lines (item and tool named) end the wait; combat lines don't", ResultLines); + } + + /// The Flaming Lugian Hammer (a loot weapon) matched " Lugian Hammer", chunked nothing, + /// and all 9 Coalesced Aetheria timed out into the skip list. + private static void HammerOnly() + { + Check.True(IltChunkClap.IsChunkHammer("Lugian Aetheria Hammer"), "the ILT tool"); + Check.True(IltChunkClap.IsChunkHammer("lugian aetheria hammer"), "any case"); + Check.False(IltChunkClap.IsChunkHammer("Flaming Lugian Hammer"), "a loot weapon is not the tool"); + Check.False(IltChunkClap.IsChunkHammer("Lugian Hammer"), "nor the plain one"); + Check.False(IltChunkClap.IsChunkHammer("Acid Lugian Hammer"), "nor any variant"); + } + + private static void ResultLines() + { + Check.Eq(IltChunkClap.ClassifyChat("You smash the Corrupted Sword with the Lugian Aetheria Hammer."), IltChunkClap.ChunkResult.Done, "ILT corrupted line"); + Check.Eq(IltChunkClap.ClassifyChat("You smash the aetheria with the hammer."), IltChunkClap.ChunkResult.Done, "aetheria line"); + Check.Eq(IltChunkClap.ClassifyChat("The aetheria is too powerful to chunk."), IltChunkClap.ChunkResult.Refused, "refused"); + Check.Eq(IltChunkClap.ClassifyChat("You're too busy!"), IltChunkClap.ChunkResult.Busy, "busy"); + Check.Eq(IltChunkClap.ClassifyChat("You smash Corrupted Shadow for 147 points of bludgeoning damage!"), IltChunkClap.ChunkResult.None, + "a combat line naming a corrupted monster is no result"); + } +} diff --git a/Tools/RynthILT.Tests/DataApiTests.cs b/Tools/RynthILT.Tests/DataApiTests.cs new file mode 100644 index 0000000..55d53da --- /dev/null +++ b/Tools/RynthILT.Tests/DataApiTests.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// "RynthILT.Data" v1 (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs): the bank JSON RynthILT +// builds (Hub/IltBankExport.cs) read back by the shared reader, the bank verb lines a reader sends +// (IltBanking.RunVerb splits them), and the table itself. The charms JSON is MoveTests' +// CharmsReaderJson. No plugin in this tree reads the interface yet. +internal static class DataApiTests +{ + public static void Register(Runner r) + { + 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); + // Last: Release() switches the table off for the rest of the process. + r.Add("data: the RynthILT.Data table: query, functions, release", DataTable); + } + + private static void BankRoundTrip() + { + var me = new IltBankState { Pyreals = 1_500_000, Luminance = 42, PrestigeCoins = 3, + LastUpdated = new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc).ToLocalTime() }; + var alt = new IltBankState { Pyreals = 7, LegendaryKeys = 2, LastUpdated = DateTime.Now }; + var tx = new List(); + for (int i = 0; i < IltBankExport.MaxTransactions + 5; i++) + tx.Add(new IltBankTransaction { Timestamp = new DateTime(2026, 10, 1).AddMinutes(i), Type = i % 2 == 0 ? "Sent" : "Received", + Currency = "Pyreals", Amount = i, OtherPlayer = "Bob \"the\" Builder" }); + string json = IltBankExport.Build(true, 1, "InfiniteLeaftide", "Zed", + new[] { new IltBankExport.Row("Alt", false, alt), new IltBankExport.Row("Zed", true, me) }, + "Deposited 5 Pyreals", tx); + Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); + + IltBankView v = IltBankView.Parse(json); + Check.True(v.Loaded && v.Available, "loaded, ILT"); + Check.Eq(v.Enabled, 1, "the server has /bank"); + Check.Eq(v.World, "InfiniteLeaftide", "world"); + Check.Eq(v.Character, "Zed", "character"); + Check.Eq(v.Result, "Deposited 5 Pyreals", "last result"); + Check.Eq(v.Characters.Count, 2, "both characters"); + Check.True(v.Characters[0].Current && v.Characters[0].Name == "Zed", "the current character first"); + Check.Eq(v.Characters[0].Pyreals, 1_500_000L, "pyreals"); + Check.Eq(v.Characters[0].PrestigeCoins, 3L, "prestige coins"); + Check.Eq(v.Characters[0].UpdatedUtc, new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "updated, in UTC"); + Check.Eq(v.Characters[1].LegendaryKeys, 2L, "the other character's keys"); + + Check.Eq(v.Deposits.Count, IltBankCommands.Deposits.Length, "every deposit choice"); + Check.Eq(v.Withdrawals.Count, IltBankCommands.Withdrawals.Length, "every withdraw choice"); + Check.Eq(v.Transfers.Count, IltBankCommands.Transfers.Length, "every transfer choice"); + Check.True(v.Transfers.Single(t => t.Notes).Label == "Trade notes", "only trade notes count notes"); + Check.Eq(v.Notes.Count, IltBankCommands.NoteDenominations.Length, "every note denomination"); + Check.Eq(v.Notes[^1].Value, 250_000L, "MMD is 250K"); + + Check.Eq(v.Transactions.Count, IltBankExport.MaxTransactions, "the log is capped"); + Check.Eq(v.Transactions[0].Amount, (long)(IltBankExport.MaxTransactions + 4), "newest first"); + Check.Eq(v.Transactions[0].Player, "Bob \"the\" Builder", "quotes in a name survive"); + } + + private static void BankVerbs() + { + Check.Eq(IltBankView.RefreshVerb(), "refresh", "refresh"); + Check.Eq(IltBankView.DepositVerb(3), "deposit 3", "deposit"); + Check.Eq(IltBankView.WithdrawVerb(7, 4, 9), "withdraw 7 4 9", "withdraw: index, amount, note"); + Check.Eq(IltBankView.TransferVerb(6, 2, 9, " Some Name "), "transfer 6 2 9 Some Name", "transfer: the name last, trimmed"); + foreach (string verb in new[] { IltBankView.RefreshVerb(), IltBankView.DepositVerb(0), IltBankView.WithdrawVerb(0, 1, -1), + IltBankView.TransferVerb(0, 1, -1, "Bob") }) + Check.True(verb.All(c => c >= 0x20 && c <= 0x7E), "ASCII verb (DataInterface refuses anything else): " + verb); + } + + private static void BankBadJson() + { + Check.True(ReferenceEquals(IltBankView.Parse(null), IltBankView.None), "null"); + Check.True(ReferenceEquals(IltBankView.Parse("{not json"), IltBankView.None), "broken"); + Check.True(ReferenceEquals(IltBankView.Parse("[1,2]"), IltBankView.None), "not an object"); + IltBankView empty = IltBankView.Parse("{}"); + Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known"); + } + + 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"); + 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->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize"); + Check.Eq(sizeof(RynthIltDataApiV1), 8 + 6 * IntPtr.Size, "header + 6 functions (v1's 4, then the breeding pair)"); + 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"); + 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. + byte* buf = stackalloc byte[64]; + Check.Eq(t->GetCharmsJson(buf, 64), 0, "no charms before login"); + Check.Eq(t->GetBankJson(buf, 64), 0, "no bank before login"); + Check.Eq(t->ToggleCharm(1234), 0, "no toggle before login"); + byte* verb = stackalloc byte[] { (byte)'r', (byte)'e', (byte)'f', (byte)'r', (byte)'e', (byte)'s', (byte)'h', 0 }; + 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"); + + DataInterface.Release(); + Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); + Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown"); + Check.Eq(t->GetBankJson(buf, 64), 0, "the old table stays callable and answers nothing"); + } +} diff --git a/Tools/RynthILT.Tests/FeatureCatalogTests.cs b/Tools/RynthILT.Tests/FeatureCatalogTests.cs new file mode 100644 index 0000000..227f2f5 --- /dev/null +++ b/Tools/RynthILT.Tests/FeatureCatalogTests.cs @@ -0,0 +1,141 @@ +using System; +using System.Text; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Leaftide feature list (IltFeatureCatalog): every feature the player asked RynthILT to cover is +// listed and the states follow the server bits. Also the NUL-terminated copy RynthILT's interfaces +// ("RynthServer.Profile", "RynthILT.Data") hand their JSON out with. +internal static class FeatureCatalogTests +{ + public static void Register(Runner r) + { + 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: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite); + 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); + } + + /// ACECustom options Infinite Leaftide runs with off (ServerConfig defaults, PROD_DEPLOY_PLAN.md). + private static readonly string[] OffInIlt = { "pet_strain", "pet_refill", "defense_scaling" }; + + /// Features the login probe (or the /myquests tracker) answers. + private static readonly string[] Probed = + { + "bank", "attributes", "augmentations", "enlightenment", "clap", "pets", "shinies", + "fellowship_blackjack", "quests", "quest_bonus", "powerball", "blackjack", + }; + + private static void ProfileOnWithTheWorld() + { + // The features the player asked about, plus the pet switches prod runs on (bond, potency). + foreach (string key in new[] { "bank_notes", "t11", "t11_craft_gate", "split_arrows", "charms", "pet_breeding", + "pet_maturity", "pet_bond", "pet_potency", "monster_capture", "universal_mastery", + "missile_power", "t11_hit_gate", "fship" }) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.Profile, key + " is on in the ILT profile"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.On, key + " on with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(f, false, _ => IltTri.On), IltTri.Unknown, key + " unknown off ILT"); + } + IltFeatureInfo mastery = IltFeatureCatalog.Find("universal_mastery")!; + Check.Eq(IltFeatureCatalog.StateOf(mastery, true, k => k == IltFeature.UniversalMastery ? IltTri.Off : IltTri.Unknown), + IltTri.Off, "a refusal in chat turns a profile feature off"); + Check.Null(IltFeatureCatalog.Find("fellowship_additive"), "upstream ACE's additive fellowship option isn't an ILT feature"); + } + + private static void ProbedAndOffInIlt() + { + foreach (string key in Probed) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.Checked, key + " is answered by the login probe"); + Check.Eq(IltFeatureCatalog.StateText(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown)), "checking", key + " reads 'checking' until then"); + } + foreach (string key in OffInIlt) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.ProfileOff, key + " is off in the ILT profile"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.Off, key + " off with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.On), IltTri.On, key + " on once the server shows it"); + Check.True(IltFeatureCatalog.Describe(key).Tooltip.Contains("Off in ILT"), key + "'s tooltip says it's off in ILT"); + } + + // ACECustom's three refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon) prove the refill is on. + Check.True(IltServerOptions.IsPyrealRefillLine("You restore one charge on your summoning essence at no cost."), "free refill"); + Check.True(IltServerOptions.IsPyrealRefillLine("You spend 1,000 pyreals to restore one charge on your summoning essence."), "paid refill"); + Check.True(IltServerOptions.IsPyrealRefillLine("You need 1,000 pyreals to auto-replenish your summoning essence. You do not have enough pyreals."), "refill too dear"); + Check.False(IltServerOptions.IsPyrealRefillLine("Your summoning essence is empty."), "an empty essence says nothing about the refill"); + } + + private static void Charms() + { + Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Unknown), IltTri.On, "a charm is on with the ILT world"); + Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Off), IltTri.Off, "a refused charm is off"); + Check.Eq(IltFeatureCatalog.CharmStateOf(false, IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); + + var (label, group, tooltip) = IltFeatureCatalog.Describe(IltFeature.Charm("Mana Barrier")); + Check.Eq(label, "Mana Barrier", "a charm row shows the charm's name"); + Check.Eq(group, IltFeatureCatalog.GroupCharms, "charms have their own section"); + Check.True(tooltip.Contains("Mana absorbs"), "the tooltip carries the charm's effect"); + Check.Eq(IltFeatureCatalog.Describe("something_new").Group, IltFeatureCatalog.GroupOther, "an unknown bit goes to Other"); + } + + private static readonly string[] Requested = + { + "bank", "guardian", "attributes", "augmentations", "paragon_armor", "paragon_weapons", + "paragon_jewelry", "split_arrows", "t11", "fellowship_large", "zone_share", "fellowship_blackjack", + }; + + private static void Listed() + { + foreach (string key in Requested) + Check.NotNull(IltFeatureCatalog.Find(key), "listed: " + key); + Check.Null(IltFeatureCatalog.Find("no_such_feature"), "an unknown key is not found"); + + var seen = new System.Collections.Generic.HashSet(StringComparer.OrdinalIgnoreCase); + foreach (IltFeatureInfo f in IltFeatureCatalog.All) + { + Check.True(seen.Add(f.Key), "keys are unique: " + f.Key); + Check.True(Array.IndexOf(IltFeatureCatalog.Groups, f.Group) >= 0, $"{f.Key} is in a known section ({f.Group})"); + Check.True(f.Label.Length > 0 && f.Where.Length > 0 && f.Description.Length > 0, f.Key + " has a label, a place and a description"); + } + } + + private static void States() + { + IltFeatureInfo bank = IltFeatureCatalog.Find("bank")!; + IltFeatureInfo guardian = IltFeatureCatalog.Find("guardian")!; + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.On), IltTri.On, "bank on when the server answers /bank"); + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Off), IltTri.Off, "bank off when the server says so"); + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Unknown), IltTri.Unknown, "bank unknown before the check"); + Check.Eq(IltFeatureCatalog.StateOf(guardian, true, _ => IltTri.Off), IltTri.On, "a built-in feature is on with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(guardian, false, _ => IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); + Check.Eq(IltFeatureCatalog.StateText(IltTri.Unknown), "checking", "unknown reads 'checking'"); + Check.Eq(IltFeatureCatalog.FellowshipMax(true), 29, "ILT fellowships hold 29"); + Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9"); + } + + private static unsafe void InterfaceWrite() + { + const string json = "{\"ilt\":true}"; + byte* small = stackalloc byte[4]; + small[0] = 0x55; + Check.Eq(ProfileInterface.Write(json, small, 4), json.Length, "too small: the length is returned"); + Check.Eq(small[0], (byte)0x55, "too small: nothing written"); + + byte* exact = stackalloc byte[json.Length]; + Check.Eq(ProfileInterface.Write(json, exact, json.Length), json.Length, "no room for the NUL: too small"); + + byte* big = stackalloc byte[64]; + int n = ProfileInterface.Write(json, big, 64); + Check.Eq(n, json.Length, "fits: the length without the NUL"); + Check.Eq(big[n], (byte)0, "NUL-terminated"); + Check.Eq(Encoding.UTF8.GetString(big, n), json, "the JSON copied whole"); + } +} diff --git a/Tools/RynthILT.Tests/FellowshipCommandTests.cs b/Tools/RynthILT.Tests/FellowshipCommandTests.cs new file mode 100644 index 0000000..fc772e9 --- /dev/null +++ b/Tools/RynthILT.Tests/FellowshipCommandTests.cs @@ -0,0 +1,97 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthILT.IltFellowship; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ILT's fellowship commands (IltFellowship/IltFellowshipCommands.cs, ACECustom /fship) and the +// "servercommands" format they are kept in (Plugins/Shared/ServerCommandShare.cs), checked together. +internal static class FellowshipCommandTests +{ + public static void Register(Runner r) + { + r.Add("ilt fellowship: the /fship list round-trips through the servercommands format", RoundTrip); + r.Add("ilt fellowship: chat lines quote multi-word names and need a name for create", Compose); + r.Add("ilt fellowship: bad commands and payloads are dropped", Rejects); + r.Add("ilt fellowship: RynthCore's verdict decides, else the world name", Active); + } + + private static void RoundTrip() + { + ServerCommandSet? set = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: true)); + Check.True(set != null, "parsed"); + Check.Eq(set!.Section, "fellowship", "section"); + Check.Eq(set.ServerId, "ilt", "server id"); + Check.Eq(set.ServerName, "Infinite Leaftide", "server name"); + Check.Eq(set.Commands.Count, IltFellowshipCommands.Commands.Count, "every command survives"); + for (int i = 0; i < set.Commands.Count; i++) + Check.Eq(set.Commands[i], IltFellowshipCommands.Commands[i], "command " + i); + Check.True(set.Commands.All(c => c.Command.StartsWith("/fship", StringComparison.Ordinal)), "all /fship"); + + ServerCommandSet? off = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: false)); + Check.True(off != null, "the clear parses"); + Check.Eq(off!.Commands.Count, 0, "the clear has no commands"); + } + + private static void Compose() + { + ServerCommand create = Find("Create"), invite = Find("Invite"), dismiss = Find("Dismiss"), list = Find("List nearby"); + Check.True(ServerCommandShare.Compose(create, "") == null, "create needs a name"); + Check.True(ServerCommandShare.Compose(create, " ") == null, "blank is no name"); + Check.Eq(ServerCommandShare.Compose(create, "Leaf"), "/fship create Leaf", "one word"); + Check.Eq(ServerCommandShare.Compose(create, " Leaf Hunters "), "/fship create \"Leaf Hunters\"", "quoted, spaces collapsed"); + Check.Eq(ServerCommandShare.Compose(invite, ""), "/fship add", "no name: the selected player"); + Check.Eq(ServerCommandShare.Compose(invite, "Raw Cigam"), "/fship add \"Raw Cigam\"", "multi-word player"); + Check.Eq(ServerCommandShare.Compose(dismiss, "Bo\"b\t"), "/fship remove Bob", "quotes and control characters dropped"); + Check.Eq(ServerCommandShare.Compose(list, "ignored"), "/fship list", "no argument taken"); + Check.True(dismiss.Confirm && Find("Disband").Confirm && Find("Leave").Confirm && Find("Invite landblock").Confirm, "risky ones ask"); + Check.False(invite.Confirm || list.Confirm || create.Confirm, "the rest don't"); + string longName = new string('x', 200); + Check.Eq(ServerCommandShare.CleanArgument(longName).Length, ServerCommandShare.MaxArgument, "argument capped"); + } + + private static void Rejects() + { + Check.True(ServerCommandShare.Parse(null) == null, "null"); + Check.True(ServerCommandShare.Parse("") == null, "empty"); + Check.True(ServerCommandShare.Parse("C\tX\t/fship\t\t\n") == null, "no S line"); + Check.True(ServerCommandShare.Parse("S\t\tilt\tILT\n") == null, "no section"); + + string payload = "S\tfellowship\tilt\tILT\n" + + "C\tNo slash\tfship list\t\t\n" + + "C\tSpace\t/ fship\t\t\n" + + "C\tQuote\t/fship add \"x\"\t\t\n" + + "C\t\t/fship list\t\tno label\n" + + "C\tLong\t/" + new string('a', ServerCommandShare.MaxCommand + 5) + "\t\t\n" + + "C\tShort\t/fship\t\n" + + "C\tGood\t/fship list\tzqA\ttip\n"; + ServerCommandSet? set = ServerCommandShare.Parse(payload); + Check.True(set != null, "parsed"); + Check.Eq(set!.Commands.Count, 1, "only the good command"); + Check.Eq(set.Commands[0].Flags, "A", "unknown flags dropped"); + + var many = Enumerable.Range(0, 40).Select(i => new ServerCommand("B" + i, "/fship list", "", "")); + string built = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", many.ToList())); + Check.Eq(ServerCommandShare.Parse(built)!.Commands.Count, ServerCommandShare.MaxCommands, "capped"); + + string tabbed = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", + new[] { new ServerCommand("A\tB", "/fship list", "", "line one\nline two") })); + ServerCommand c = ServerCommandShare.Parse(tabbed)!.Commands[0]; + Check.Eq(c.Label, "A B", "tab in a field becomes a space"); + Check.Eq(c.Tooltip, "line one line two", "newline in a field becomes a space"); + } + + private static void Active() + { + Check.True(IltFellowshipCommands.IsActive(true, "Coldeve"), "RynthCore says ILT"); + Check.False(IltFellowshipCommands.IsActive(false, "InfiniteLeaftide"), "RynthCore says not ILT"); + Check.True(IltFellowshipCommands.IsActive(null, "InfiniteLeaftide"), "no verdict yet: the world name"); + Check.False(IltFellowshipCommands.IsActive(null, "Coldeve"), "no verdict, another world"); + Check.False(IltFellowshipCommands.IsActive(null, null), "nothing known"); + } + + private static ServerCommand Find(string label) => + IltFellowshipCommands.Commands.First(c => c.Label == label); +} diff --git a/Tools/RynthILT.Tests/IltSettingsTests.cs b/Tools/RynthILT.Tests/IltSettingsTests.cs new file mode 100644 index 0000000..49be9d8 --- /dev/null +++ b/Tools/RynthILT.Tests/IltSettingsTests.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.IltSettingsView; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// RynthILT's copy of the ILT settings (IltSettingsView/IltSettingsModel.cs): RynthCore's server +// list (plugin API v86, GetServerStateJson: verdict, override, reason), the Hub's feature read, the +// engine verdict the Hub follows (IltEngineVerdict), and the RynthCore commands the view sends. +internal static class IltSettingsTests +{ + public static void Register(Runner r) + { + r.Add("ilt settings: RynthCore's server list gives the ILT verdict, override and reason", ServerList); + r.Add("ilt settings: a list without ILT, or no list at all, reads as such", NoIlt); + r.Add("ilt settings: the Hub's feature read is published whole", FeatureRead); + r.Add("ilt settings: the Hub follows RynthCore's ILT verdict once one arrives", EngineVerdict); + r.Add("ilt settings: override and world-name commands are checked before sending", Commands); + r.Add("ilt settings: logout clears the copy", ClearOnLogout); + } + + // GetServerStateJson as RynthCore writes it (UI/Sections/ServerStateJson.cs, schema 1). + private const string State = + "{\"schema\":1,\"revision\":3,\"host\":\"infiniteleaftide.online\",\"world\":\"InfiniteLeaftide\",\"pick\":\"auto\"," + + "\"active\":\"ilt\",\"activeName\":\"Infinite Leaftide\",\"activePlugin\":\"RynthILT\",\"servers\":[" + + "{\"id\":\"ilt\",\"name\":\"Infinite Leaftide\",\"active\":true,\"detected\":false,\"force\":\"on\",\"builtIn\":true," + + "\"plugin\":\"RynthILT\",\"reason\":\"forced on for this character\"}," + + "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":false,\"detected\":false,\"force\":\"auto\",\"builtIn\":true," + + "\"plugin\":\"\",\"reason\":\"not detected\"}]}"; + + private const string NoIltState = + "{\"schema\":1,\"revision\":1,\"active\":\"\",\"servers\":[" + + "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":true,\"detected\":true,\"force\":\"auto\"}]}"; + + private static void ServerList() + { + IltEngineView? v = IltSettingsModel.FromServerState(EngineServerState.Parse(State)); + Check.True(v?.Server != null, "the ILT server is there"); + Check.Eq(v!.Server!.Name, "Infinite Leaftide", "name"); + Check.True(v.Server.Active, "active"); + Check.False(v.Server.Detected, "not detected (forced)"); + Check.Eq(v.Server.Force, "on", "override"); + Check.Eq(v.Server.Reason, "forced on for this character", "reason"); + + IltEngineView? odd = IltSettingsModel.FromServerState(EngineServerState.Parse( + "{\"schema\":1,\"servers\":[{\"id\":\"ILT\",\"force\":\"WEIRD\"}]}")); + Check.True(odd?.Server != null, "the id ignores case"); + Check.Eq(odd!.Server!.Force, "auto", "an unknown override shows as auto"); + Check.Eq(odd.Server.Name, "Infinite Leaftide", "a missing name gets the server's"); + Check.False(odd.Server.Active, "a missing flag is off"); + } + + private static void NoIlt() + { + IltEngineView? none = IltSettingsModel.FromServerState(EngineServerState.Parse(NoIltState)); + Check.True(none != null && none.Server == null, "a list without ILT says so (not 'waiting')"); + Check.True(IltSettingsModel.FromServerState(null) == null, "no list: nothing"); + Check.True(EngineServerState.Parse("") == null && EngineServerState.Parse("{\"schema\":2}") == null, "empty or another schema: no list"); + + var model = new IltSettingsModel(); + model.ApplyServerState(EngineServerState.Parse(State)); + model.ApplyServerState(null); + Check.True(model.Engine?.Server?.Active == true, "no answer keeps the last list"); + } + + private static void FeatureRead() + { + var model = new IltSettingsModel(); + var read = new IltFeatureView("Infinite Leaftide", "probe", "12:00:00", Checking: true, IltLike: true, + new[] { new KeyValuePair("bank", 1) }); + model.PublishFeatures(read); + Check.True(ReferenceEquals(model.Features, read), "published as is"); + model.PublishFeatures(null); + Check.True(model.Features == null, "cleared while there is no Hub"); + Check.Eq(IltSettingsModel.StateText(1), "on", "1 is on"); + Check.Eq(IltSettingsModel.StateText(0), "off", "0 is off (not unknown)"); + Check.Eq(IltSettingsModel.StateText(-1), "unknown", "-1 is unknown"); + } + + private static void EngineVerdict() + { + var model = new IltSettingsModel(); + try + { + IltEngineVerdict.Attach(model); + Check.False(IltEngineVerdict.Pushed, "nothing sent yet"); + Check.True(IltEngineVerdict.Active == null, "no verdict: RynthILT's own list decides"); + model.ApplyServerState(EngineServerState.Parse(State)); + Check.True(IltEngineVerdict.Pushed, "sent"); + Check.True(IltEngineVerdict.Active == true, "RynthCore says ILT"); + model.ApplyServerState(EngineServerState.Parse(NoIltState)); + Check.True(IltEngineVerdict.Pushed && IltEngineVerdict.Active == null, "a list without ILT gives no ILT verdict"); + model.Clear(); + Check.False(IltEngineVerdict.Pushed, "logout forgets it"); + } + finally { IltEngineVerdict.Attach(null); } + Check.True(IltEngineVerdict.Active == null, "detached"); + } + + private static void Commands() + { + Check.Eq(IltSettingsModel.ForceCommand("on"), "/rc server ilt on", "on"); + Check.Eq(IltSettingsModel.ForceCommand("auto"), "/rc server ilt auto", "auto"); + Check.Eq(IltSettingsModel.ForceCommand("maybe"), "", "unknown mode sends nothing"); + Check.Eq(IltSettingsModel.NamesListCommand, "/rc server names ilt", "the names are listed by RynthCore"); + + Check.Eq(IltSettingsModel.NamesCommand(true, " *Frost* ", out _), "/rc server names ilt add *Frost*", "add, trimmed"); + Check.Eq(IltSettingsModel.NamesCommand(false, "Infinite Leaftide", out _), "/rc server names ilt remove Infinite Leaftide", "remove"); + Check.Eq(IltSettingsModel.NamesCommand(true, "", out string e1), "", "empty refused"); + Check.True(e1.Length > 0, "with a reason"); + Check.Eq(IltSettingsModel.NamesCommand(true, new string('a', IltSettingsModel.MaxPattern + 1), out _), "", "too long refused"); + Check.Eq(IltSettingsModel.NamesCommand(true, "x\n/rc reload", out _), "", "a line break can't start a second command"); + Check.Eq(IltSettingsModel.NamesCommand(true, "a/b", out _), "", "no '/'"); + } + + private static void ClearOnLogout() + { + var model = new IltSettingsModel(); + model.ApplyServerState(EngineServerState.Parse(State)); + model.PublishFeatures(new IltFeatureView("w", "", "", false, true, Array.Empty>())); + Check.True(model.Engine != null && model.Features != null, "both copies"); + model.Clear(); + Check.True(model.Engine == null && model.Features == null, "cleared"); + } +} diff --git a/Tools/RynthILT.Tests/MoveTests.cs b/Tools/RynthILT.Tests/MoveTests.cs index 609088c..39e5f59 100644 --- a/Tools/RynthILT.Tests/MoveTests.cs +++ b/Tools/RynthILT.Tests/MoveTests.cs @@ -32,6 +32,9 @@ internal static class MoveTests r.Add("move: the interface structs have the agreed layout", InterfaceLayout); r.Add("move: server-list status lines", DescribeLines); 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); // Last: Release() switches the table off for the rest of the process. r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable); } @@ -362,7 +365,11 @@ 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"); - Check.Eq(sizeof(RynthAiHubApiV1), 8 + 10 * IntPtr.Size, "RynthAiHubApiV1: header + 10 functions"); + // SessionStatsMore was appended (2026-10-13); readers accept any table at least + // BaseStructSize long, so an older RynthAi still connects. + Check.Eq(sizeof(RynthAiHubApiV1), 8 + 11 * IntPtr.Size, "RynthAiHubApiV1: header + 11 functions"); + 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(sizeof(QuestFlagV1), 24, "QuestFlagV1"); Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1"); Check.Eq(RynthIltHubApiV1.InterfaceName, "RynthILT.Hub", "interface name"); @@ -394,6 +401,75 @@ internal static class MoveTests while (DateTime.UtcNow < until) { hub.Tick(); System.Threading.Thread.Sleep(50); } } + /// + /// The charms JSON behind "RynthILT.Data" is valid JSON; on ILT it has a "hands" array (empty + /// with no hand carried) that the shared reader parses, off ILT it has none and still parses. + /// + private static void CharmsReaderJson() + { + var on = NewHub("InfiniteLeaftide", "charms-on"); + string json = on.CharmsTab.BuildReaderJson(); + using (var doc = System.Text.Json.JsonDocument.Parse(json)) + Check.True(doc.RootElement.TryGetProperty("hands", out var hands) && hands.GetArrayLength() == 0, + "on ILT: an empty hands array with no Guardian Hand carried"); + Check.True(json.All(c => c < 128), "ASCII only"); + var view = IltCharmsView.Parse(json); + Check.True(view.Loaded && view.Hands.Count == 0, "the shared reader takes it"); + + var withHands = IltCharmsView.Parse("{\"available\":true,\"charms\":[],\"hands\":[" + + "{\"id\":1234,\"name\":\"Guardian Hand\",\"active\":\"on\",\"server\":\"off\"},{\"id\":0,\"name\":\"no id\"}]}"); + Check.Eq(withHands.Hands.Count, 1, "a hand without an id is skipped (nothing to toggle)"); + Check.True(withHands.Hands[0] == new IltHandRow(1234, "Guardian Hand", "on", "off"), "id, name, active, server"); + + var off = NewHub("Aeshnidae", "charms-off"); + string offJson = off.CharmsTab.BuildReaderJson(); + using (var doc = System.Text.Json.JsonDocument.Parse(offJson)) + Check.False(doc.RootElement.TryGetProperty("hands", out _), "off ILT: no hands"); + Check.True(IltCharmsView.Parse(offJson).Hands.Count == 0, "and the reader shows none"); + } + + /// The Character tab moved out (2026-10-13); every other ILT tab is still RynthILT's. + private static void MovedSections() + { + Check.Eq(IltSections.MovedCommand(IltSection.Character), IltSections.OracleCharacterCommand, "Character -> RynthOracle Character"); + foreach (var kept in new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games }) + { + Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's"); + Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab"); + } + Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games }), + "the tab list is Banking, Gear, Charms, Games"); + Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs"); + Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)"); + Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command"); + } + + /// + /// RynthILT's RynthPluginGetSectionsJson: schema 1 (UI/Sections/SectionManifest.cs in RynthCore), + /// every view an ILT one, each surface one RenderEmbed answers. + /// + private static void SectionsManifest() + { + using var doc = System.Text.Json.JsonDocument.Parse(RynthILTPlugin.SectionsJson); + 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[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)"); + var surfaces = new System.Collections.Generic.List(); + foreach (var c in root.GetProperty("contributions").EnumerateArray()) + { + Check.Eq(c.GetProperty("server").GetString(), "ilt", "an Infinite Leaftide view"); + surfaces.Add(c.GetProperty("surface").GetString() ?? ""); + } + 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(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu") + && !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb"); + } + private static void DormantOffIlt() { var off = NewHub("Aeshnidae", "dormant"); @@ -414,7 +490,13 @@ internal static class MoveTests TickFor(on, 6800); Check.True(on.Options.IsIltLikeWorld, "InfiniteLeaftide is ILT"); Check.True(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count > 0, "on ILT the login probe asks the server"); - Check.True(on.TabShown(IltSection.Character), "and the Character tab shows"); + Check.False(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Any(c => c.Contains("/ilt features", StringComparison.OrdinalIgnoreCase)), + "the server is never asked for a feature list (the ILT profile is Rynth-side)"); + // Character moved out of the Mini Remote (RynthOracle's Character tab, Session Stats); + // Charms and Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. + Check.False(on.TabShown(IltSection.Character), "Character is no Mini Remote tab any more"); + Check.Eq(on.TabShown(IltSection.Gear), on.Available, "Gear shows once the server features are known"); + Check.Eq(on.TabShown(IltSection.Charms), on.Available, "Charms too"); on.OnLogout(); var forced = NewHub("Aeshnidae", "forced"); diff --git a/Tools/RynthILT.Tests/ProfileTests.cs b/Tools/RynthILT.Tests/ProfileTests.cs new file mode 100644 index 0000000..0f23642 --- /dev/null +++ b/Tools/RynthILT.Tests/ProfileTests.cs @@ -0,0 +1,87 @@ +using System; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// RynthILT's "RynthServer.Profile" (ProfileInterface.cs): the same interface and JSON the server +// plugins serve, for "ilt", carrying Infinite Leaftide's tinkering salvage (Hub/IltSalvage.cs). +// The JSON is read back with the shared reader RynthAi's Crafting tab uses (EngineServerState.cs: +// ServerSalvageView.ParseList), so the rows it plans with are the ones checked here. 2026-10-15. +internal static unsafe class ProfileTests +{ + public static void Register(Runner r) + { + 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); + } + + private static void Interface() + { + Check.Eq(ProfileInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not this table"); + Check.Eq(ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthServerProfileApiV1*)ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 1); + Check.True(t != null, "the table"); + Check.Eq(t->Version, RynthServerProfileApiV1.InterfaceVersion, "version"); + Check.Eq(t->StructSize, (uint)sizeof(RynthServerProfileApiV1), "struct size"); + Check.True(t->GetProfileJson != null, "GetProfileJson"); + + string json = ProfileInterface.CurrentJson(true, "InfiniteLeaftide"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("schema").GetInt32(), RynthServerProfile.Schema, "schema"); + Check.Eq(root.GetProperty("id").GetString(), "ilt", "the engine's ILT id"); + Check.Eq(root.GetProperty("name").GetString(), "Infinite Leaftide", "name"); + Check.Eq(root.GetProperty("plugin").GetString(), "RynthILT", "plugin"); + Check.True(root.GetProperty("active").GetBoolean(), "active"); + Check.Eq(root.GetProperty("world").GetString(), "InfiniteLeaftide", "world"); + Check.Eq(root.GetProperty("hosts")[0].GetString(), "infiniteleaftide.online", "hosts from the csproj"); + Check.Eq(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"), json, "unchanged state: the same JSON"); + Check.False(JsonDocument.Parse(ProfileInterface.CurrentJson(false, null)).RootElement.GetProperty("active").GetBoolean(), + "before the Hub is up: not active"); + } + + private static void Salvage() + { + var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); + Check.Eq(rows.Count, IltSalvage.Rows.Length, "every row arrives"); + for (int i = 0; i < rows.Count; i++) + { + var a = IltSalvage.Rows[i]; + var b = rows[i]; + bool same = a.Bench == b.Bench && a.Material == b.Material && a.Kind == b.Kind && a.Effect == b.Effect + && a.UsesTinkSlot == b.UsesTinkSlot && a.NameMatch == b.NameMatch && a.AppliedInt == b.AppliedInt + && a.Prepared == b.Prepared && a.Order == b.Order && a.AfterCap == b.AfterCap + && a.StackGroup == b.StackGroup && a.StackCap == b.StackCap; + Check.True(same, $"row {i} ({a.Bench} {a.Material}) round-trips"); + } + + const int Leather = 52, Steel = 64, Serpentine = 71, Silver = 63, Diamond = 20, BlackGarnet = 15; + foreach (string bench in new[] { "melee", "missile", "caster" }) + { + var leather = rows.Single(r => r.Bench == bench && r.Material == Leather); + Check.True(leather.AfterCap, bench + " Leather: after the cap"); + Check.False(leather.UsesTinkSlot, bench + " Leather: no tink slot"); + Check.Eq(leather.Kind, "once", bench + " Leather: once"); + Check.Eq(leather.Order, 995, bench + " Leather: last"); + } + Check.Eq(rows.Count(r => r.AfterCap), 3, "only the weapon Leathers wait for the cap"); + + var stack = rows.Where(r => r.StackGroup.Length > 0).ToList(); + Check.Eq(string.Join(",", stack.Select(r => r.Bench + ":" + r.Material)), $"jewelry:{Serpentine},jewelry:{Steel}", "Serpentine + Steel stack"); + Check.True(stack.All(r => r.StackGroup == "jewelry-stack" && r.StackCap == 10 && r.Kind == "tink" && !r.UsesTinkSlot), + "one group, cap 10, repeatable, no tink slot"); + + Check.Eq(rows.Single(r => r.Bench == "jewelry" && r.Material == Silver).AppliedInt, 374, "jewelry Silver flag int"); + var diamond = rows.Single(r => r.Bench == "trinkets" && r.Material == Diamond); + Check.True(diamond.Prepared && diamond.AppliedInt == 384 && diamond.Order == 10, "trinket Diamond: prepared, flag 384, first"); + Check.Eq(rows.Count(r => r.Prepared), 4, "the four trinket tiers are prepared"); + Check.True(rows.Where(r => r.Material == BlackGarnet).All(r => r.NameMatch == "Abyssal" && r.UsesTinkSlot), + "Abyssal-Touched Gems by bag name, using a tink slot"); + Check.False(rows.Any(r => r.Bench is "armor" or "items"), "no armor or item rows"); + } +} diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs index 23c2f72..b75b0c0 100644 --- a/Tools/RynthILT.Tests/Program.cs +++ b/Tools/RynthILT.Tests/Program.cs @@ -7,7 +7,8 @@ namespace RynthILT.Tests; // Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the // quiet /bounty list read loop on a fake clock, persistence, the bridge JSON) and the ILT Hub // (attribute raiser, aug costs, bank commands, sigil chain, and the move out of RynthAi: data -// migration, the RynthILT.Hub table, verb routing, the object view). Each test prints PASS / FAIL. +// migration, the RynthILT.Hub table, verb routing, the object view) and its RynthServer.Profile +// (ILT's tinkering salvage). Each test prints PASS / FAIL. // // Run: dotnet run -c Release (all tests) // dotnet run -c Release -- window (tests whose name contains "window") @@ -38,6 +39,16 @@ internal static class Program SigilChainTests.Register(runner); BankCommandTests.Register(runner); MoveTests.Register(runner); + ChunkTests.Register(runner); + ProfileTests.Register(runner); + FeatureCatalogTests.Register(runner); + IltSettingsTests.Register(runner); + FellowshipCommandTests.Register(runner); + AetheriaChunkTests.Register(runner); + RingChainTests.Register(runner); + // Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries. + BreedingTests.Register(runner); + DataApiTests.Register(runner); return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthILT.Tests/RingChainTests.cs b/Tools/RynthILT.Tests/RingChainTests.cs new file mode 100644 index 0000000..25b225f --- /dev/null +++ b/Tools/RynthILT.Tests/RingChainTests.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Rings inscription chain's pure parts (Hub/IltRingChain.cs, SilentKelpie's RynthAi +// Crafting > Rings moved to RynthILT): ingredient names, the craft queue and the scroll pairing. +internal static class RingChainTests +{ + public static void Register(Runner r) + { + r.Add("rings: ingredients match by name, with alternates and an exclude", Ingredients); + r.Add("rings: the queue runs every Step 1, then Step 2, then the glyphs, capped per recipe", Queue); + r.Add("rings: scrolls are known by their glyph and paired with targets the UB-IT way", Scrolls); + r.Add("rings: the recipe list holds the three steps and eight glyphs", RecipeList); + } + + private static IltRingRecipe Recipe(string id) => IltRingChain.Recipes.Single(r => r.Id == id); + + private static void Ingredients() + { + var step1 = Recipe("ring2_step1_quill_trophy"); + Check.True(IltRingChain.Matches("Quill of Infliction", step1.Tool), "the quill"); + Check.True(IltRingChain.Matches("infliction quill", step1.Tool), "an alternate name, any case"); + Check.False(IltRingChain.Matches("Enlightened Quill of Infliction", step1.Tool), "the enlightened quill is Step 2's, not Step 1's"); + Check.True(IltRingChain.Matches("Empyrean Trophy", step1.Target), "a trophy"); + Check.False(IltRingChain.Matches("Trophy Scroll", step1.Target), "plain 'Trophy' isn't enough (scrolls carry the word)"); + Check.False(IltRingChain.Matches(null, step1.Tool), "no name"); + Check.False(IltRingChain.Matches("", step1.Tool), "empty name"); + + var step2 = Recipe("ring2_step2_ink"); + Check.True(IltRingChain.Matches("Enlightened Quill of Infliction", step2.Tool), "Step 2 takes Step 1's quill"); + Check.False(IltRingChain.Matches("Enlightened Infliction Quill of Partition", step2.Tool), "but not the partition quill"); + + var flame = Recipe("ring2_glyph_flame"); + Check.True(IltRingChain.Matches("Enlightened Infliction Quill of Partition", flame.Tool), "Step 3 takes the partition quill"); + Check.True(IltRingChain.Matches("Glyph of Flame", flame.Target), "the full glyph name"); + Check.False(IltRingChain.Matches("Glyph of Frost", flame.Target), "another glyph is not"); + } + + private static void Queue() + { + var runs = new Dictionary + { + ["ring2_glyph_frost"] = 1, + ["ring2_step2_ink"] = 2, + ["ring2_step1_quill_trophy"] = 2, + ["ring2_glyph_bludgeoning"] = 1, + }; + List q = IltRingChain.Expand(id => runs.TryGetValue(id, out int n) ? n : 0); + Check.Eq(string.Join(",", q.Select(r => r.Id)), + "ring2_step1_quill_trophy,ring2_step1_quill_trophy,ring2_step2_ink,ring2_step2_ink,ring2_glyph_bludgeoning,ring2_glyph_frost", + "tier order, then the definition order within a tier"); + Check.Eq(IltRingChain.Expand(_ => 0).Count, 0, "nothing queued"); + Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? -5 : 0).Count, 0, "negative runs count as none"); + Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? 500 : 0).Count, IltRingChain.MaxRuns, "capped at MaxRuns"); + } + + private static void Scrolls() + { + Check.True(IltRingChain.IsInscriptionScroll("Inscription of Halo of Frost"), "an inscription scroll"); + Check.False(IltRingChain.IsInscriptionScroll("Scroll of Frost Bolt"), "a spell scroll is not"); + Check.False(IltRingChain.IsInscriptionScroll(null), "no name"); + Check.Eq(IltRingChain.GlyphOf("Inscription of Halo of Frost")?.Id, "ring2_glyph_frost", "known by its scroll name"); + Check.Eq(IltRingChain.GlyphOf("Inscription of Cassius' Ring of Fire")?.Id, "ring2_glyph_flame", "apostrophes too"); + Check.True(IltRingChain.GlyphOf("Inscription of Something New") == null, "an unknown scroll has no glyph"); + + var scrolls = new[] + { + (Id: 50, Name: "Inscription of Something New"), + (Id: 40, Name: "Inscription of Halo of Frost"), + (Id: 30, Name: "Inscription of Tectonic Rifts"), + (Id: 20, Name: "Inscription of Halo of Frost"), + }; + var pairs = IltRingChain.PairScrolls(scrolls, new[] { 900, 700, 800, 700 }); + // Scrolls by glyph id (bludgeoning < frost; unknown last), then by id; targets by id, once each. + Check.Eq(string.Join(" ", pairs.Select(p => p.Scroll + ">" + p.Target)), "30>700 20>800 40>900", "pairing order"); + Check.Eq(IltRingChain.PairScrolls(scrolls.Take(1), new[] { 1, 2, 3 }).Count, 1, "one scroll per target, no more pairs than scrolls"); + Check.Eq(IltRingChain.PairScrolls(scrolls, Array.Empty()).Count, 0, "no targets, no pairs"); + } + + private static void RecipeList() + { + Check.Eq(IltRingChain.Recipes.Length, 10, "Step 1, Step 2 and eight glyphs"); + Check.Eq(IltRingChain.Recipes.Count(r => r.Tier == 3), 8, "eight glyphs"); + Check.True(IltRingChain.Recipes.Select(r => r.Id).Distinct().Count() == IltRingChain.Recipes.Length, "ids are unique"); + foreach (var r in IltRingChain.Recipes.Where(r => r.Tier == 3)) + Check.True(r.ScrollMarkers.Length > 0, r.Id + " knows its scroll's name"); + } +} diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj index 12399d4..f6c2e02 100644 --- a/Tools/RynthILT.Tests/RynthILT.Tests.csproj +++ b/Tools/RynthILT.Tests/RynthILT.Tests.csproj @@ -39,6 +39,8 @@ + + diff --git a/Tools/RynthInventory.Tests/VaultFeedTests.cs b/Tools/RynthInventory.Tests/VaultFeedTests.cs index 3892f1c..742d5dc 100644 --- a/Tools/RynthInventory.Tests/VaultFeedTests.cs +++ b/Tools/RynthInventory.Tests/VaultFeedTests.cs @@ -59,6 +59,25 @@ namespace RynthInventory.Tests 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(); diff --git a/Tools/RynthLua.CompatTests/Scripts/format.lua b/Tools/RynthLua.CompatTests/Scripts/format.lua new file mode 100644 index 0000000..6d80633 --- /dev/null +++ b/Tools/RynthLua.CompatTests/Scripts/format.lua @@ -0,0 +1,18 @@ +-- string.format as standard Lua 5.2+ has it: %s takes any value through tostring, so a +-- script that formats a missing field (nil) keeps running (MoonSharp alone throws +-- "bad argument #3 to 'format' (string expected, got nil)"). +local e = { SenderName = "Cap" } -- no Message field, as in the DiscordWebhook report +eq(string.format("**%s**: %s", e.SenderName, e.Message), "**Cap**: nil", "nil through %s") +eq(string.format("%s %s %s", true, false, nil), "true false nil", "booleans and nil through %s") +check(string.format("%s", {}):find("^table") ~= nil, "a table through %s") +local obj = setmetatable({}, { __tostring = function() return "custom" end }) +eq(string.format("[%s]", obj), "[custom]", "__tostring is honoured") +eq(("%s=%s"):format("k", nil), "k=nil", "the method form too") + +-- everything else is unchanged +eq(string.format("%d%% of %5.1f", 50, 3.14159), "50% of 3.1", "%d, %%, widths") +eq(string.format("0x%08X %-4s|", 255, "ab"), "0x000000FF ab |", "hex and left-aligned %s") +eq(string.format("%q", "a\"b"), "\"a\\\"b\"", "%q") +eq(string.format("no args"), "no args", "no arguments") +eq(string.format("%s", 12), "12", "numbers through %s") +done() diff --git a/Tools/RynthOracle.Tests/Program.cs b/Tools/RynthOracle.Tests/Program.cs index 722445c..fa07a1d 100644 --- a/Tools/RynthOracle.Tests/Program.cs +++ b/Tools/RynthOracle.Tests/Program.cs @@ -43,10 +43,13 @@ namespace RynthOracle.Tests QuestLines(); Catalog(); Servers(); + EngineServers(); + QuestNotes(); ConquestReplies(); AelrynthReplies(); Void(); Pages(); + CharacterExtras(); Events(); Console.WriteLine($"{_pass} passed, {_fail} failed"); return _fail == 0 ? 0 : 1; @@ -158,6 +161,71 @@ namespace RynthOracle.Tests Check(QuestCatalog.Validate(string.Join("\n", Enumerable.Repeat("x", 3)), out _) == false, "validation rejects junk"); } + /// A RynthCore GetServerStateJson answer (schema 1) with the given servers. + private static string EngineJson(string active, string activeName, string activePlugin, string pick, string world, params string[] servers) + => "{\"schema\":1,\"revision\":3,\"host\":\"h\",\"world\":\"" + world + "\",\"pick\":\"" + pick + "\",\"active\":\"" + active + + "\",\"activeName\":\"" + activeName + "\",\"activePlugin\":\"" + activePlugin + "\",\"servers\":[" + string.Join(",", servers) + "]}"; + + private static string EngineRow(string id, bool active, string force, string plugin = "", string reason = "") + => "{\"id\":\"" + id + "\",\"name\":\"" + id.ToUpperInvariant() + "\",\"active\":" + (active ? "true" : "false") + + ",\"detected\":" + (active && force == "auto" ? "true" : "false") + ",\"force\":\"" + force + + "\",\"builtIn\":false,\"plugin\":\"" + plugin + "\",\"reason\":\"" + reason + "\"}"; + + // RynthCore's server list (API v86) drives the identity: overrides and the Diagnostics pick included. + private static void EngineServers() + { + // The shared parser. + Check(RynthCore.Plugin.Shared.EngineServerState.Parse(null) == null && RynthCore.Plugin.Shared.EngineServerState.Parse("junk") == null, "engine state: junk is null"); + Check(RynthCore.Plugin.Shared.EngineServerState.Parse("{\"schema\":2}") == null, "engine state: another schema is null"); + var st = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("ilt", "Infinite Leaftide", "RynthILT", "auto", "InfiniteLeaftide", + EngineRow("ilt", true, "auto", "RynthILT", "host matches"), EngineRow("aelrynth", false, "auto"))); + Check(st != null && st.HasActive && st.IsActive("ILT") && st.ActivePlugin == "RynthILT" && !st.Picked, "engine state: active ILT, detected"); + Check(st!.Servers.Count == 2 && st.Find("aelrynth") != null && st.Find("x") == null && st.Revision == 3, "engine state: rows"); + + // 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(source.Contains("host matches"), "engine: the reason is shown: " + source); + + var picked = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("conquest", "ConquestAC", "RynthConquest", "conquest", "", + EngineRow("ilt", false, "off"), EngineRow("conquest", true, "on", "RynthConquest")))!; + ServerIdentity.FromEngine(picked, "Leaftide Box", out tag, out world, out source); + Check(tag == ServerTags.Conquest && world == "Leaftide Box", "engine: a pick beats the world name (and the world falls back): " + source); + Check(source.Contains("picked by hand"), "engine: a pick says so: " + source); + + var off = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("", "", "", "mixed", "InfiniteLeaftide", EngineRow("ilt", false, "off")))!; + ServerIdentity.FromEngine(off, "", out tag, out _, out source); + Check(tag == "", "engine: ILT forced off stays off despite the Leaftide world name: " + source); + + var unknown = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("", "", "", "auto", "Levistras", EngineRow("ilt", false, "auto")))!; + ServerIdentity.FromEngine(unknown, "", out tag, out _, out source); + Check(tag == ServerTags.Levistras, "engine: a world the engine has no server for still tags by name: " + source); + + var coldeve = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("coldeve", "Coldeve", "RynthColdeve", "auto", "Coldeve", EngineRow("coldeve", true, "auto", "RynthColdeve")))!; + ServerIdentity.FromEngine(coldeve, "", out tag, out _, out source); + Check(tag == "" && source.Contains("Coldeve"), "engine: a server without Oracle pages has no tag: " + source); + + Check(ServerIdentity.TagForEngineId("AELRYNTH") == ServerTags.Aelrynth && ServerIdentity.TagForEngineId(null) == "", "engine id to tag"); + Check(ServerIdentity.EngineIdForTag(ServerTags.Aelrynth) == "aelrynth" && ServerIdentity.EngineIdForTag("") == "", "tag to engine id"); + + // The owner's profile, read leniently (a server plugin's, and RynthILT's). + var prof = RynthCore.Plugin.Shared.ServerProfileView.Parse( + "{\"schema\":1,\"id\":\"coldeve\",\"name\":\"Coldeve\",\"plugin\":\"RynthColdeve\",\"ruleset\":\"PvE\",\"emulator\":\"ACE\",\"botting\":\"forbidden\",\"bottingNote\":\"no bots\",\"accountLimit\":\"3 accounts\"}"); + Check(prof != null && prof.Botting == "forbidden" && prof.Summary() == "PvE, ACE; botting forbidden - no bots; accounts: 3 accounts", "profile: server plugin: " + prof?.Summary()); + var iltProf = RynthCore.Plugin.Shared.ServerProfileView.Parse("{\"ilt\":true,\"features\":[{\"key\":\"bank\",\"state\":1},{\"key\":\"x\",\"state\":0},{\"key\":\"y\",\"state\":1}]}"); + Check(iltProf != null && iltProf.Ilt && iltProf.FeaturesOn == 2 && iltProf.Summary() == "ILT world, 2 Leaftide features on", "profile: RynthILT: " + iltProf?.Summary()); + Check(RynthCore.Plugin.Shared.ServerProfileView.Parse("") == null && RynthCore.Plugin.Shared.ServerProfileView.Parse("[1]") == null, "profile: junk is null"); + // A user's server-name list (ub-Rythai's ILT Auto list) against the engine's verdict. + string[] list = { "InfiniteLeaftide", "Conquest" }; + Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(null, "Infinite Leaftide", list), "names: no engine, the world name decides (spaces ignored)"); + Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(null, "Coldeve", list), "names: no engine, another world"); + Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(st, "Launcher Profile", list), "names: ILT active matches a Leaftide name whatever the world"); + Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(picked, "", list), "names: a picked Conquest matches by id"); + Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(coldeve, "InfiniteLeaftide", list), "names: Coldeve active beats a Leaftide world name"); + Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(off, "InfiniteLeaftide", list), "names: ILT listed and off stays off"); + Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(unknown, "Conquest", list), "names: a server the engine doesn't list still matches by world"); + } + private static void Servers() { Check(ServerIdentity.TagForWorld("Aeshnidae") == ServerTags.Aelrynth, "Aeshnidae (the live world name) is Aelrynth"); @@ -165,6 +233,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)"); 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"); @@ -188,6 +257,78 @@ namespace RynthOracle.Tests Check(view.Tab == OracleView.TabQuests, "a Conquest tab left selected falls back to Quests elsewhere"); } + // Quest notes: tracking and rewards saved per character, UB's reward format and import, kill-task timers. + private static void QuestNotes() + { + string root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N")); + try + { + var r = new QuestReward { XpPercent = 1.5, LumPercent = 2, RecordedLevel = 275, Coins = 3, Trinkets = 1, Medallions = 2, + YellowPowder = 1, RedPowder = 1, BluePowder = 1, Mmd = 2 }; + Check(r.ShortSummary() == "1.5%XP 2%Lum 3C 1T 2M 1Y 1R 1B 2D L275", "UB's short summary: " + r.ShortSummary()); + Check(QuestReward.Percent(12.345) == "12.3" && QuestReward.Percent(0.1234) == "0.123" && QuestReward.Percent(1.234) == "1.23", "UB's percent format"); + Check(QuestReward.TryParsePercent("2,5%", out double pc) && pc == 2.5, "a percent with a comma and a % sign"); + Check(QuestReward.TryParsePercent("5000", out double big) && big == QuestReward.MaxPercent, "percent clamped to 1000"); + Check(!QuestReward.TryParsePercent("abc", out _) && !QuestReward.TryParseCount("1.5", out _), "junk is refused"); + Check(QuestReward.TryParseCount("-4", out int neg) && neg == 0 && QuestReward.TryParseCount("", out int blank) && blank == 0, "counts: negatives and blanks are 0"); + Check(new QuestReward().IsEmpty && !r.IsEmpty, "empty entry"); + + // Track and record, then read it back as a new session would. + var book = new QuestBook { RootOverride = root, UbRootOverride = "" }; + book.Load("Infinite Leaftide", "Test \"Char\""); + Check(book.Loaded && book.Tracked.Count == 0 && book.RewardCount == 0, "a new character starts empty"); + book.SetTracked("killtaskdrudges", true); + book.SetTracked("30minattributes", true); + book.SetTracked("killtaskdrudges", true); + book.SetReward("30minattributes", r); + Check(book.Tracked.Count == 2 && book.IsTracked("KILLTASKDRUDGES"), "tracked once, case-insensitive"); + string file = book.PathFor("Infinite Leaftide", "Test \"Char\""); + Check(System.IO.File.Exists(file) && System.IO.File.ReadAllText(file).All(ch => ch == '\n' || (ch >= 0x20 && ch <= 0x7E)), "saved at once, plain ASCII"); + + var again = new QuestBook { RootOverride = root, UbRootOverride = "" }; + again.Load("Infinite Leaftide", "Test \"Char\""); + Check(again.Tracked.SequenceEqual(new[] { "killtaskdrudges", "30minattributes" }), "tracked list kept in order"); + Check(again.TryGetReward("30minattributes", out QuestReward back) && back.ShortSummary() == r.ShortSummary(), "rewards read back"); + again.SetReward("30minattributes", new QuestReward()); + again.ToggleTracked("killtaskdrudges"); + Check(again.RewardCount == 0 && again.Tracked.Count == 1, "an empty entry removes the rewards; untrack"); + + // UB ILT's quest_rewards.json is imported once for a character without notes. + string ub = System.IO.Path.Combine(root, "ub"); + System.IO.Directory.CreateDirectory(System.IO.Path.Combine(ub, "InfiniteLeaftide", "Kelp")); + System.IO.File.WriteAllText(System.IO.Path.Combine(ub, "InfiniteLeaftide", "Kelp", "quest_rewards.json"), + "{\"SchemaVersion\":2,\"Character\":\"Kelp\",\"Server\":\"InfiniteLeaftide\",\"Rewards\":{" + + "\"stipendtimer_0812\":{\"XpPercent\":1.25,\"LumPercent\":0,\"RecordedLevel\":300,\"Coins\":5}," + + "\"emptyone\":{\"XpPercent\":0}}}"); + var imported = new QuestBook { RootOverride = root, UbRootOverride = ub }; + imported.Load("Infinite Leaftide", "Kelp"); + Check(imported.RewardCount == 1 && imported.TryGetReward("stipendtimer_0812", out QuestReward ir) && ir.Coins == 5 && ir.RecordedLevel == 300 + && imported.LoadNote.Contains("Imported 1"), "UB rewards imported (empty entries skipped): " + imported.LoadNote); + var noReimport = new QuestBook { RootOverride = root, UbRootOverride = ub }; + noReimport.Load("Infinite Leaftide", "Kelp"); + Check(noReimport.RewardCount == 1 && noReimport.LoadNote.Length == 0, "imported once: the next load reads Oracle's own file"); + + // Kill tasks: kills left, then the reset timer, then done (UB's rule). + DateTime now = new DateTime(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc); + var kt = new QuestFlag { Key = "killtaskdrudges", Solves = 12, MaxSolves = 50, RepeatTime = TimeSpan.FromHours(20), CompletedOnUtc = now.AddHours(-1) }; + Check(QuestTimer.IsKillTask(kt) && QuestTimer.State(kt, true, now, out string t1) == QuestTimerState.InProgress && t1 == "38 left", "kill task counting"); + kt.Solves = 50; + Check(QuestTimer.State(kt, true, now, out string t2) == QuestTimerState.Waiting && t2.StartsWith("19h"), "kill task waiting: " + t2); + kt.CompletedOnUtc = now.AddDays(-2); + Check(QuestTimer.State(kt, true, now, out string t3) == QuestTimerState.Done && t3 == "done", "kill task done"); + var timed = new QuestFlag { Key = "stipendtimer_0812", Solves = 3, RepeatTime = TimeSpan.FromHours(1), CompletedOnUtc = now.AddMinutes(-30) }; + QuestTimerState s4 = QuestTimer.State(timed, true, now, out string t4); + Check(!QuestTimer.IsKillTask(timed) && s4 == QuestTimerState.Waiting && t4 == "30m 0s", "timer: " + t4); + timed.CompletedOnUtc = now.AddHours(-2); + Check(QuestTimer.State(timed, true, now, out string t5) == QuestTimerState.Ready && t5 == "ready", "timer ran out"); + Check(QuestTimer.State(timed, false, now, out string t6) == QuestTimerState.Done && t6 == "completed", "one-time quest"); + } + finally + { + try { System.IO.Directory.Delete(root, true); } catch (System.IO.IOException) { } + } + } + private static void ConquestReplies() { var d = new ConquestData(); @@ -319,6 +460,13 @@ namespace RynthOracle.Tests ch.Enchantments.Add(new ActiveEnchantment(3531, "Bobo's Quickening", 600, 1800, false)); ch.Enchantments.Add(new ActiveEnchantment(SpellIds.SurgeOfDestruction, "Surge of Destruction", 5, 8, false)); c.Void.OnChatLine("You cast Corrosion VII on Drudge Slinker", c.NowMs, _ => 0, () => true); + // The quest book in a temp folder (never the player's %APPDATA%), with two tracked quests. + c.Book.RootOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N")); + c.Book.UbRootOverride = ""; + c.Book.Load("Aeshnidae", ch.Name); + c.Book.SetTracked("30minattributes", true); + c.Book.SetTracked("societyribbonsperdaycounter", true); + c.Book.SetReward("30minattributes", new QuestReward { XpPercent = 1.5, RecordedLevel = 126, Coins = 2 }); return c; } @@ -331,6 +479,11 @@ namespace RynthOracle.Tests UiWindow voidW = host.Add(new UiWindow("RynthOracle/Void", "Void") { Visible = true }); var vv = new VoidView(c); voidW.Begin(); vv.Draw(voidW); voidW.End(); + UiWindow timersW = host.Add(new UiWindow("RynthOracle/QuestTimers", "Quest Timers") { Visible = true }); + var tv = new QuestTimersView(c); + timersW.Begin(); tv.Draw(timersW); timersW.End(); + string timersBody = Encoding.UTF8.GetString(timersW.Body); + 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); @@ -354,6 +507,24 @@ namespace RynthOracle.Tests main.MarkSubmitted(true); } } + // The Quests tab with a quest opened (rewards editor) and the Tracked filter on. + c.Server.Force("", "Coldeve"); + c.Settings.TabName = OracleView.TabQuests; + main.Begin(); view.Draw(main); main.End(); + Apply(host, Event(2, 89, main.Hash, main.KeyOf("q.tracked"), new byte[] { 1 })); + main.Begin(); view.Draw(main); main.End(); + Check(Encoding.UTF8.GetString(main.Body).Contains("2 shown"), "the Tracked filter lists the two tracked quests"); + Apply(host, Event(1, 90, main.Hash, main.KeyOf("q.r.30minattributes"), new byte[] { 1, 0, 0 })); + main.Begin(); view.Draw(main); main.End(); + ParseAll(host, "quests with a quest opened", out int openOps); + string openBody = Encoding.UTF8.GetString(main.Body); + Check(openOps > 5 && openOps < 1400, $"quests page with a quest opened: {openOps} ops"); + Check(openBody.Contains("Save rewards") && openBody.Contains("Level: 126"), "the opened quest shows the rewards editor"); + Check(openBody.Contains("1.5%XP 2C L126"), "the Rewards column shows the recorded rewards"); + Check(!openBody.Contains("/qb"), "no quest bonus list here (Infinite Leaftide's /qb is RynthILT's)"); + 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; @@ -394,6 +565,41 @@ namespace RynthOracle.Tests maxOps = windows.Where(w => w.List != null).Select(w => w.List!.OpCount).DefaultIfEmpty(0).Max(); } + /// + /// The Character tab's RynthAi session (the generic part of the Mini Remote's old Character + /// tab, moved here 2026-10-13). Infinite Leaftide's charms are RynthILT's and never drawn here. + /// + private static void CharacterExtras() + { + OracleContext c = Context(); + c.Server.Force("", "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 }); + + // Nothing from RynthAi yet: the tab says what to load. + main.Begin(); view.Draw(main); main.End(); + string empty = Encoding.UTF8.GetString(main.Body); + Check(empty.Contains("Load RynthAi for the session rates"), "without RynthAi: says to load it"); + Check(!empty.Contains("Charms") && !empty.Contains("RynthILT"), "no charms section on any world (RynthILT's Charms tab)"); + main.MarkSubmitted(true); + + c.Session = new RynthCore.Plugin.Shared.SessionStatsV1 + { + StartUtcTicks = DateTime.UtcNow.AddHours(-1).Ticks, SessionSeconds = 3600, Xp = 1_234_567, XpPerHour = 1_234_567, + Lum = 4000, LumPerHour = 4000, LumLast5Min = 250, Kills = 42, KillsPerHour = 42, + }; + c.SessionKnown = true; + main.Begin(); view.Draw(main); main.End(); + ParseAll(host, "Character with the session", out int ops); + string body = Encoding.UTF8.GetString(main.Body); + Check(ops > 5 && ops < 1400, $"Character with the session: {ops} ops"); + Check(body.Contains("1,234,567") && body.Contains("4,000") && body.Contains("42 (42/h)"), "the session shows RynthAi's XP, luminance and kills"); + Check(OracleView.SessionStatsCommand == "/rc miniremote section char", "Session Stats opens the section, not the moved tab"); + main.MarkSubmitted(true); + } + private static void Events() { OracleContext c = Context(); diff --git a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj index 59d54f9..9bd8011 100644 --- a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj +++ b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj @@ -28,6 +28,12 @@ + + + + + + diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs new file mode 100644 index 0000000..603fa97 --- /dev/null +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -0,0 +1,18 @@ +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// Offline tests for the server plugins: the shared model and every server plugin's detection data. +// +// Run: dotnet run -c Release (all tests) +// dotnet run -c Release -- host (tests whose name contains "host") +internal static class Program +{ + private static int Main(string[] args) + { + var runner = new Runner(); + ServerPackModelTests.Register(runner); + ServerProjectsTests.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 new file mode 100644 index 0000000..6184827 --- /dev/null +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -0,0 +1,37 @@ + + + + + Exe + net10.0 + enable + true + RynthServerPack.Tests + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs new file mode 100644 index 0000000..f77ac4c --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs @@ -0,0 +1,243 @@ +using System; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The shared server-plugin model (Plugins\Shared\ServerPack\ServerPackModel.cs): RynthCore's +// "servermenu" verdict for the plugin's own server, the world-name fallback before one arrives, +// the override commands the card sends, and the sections manifest RynthCore reads. +internal static class ServerPackModelTests +{ + public static void Register(Runner r) + { + r.Add("server pack: RynthCore's push gives this server's verdict, override and reason", EnginePush); + r.Add("server pack: a push without this server, or not a push, changes nothing", ForeignPush); + r.Add("server pack: before any push the world name decides", WorldFallback); + r.Add("server pack: override commands are checked before sending", ForceCommands); + r.Add("server pack: the sections manifest declares the server and a server-only card", SectionsJson); + r.Add("server pack: logout clears the verdict", ClearOnLogout); + r.Add("server pack: the card's botting line and address", InfoText); + r.Add("server pack: the RynthServer.Profile JSON carries the server's settings", ProfileJson); + r.Add("server pack: the profile JSON is plain ASCII and escaped", ProfileJsonAscii); + } + + private static void ProfileJson() + { + ServerPackInfo info = new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) + { + Port = 9050, Ruleset = "PvP", Status = "Stable", Botting = BottingPolicy.Restricted, BottingNote = "attended only", + AccountLimit = "3 accounts", Facts = new[] { "fact one" }, Commands = new[] { new ServerCommand("/x", "does x") }, + Discord = "https://discord.gg/x", + }; + string json = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", true, "Coldeve"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackProfile.Schema, "schema"); + Check.Eq(root.GetProperty("id").GetString(), "coldeve", "id (lower-cased)"); + Check.Eq(root.GetProperty("plugin").GetString(), "RynthColdeve", "plugin"); + Check.Eq(root.GetProperty("version").GetString(), "0.1.2", "version"); + Check.True(root.GetProperty("active").GetBoolean(), "active"); + Check.Eq(root.GetProperty("world").GetString(), "Coldeve", "world"); + Check.Eq(root.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); + Check.Eq(root.GetProperty("port").GetInt32(), 9050, "port"); + Check.Eq(root.GetProperty("ruleset").GetString(), "PvP", "ruleset"); + Check.Eq(root.GetProperty("botting").GetString(), "restricted", "botting"); + Check.Eq(root.GetProperty("bottingNote").GetString(), "attended only", "botting note"); + Check.Eq(root.GetProperty("facts")[0].GetString(), "fact one", "facts"); + Check.Eq(root.GetProperty("commands")[0].GetProperty("what").GetString(), "does x", "commands"); + Check.Eq(root.GetProperty("discord").GetString(), "https://discord.gg/x", "links"); + + // What a reader (RynthOracle, RynthAi's /ra server) makes of it. + var view = RynthCore.Plugin.Shared.ServerProfileView.Parse(json); + Check.True(view != null, "the shared reader parses it"); + Check.Eq(view!.Summary(), "PvP, ACE; botting restricted - attended only; accounts: 3 accounts", "the reader's summary"); + + // No salvage defined: an empty list, which the Crafting tab reads as "none defined". + Check.Eq(root.GetProperty("salvage").GetArrayLength(), 0, "no salvage: empty list"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList(json).Count, 0, "the reader sees none"); + + // Salvage defined: each row round-trips through the shared reader. + ServerPackInfo withSalvage = new("x", "X", new[] { "x.example" }, new[] { "X" }) + { + Salvage = new[] + { + new ServerSalvage("melee", 52, "+1 tink past the cap", "once", UsesTinkSlot: false), + new ServerSalvage("Armor", 64, "+30 armor level"), + new ServerSalvage("", 64, "no bench: skipped"), + }, + }; + var salvage = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X")); + Check.Eq(salvage.Count, 2, "rows without a bench are skipped"); + Check.Eq(salvage[0].Bench, "melee", "bench"); + Check.Eq(salvage[0].Material, 52, "material id"); + Check.Eq(salvage[0].Kind, "once", "kind"); + Check.False(salvage[0].UsesTinkSlot, "no tink slot"); + Check.Eq(salvage[1].Bench, "armor", "bench lower-cased"); + Check.Eq(salvage[1].Kind, "tink", "default kind"); + Check.True(salvage[1].UsesTinkSlot, "slot by default"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList("{\"id\":\"x\"}").Count, 0, "a profile without the list (older plugins)"); + + // The optional row fields: absent = off / the default, and the writer leaves them out then. + Check.True(salvage.All(v => v.AppliedInt == 0 && !v.Prepared && v.Order == 0 && !v.AfterCap + && v.StackGroup.Length == 0 && v.StackCap == 0), "optional fields default when absent"); + string plain = ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X"); + Check.True(!plain.Contains("\"applied\"") && !plain.Contains("\"prepared\"") && !plain.Contains("\"order\"") + && !plain.Contains("\"afterCap\"") && !plain.Contains("\"stackGroup\""), "unset fields are not written"); + + ServerPackInfo withRules = new("x", "X", new[] { "x.example" }, new[] { "X" }) + { + Salvage = new[] + { + new ServerSalvage("melee", 52, "post-cap", "once", UsesTinkSlot: false, Order: 995, AfterCap: true), + new ServerSalvage("jewelry", 71, "stack", UsesTinkSlot: false, Order: 50, StackGroup: "jewelry-stack", StackCap: 10), + new ServerSalvage("trinkets", 20, "tier", "once", UsesTinkSlot: false, AppliedInt: 384, Prepared: true, Order: 10), + }, + }; + var rules = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + ServerPackProfile.BuildJson(withRules, "RynthX", "1", true, "X")); + Check.Eq(rules.Count, 3, "rows with rules"); + Check.True(rules[0].AfterCap && rules[0].Order == 995 && !rules[0].Prepared && rules[0].StackGroup.Length == 0, "after cap + order"); + Check.Eq(rules[1].StackGroup, "jewelry-stack", "stack group"); + Check.Eq(rules[1].StackCap, 10, "stack cap"); + Check.True(rules[2].Prepared && rules[2].AppliedInt == 384 && rules[2].Order == 10 && !rules[2].AfterCap, "prepared + applied + order"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + "{\"salvage\":[{\"bench\":\"jewelry\",\"material\":64,\"stackGroup\":\"g\"},{\"bench\":\"jewelry\",\"material\":71,\"stackGroup\":\"g\",\"stackCap\":0}]}") + .Count(v => v.StackGroup.Length > 0), 0, "a stack group without a positive cap is no group"); + var odd = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + "{\"salvage\":[{\"bench\":\"melee\",\"material\":52,\"applied\":\"x\",\"prepared\":1,\"order\":null,\"afterCap\":\"yes\"}]}"); + Check.True(odd.Count == 1 && odd[0].AppliedInt == 0 && !odd[0].Prepared && odd[0].Order == 0 && !odd[0].AfterCap, + "fields of the wrong type read as absent"); + + string idle = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", false, null); + using JsonDocument idleDoc = JsonDocument.Parse(idle); + Check.False(idleDoc.RootElement.GetProperty("active").GetBoolean(), "not active"); + Check.Eq(idleDoc.RootElement.GetProperty("world").GetString(), "", "no world before login"); + Check.Eq(ServerPackProfile.BottingName(BottingPolicy.Unknown), "unknown", "unknown botting"); + } + + private static void ProfileJsonAscii() + { + ServerPackInfo info = new("x", "Caf\u00e9 \"Q\"\n", Array.Empty(), Array.Empty()) { Summary = "a\\b\tc \u2014 d" }; + string json = ServerPackProfile.BuildJson(info, "RynthX", "1", false, ""); + bool ascii = true; + foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; + Check.True(ascii, "only printable ASCII: " + json); + using JsonDocument doc = JsonDocument.Parse(json); + Check.Eq(doc.RootElement.GetProperty("name").GetString(), "Caf\u00e9 \"Q\"", "name round-trips (trimmed)"); + Check.Eq(doc.RootElement.GetProperty("summary").GetString(), "a\\b\tc \u2014 d", "summary round-trips"); + } + + private static ServerPackInfo Coldeve() => + new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) { Discord = "https://discord.gg/x" }; + + private const string Push = + "V\tcoldeve\tColdeve\t1\ton\t0\tforced on for this character\n" + + "V\tilt\tInfinite Leaftide\t0\tauto\t0\tnot Infinite Leaftide\n" + + "X\tchar\tChar\n" + + "S\tcoldeve\tColdeve\t1\t/rc server coldeve on\n" + + "I\tColdeve server (RynthColdeve)\t/rc miniremote section char\tWhat is known.\tsection:char\n"; + + private static void EnginePush() + { + var model = new ServerPackModel(Coldeve()); + Check.True(model.ApplyEngine(Push, 1234), "taken"); + ServerVerdictView? v = model.Engine; + Check.True(v != null, "this server's verdict"); + Check.True(v!.Active, "active"); + Check.Eq(v.Force, "on", "override"); + Check.False(v.Detected, "forced, not detected"); + Check.Eq(v.Reason, "forced on for this character", "reason"); + Check.Eq(model.EngineAtMs, 1234L, "when"); + Check.True(model.IsActive("SomewhereElse"), "RynthCore's verdict beats the world name"); + } + + private static void ForeignPush() + { + var model = new ServerPackModel(Coldeve()); + Check.False(model.ApplyEngine("X\tchar\tChar\n", 1), "no server lines: not a push"); + Check.False(model.ApplyEngine(null, 1), "null"); + Check.False(model.ApplyEngine(new string('V', ServerPackModel.MaxPayload + 1), 1), "too long"); + Check.True(model.Engine == null, "nothing published"); + + // A push that lists other servers but not this one yet (RynthCore hasn't read the manifest). + Check.True(model.ApplyEngine("V\tilt\tInfinite Leaftide\t1\tauto\t1\thost matches\n", 2), "a push"); + Check.True(model.Engine == null, "no verdict for this server"); + ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out bool listed); + Check.True(listed, "listed"); + Check.Eq(ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out _)!.Force, "auto", + "id case ignored; an unknown override reads as auto; no reason field is fine"); + } + + private static void WorldFallback() + { + var model = new ServerPackModel(Coldeve()); + Check.True(model.IsActive("Coldeve"), "exact world name"); + Check.True(model.IsActive(" coldeve "), "case and spaces"); + Check.False(model.IsActive("ColdeveTwo"), "no partial match without '*'"); + Check.False(model.IsActive(null), "unknown world"); + Check.True(ServerPackModel.WorldMatches("Aeshnidae Live", new[] { "Aelrynth*", "Aeshnidae*" }), "wildcard"); + Check.False(ServerPackModel.WorldMatches("LeafDawn", new[] { "Leafdawning" }), "LeafDawn is not Leafdawning"); + Check.True(ServerPackModel.WorldMatches("Infinite Leaftide", new[] { "*Leaftide*" }), "both ends"); + } + + private static void ForceCommands() + { + Check.Eq(ServerPackModel.ForceCommand("coldeve", "On"), "/rc server coldeve on", "on"); + Check.Eq(ServerPackModel.ForceCommand("coldeve", "auto"), "/rc server coldeve auto", "auto"); + Check.Eq(ServerPackModel.ForceCommand("coldeve", "maybe"), "", "unknown mode"); + Check.Eq(ServerPackModel.ForceCommand("cold eve", "on"), "", "an id with a space"); + Check.Eq(ServerPackModel.ForceCommand("coldeve; /quit", "on"), "", "no command injection through the id"); + Check.False(ServerPackModel.IsSafeId(new string('a', 33)), "too long"); + } + + private static void SectionsJson() + { + string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); + JsonElement server = root.GetProperty("servers")[0]; + Check.Eq(server.GetProperty("id").GetString(), "coldeve", "server id lower-cased"); + Check.Eq(server.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); + Check.Eq(server.GetProperty("worldNames")[0].GetString(), "Coldeve", "world names"); + JsonElement card = root.GetProperty("contributions")[0]; + Check.Eq(card.GetProperty("section").GetString(), "server", "in the Server section (not Session Stats)"); + JsonElement section = root.GetProperty("sections")[0]; + Check.Eq(section.GetProperty("id").GetString(), "server", "the Server section is declared"); + Check.Eq(section.GetProperty("label").GetString(), "Server", "its label"); + Check.Eq(section.GetProperty("order").GetInt32(), 50, "after Session Stats, before Map"); + Check.Eq(card.GetProperty("server").GetString(), "coldeve", "only while Coldeve is active"); + Check.Eq(card.GetProperty("surface").GetString(), "section:server-coldeve", "the card's surface"); + + var quoted = new ServerPackInfo("odd", "Odd \"Name\"\n", new[] { "a\\b" }, Array.Empty()); + using JsonDocument odd = JsonDocument.Parse(ServerPackModel.BuildSectionsJson(quoted, "RynthOdd")); + Check.Eq(odd.RootElement.GetProperty("servers")[0].GetProperty("hosts")[0].GetString(), "a\\b", "escaped"); + } + + private static void ClearOnLogout() + { + var model = new ServerPackModel(Coldeve()); + model.ApplyEngine(Push, 5); + model.Clear(); + Check.True(model.Engine == null, "verdict cleared"); + Check.Eq(model.EngineAtMs, 0L, "time cleared"); + Check.False(model.IsActive("Elsewhere"), "back to the world name"); + } + + private static void InfoText() + { + ServerPackInfo c = Coldeve(); + Check.Eq(c.Address, "play.coldeve.ac:9000", "address"); + Check.True(c.BottingText.StartsWith("Not published"), "unknown policy says so"); + Check.True(c.BottingText.Contains("Discord"), "and points at the Discord"); + var lev = new ServerPackInfo("example", "Example", new[] { "play.example.test" }, new[] { "Example" }) + { Botting = BottingPolicy.Forbidden, BottingNote = "no automation" }; + Check.Eq(lev.BottingText, "Forbidden - no automation", "forbidden"); + Check.Eq(new ServerPackInfo("x", "", Array.Empty(), Array.Empty()).Address, "", "no host, no address"); + Check.True(ServerPackModel.LauncherSteps(c)[0].Contains("play.coldeve.ac:9000"), "setup names the address"); + } +} diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs new file mode 100644 index 0000000..66c8434 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using RynthCore.PluginSdk.Manifest; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// Every server plugin's csproj (Plugins\RynthCore.Plugin.Rynth*\ with RynthPluginServerId), read as +// XML: the detection data RynthCore's loader and sections use must be unique and must not overlap, +// or a client would load (or show) the wrong server's plugin. +internal static class ServerProjectsTests +{ + public static void Register(Runner r) + { + r.Add("server projects: every listed server has a plugin", AllServersPresent); + 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); + } + + private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared); + + /// The servers in the request (the server list's busiest, plus Aelrynth) and their plugins. + private static readonly string[] Expected = + { + "coldeve", "ilt", "frostace", "reefcull", "conquest", "dreamweave", "portalstorm", "sundering", + "achard", "leafdawn", "derptide", "frostcull", "thistlecrown", "eversong", "leafdawning", "aelrynth", + }; + + private static string PluginsDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins"); + } + + private static List Load() + { + var list = new List(); + foreach (string dir in Directory.GetDirectories(PluginsDir(), "RynthCore.Plugin.Rynth*")) + { + string csproj = Path.Combine(dir, Path.GetFileName(dir) + ".csproj"); + if (!File.Exists(csproj)) continue; + XDocument doc = XDocument.Load(csproj); + string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? ""; + string id = Prop("RynthPluginServerId"); + if (id.Length == 0) continue; + string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + bool shared = doc.Descendants("Import").Any(i => (i.Attribute("Project")?.Value ?? "").EndsWith("ServerPlugin.props")); + string asm = Prop("AssemblyName"); + list.Add(new Project(dir, asm.Replace("RynthCore.Plugin.", ""), id, Prop("RynthPluginServerName"), + Split(Prop("RynthPluginServerHosts")), Split(Prop("RynthPluginServerWorldNames")), shared)); + } + return list; + } + + private static void AllServersPresent() + { + List projects = Load(); + foreach (string id in Expected) + Check.True(projects.Any(p => p.Id == id), "a server plugin for " + id); + Check.Eq(projects.Count, Expected.Length, "no unexpected server plugins"); + } + + private static void Unique() + { + List projects = Load(); + Check.Eq(projects.Select(p => p.Id).Distinct().Count(), projects.Count, "ids unique"); + Check.Eq(projects.Select(p => p.PluginName.ToLowerInvariant()).Distinct().Count(), projects.Count, "plugin names unique"); + var hosts = projects.SelectMany(p => p.Hosts).Select(h => h.ToLowerInvariant()).ToList(); + Check.Eq(hosts.Distinct().Count(), hosts.Count, "hosts unique"); + foreach (Project p in projects) + { + Check.True(p.Hosts.Length > 0, p.PluginName + " lists a host (the loader picks plugins by host)"); + Check.True(p.Worlds.Length > 0, p.PluginName + " lists a world name"); + Check.True(p.Name.Length > 0, p.PluginName + " has a display name"); + } + } + + private static void NoHostOverlap() + { + List projects = Load(); + foreach (Project owner in projects) + foreach (string host in owner.Hosts.Where(h => !h.Contains('*'))) + foreach (Project other in projects.Where(o => o != owner)) + { + var server = new RynthPluginServer { Id = other.Id, Hosts = other.Hosts.ToList() }; + Check.False(server.MatchesHost(host, out string hit), + $"{owner.PluginName}'s host {host} is not claimed by {other.PluginName} ({hit})"); + } + } + + private static void Layout() + { + foreach (Project p in Load().Where(p => p.Id != "ilt")) + { + Check.True(p.Shared, p.PluginName + " imports Shared\\ServerPack\\ServerPlugin.props"); + Check.True(File.Exists(Path.Combine(p.Dir, "ServerData.cs")), p.PluginName + " has ServerData.cs"); + } + } + +}