From d54613aa63078fcff270b2a564790b107245be1d Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sat, 31 Oct 2026 19:00:25 -0400 Subject: [PATCH] Snapshot for release 2026.10.31.2 (internal 4a0710c) --- .../Combat/CombatManager.PassedOver.cs | 144 ++ .../Combat/CombatManager.cs | 50 +- .../CorpseOpenController.cs | 299 ++- .../GroundLootController.cs | 18 +- .../ItemInfo/LootChatLine.cs | 86 + .../ItemInfo/MagItemDescriber.cs | 6 + .../ItemInfo/MagItemInfoSettings.cs | 17 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 1 + .../LegacyUi/LegacyItemInfoUi.cs | 31 + .../RynthCore.Plugin.RynthAi/Loot/LootWhy.cs | 74 + .../Loot/VTankLootEvaluator.cs | 420 +++- .../Meta/ExpressionEngine.cs | 5 + .../RynthAiCommands.cs | 73 + .../RynthAiItemInfo.cs | 43 +- .../RynthAiPlugin.ChestLoot.cs | 10 +- .../RynthAiPlugin.VTankHotkeys.cs | 5 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 37 +- .../Model/Quantity.cs | 121 +- .../Quantity/QtyWorld.cs | 39 +- .../Quantity/QuantityController.cs | 20 +- .../RynthCore.Plugin.RynthDefective.csproj | 5 + .../RynthDefectivePlugin.cs | 2 + .../ShortcutBar/SelectionWindow.Quantity.cs | 11 +- .../Characters/CharactersLook.cs | 171 ++ .../Characters/CharactersManifest.cs | 26 +- .../Characters/CharactersWindow.cs | 290 ++- .../PluginExports.cs | 10 +- .../RynthNetPlugin.Characters.cs | 56 +- .../RynthNetPlugin.Commands.cs | 4 + .../RynthNetPlugin.cs | 2 + .../RynthNetSettings.cs | 19 +- Plugins/Shared/RynthServerProfileApi.cs | 24 +- .../Fixtures/lootsnob-excerpt.utl | 1815 +++++++++++++++++ Tools/RynthCore.RynthAiHostTests/Program.cs | 6 + .../Tests/CommandReplyTests.cs | 1 + .../Tests/LootChatLineTests.cs | 300 +++ .../Tests/LootClaimMismatchTests.cs | 291 +++ .../Tests/LootLateIdTests.cs | 180 ++ .../Tests/LootNothingLineTests.cs | 249 +++ .../Tests/LootRuleMatchTests.cs | 271 +++ .../Tests/LootSurveyTests.cs | 245 +++ .../Tests/ProfileLoadTests.cs | 10 + .../Tests/TargetingTests.cs | 129 ++ .../Tests/VTankLootTests.cs | 33 +- Tools/RynthDefective.Tests/Program.cs | 2 + Tools/RynthDefective.Tests/QuantityTests.cs | 172 ++ .../RynthDefective.Tests.csproj | 4 + Tools/RynthNet.Tests/LookTests.cs | 166 ++ Tools/RynthNet.Tests/Program.cs | 1 + Tools/RynthNet.Tests/RynthNet.Tests.csproj | 9 +- 50 files changed, 5824 insertions(+), 179 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersLook.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootLateIdTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootNothingLineTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootSurveyTests.cs create mode 100644 Tools/RynthNet.Tests/LookTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs new file mode 100644 index 0000000..fe62ab5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs @@ -0,0 +1,144 @@ +// ============================================================================ +// RynthSuite - Combat/CombatManager.PassedOver.cs +// Why a higher-priority monster was not the target (R-20261031-201214-8be7). +// +// Target selection only ever sees the scan's candidates: monsters inside +// Monster Range that are attackable, alive, not blacklisted and in line of +// sight. A Priority 5 monster standing behind a tree, or a few metres past +// Monster Range, is not a candidate, so a Priority 1 monster beside it is +// fought; from the chair that looks like the priority being ignored. The +// report could not tell which: the [ScanTele] counts said two monsters in +// range were LOS-blocked, not which ones or their priority. +// +// Now the lock/switch line names the best monster it passed over and why +// ("[passed over 0x.. 'X' priority 5, 3.1 m: line of sight blocked]"), and +// while the target is fought, a higher-priority monster in range that is not +// a candidate is logged once per reason. Log only: selection is unchanged. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +public partial class CombatManager +{ + /// A monster inside Monster Range the last scan left out, and why. + private struct PassedOverMonster + { + public int Id; + public double Distance; + public string Why; + } + + // Refilled by every scan (ScanNearbyTargets): in-range monsters it left out for a reason + // that can hide a monster worth fighting. Not the dead (just killed, health 0) or the + // Priority 0 ones (ignored by the rule, so never above anything). + private readonly List _passedOver = new(); + + // Per lock: the monsters already logged as passed over, with the reason logged, so a + // monster held behind a wall is one line, not one per tick. Emptied by every lock. + private readonly Dictionary _passedOverLogged = new(); + + /// How far past Monster Range the lock line still looks for a higher priority. + internal const double PassedOverBeyondRangeM = 15.0; + + internal const string PassedOverLos = "line of sight blocked"; + internal const string PassedOverBlacklisted = "blacklisted"; + internal const string PassedOverNeverAttack = "on the never-attack list"; + internal const string PassedOverGhost = "a ghost (the server doesn't have it)"; + internal const string PassedOverEnvironment = "left for hitting the environment"; + internal const string PassedOverNotAttackable = "not attackable"; + + /// Tests: the LOS verdict per monster instead of the ray test (true = blocked). + internal Func? LosBlockedOverride { get; set; } + + private void NotePassedOver(int id, double distance, string why) + => _passedOver.Add(new PassedOverMonster { Id = id, Distance = distance, Why = why }); + + /// + /// The best monster of a higher Priority than that was not a + /// candidate, as "0x.. 'name' priority P, D m: why", or null when there is none. In range + /// and left out by the scan first (the highest priority, then the closest); else the + /// closest higher priority up to past Monster Range. + /// The second half walks the landscape, so it is for the lock line only (a lock is rare). + /// + internal string? DescribePassedOver(int priority, int pickedId, bool lookBeyondRange) + { + if (TryBestPassedOver(priority, pickedId, out var po, out int poPriority)) + return $"0x{po.Id:X8} '{_worldFilter[po.Id]?.Name}' priority {poPriority}, {po.Distance:0.0} m: {po.Why}"; + if (!lookBeyondRange) return null; + + int playerId = (int)_playerId; + if (playerId == 0) return null; + double range = Math.Max(1.0, _settings.MonsterRange); + int bestId = 0, bestP = 0; + double bestDist = double.MaxValue; + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.Id == playerId || wo.Id == pickedId) continue; + if ((int)wo.ObjectClass != (int)AcObjectClass.Monster || IsSpellProjectileName(wo.Name)) continue; + double d = _worldFilter.Distance(playerId, wo.Id); + if (d <= range || d > range + PassedOverBeyondRangeM || d >= bestDist) continue; + if (_worldFilter.GetHealthRatio(wo.Id) == 0f || _recentlyKilled.ContainsKey(wo.Id)) continue; + int p = PriorityOf(wo.Id); + if (p <= priority) continue; + bestId = wo.Id; bestP = p; bestDist = d; + } + return bestId == 0 ? null + : $"0x{bestId:X8} '{_worldFilter[bestId]?.Name}' priority {bestP}, {bestDist:0.0} m: beyond Monster Range ({range:0.#} m)"; + } + + private bool TryBestPassedOver(int priority, int skipId, out PassedOverMonster best, out int bestPriority) + { + best = default; + bestPriority = int.MinValue; + for (int i = 0; i < _passedOver.Count; i++) + { + var po = _passedOver[i]; + if (po.Id == skipId) continue; + int p = PriorityOf(po.Id); + if (p <= priority) continue; + if (p > bestPriority || (p == bestPriority && po.Distance < best.Distance)) + { + best = po; + bestPriority = p; + } + } + return bestPriority != int.MinValue; + } + + /// + /// While a target is fought: a monster in range of a higher Priority than the target that + /// the scan left out is logged, once per monster and reason for this lock. Selection + /// already switches to such a monster the moment it is a candidate; this says why it isn't. + /// + internal void NotePassedOverWhileEngaged() + { + if (_lockedTargetId == 0 || _passedOver.Count == 0) return; + for (int i = 0; i < _passedOver.Count; i++) + { + var po = _passedOver[i]; + if (po.Id == _lockedTargetId) continue; + int p = PriorityOf(po.Id); + if (p <= _lockedPriority) continue; + if (_passedOverLogged.TryGetValue(po.Id, out string? was) && was == po.Why) continue; + if (_passedOverLogged.Count >= 64) _passedOverLogged.Clear(); + _passedOverLogged[po.Id] = po.Why; + _host.Log($"[CombatTarget] passed over 0x{po.Id:X8} '{_worldFilter[po.Id]?.Name}' priority {p}, {po.Distance:0.0} m: {po.Why}; " + + $"the target stays 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority}"); + } + } + + /// A new lock: the lock line names what it passed over; the per-lock log starts over. + private string PassedOverNoteForLock(int bestId, int bestPriority) + { + _passedOverLogged.Clear(); + string? po = DescribePassedOver(bestPriority, bestId, lookBeyondRange: true); + if (po == null) return ""; + // The monster named here isn't logged again by NotePassedOverWhileEngaged for the same reason. + if (TryBestPassedOver(bestPriority, bestId, out var inRange, out _)) + _passedOverLogged[inRange.Id] = inRange.Why; + return $" [passed over {po}]"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index ed2b8ec..12506a7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1050,6 +1050,7 @@ public partial class CombatManager : IDisposable PrunePredictedDeaths(); // before the loop: a predicted kill still alive is scanned again this tick _scannedTargets.Clear(); + _passedOver.Clear(); _nearbyNoLos = 0; int scanTotal = 0, scanRing = 0; // D2 telemetry, published after the loop int playerId = (int)_playerId; @@ -1133,25 +1134,49 @@ public partial class CombatManager : IDisposable // Priority 0 don't keep it out (attackable, alive and LOS still do). bool isForced = wo.Id != 0 && wo.Id == ForcedTargetId; if (dist > (isEngaged || isForced ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue; + // Left out below for a reason that can hide a monster worth fighting: noted for the + // lock line's "passed over" (CombatManager.PassedOver.cs). In range, not the target. + bool notePassed = !isEngaged && dist <= maxDist; // User-configured "never attack" list — excluded from acquisition // entirely (an already-engaged match drops out of _scannedTargets // here and is released by the scan-grace timer in Think). - if (!isForced && IsUserBlacklistedName(wo.Name)) continue; + if (!isForced && IsUserBlacklistedName(wo.Name)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverNeverAttack); + continue; + } - if (_blacklistManager.IsBlacklisted(wo.Id)) continue; + if (_blacklistManager.IsBlacklisted(wo.Id)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverBlacklisted); + continue; + } // A ghost (the server doesn't have it for us): skipped until it shows it is real. - if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; } + if (Ghosts.IsGhost(wo.Id)) + { + _ghostsSkippedInScan++; + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverGhost); + continue; + } // Left for hitting the environment (New target): skipped for EnvironmentSkipSec. - if (IsEnvironmentSkipped(wo.Id)) continue; + if (IsEnvironmentSkipped(wo.Id)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverEnvironment); + continue; + } // Just killed (KillerNotification) but not yet a corpse — skip so we // don't re-lock and cast at it during its death animation. if (_recentlyKilled.ContainsKey(wo.Id)) continue; - if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)wo.Id)) continue; + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)wo.Id)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverNotAttackable); + continue; + } // Dead but not yet reclassified as corpse — skip if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; @@ -1164,7 +1189,9 @@ public partial class CombatManager : IDisposable if (!isForced && PriorityOf(wo.Id) <= 0) continue; bool losBlocked = false; - if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null) + if (LosBlockedOverride != null) + losBlocked = LosBlockedOverride(wo.Id); + else if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null) { RaycastCheckCount++; losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail); @@ -1177,6 +1204,7 @@ public partial class CombatManager : IDisposable if (losBlocked) { _nearbyNoLos++; // in range + attackable but wall-blocked — still stops nav + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverLos); continue; } @@ -3409,6 +3437,9 @@ public partial class CombatManager : IDisposable // Pick every tick: the initial pick, and a switch when the target is no longer valid, // a higher-priority monster is in range, or (Target Lock off) another is clearly better. HandleCombatTrigger(); + // A higher-priority monster in range that isn't a candidate (behind a wall, blacklisted): + // one log line saying why the target stays (R-20261031-201214-8be7). + NotePassedOverWhileEngaged(); if (activeTargetId == 0) { @@ -4564,12 +4595,15 @@ public partial class CombatManager : IDisposable { int bestId = best.Id; _lockWasSwitch = _lockedTargetId != 0 && _lockedTargetId != bestId; + // A higher-priority monster that wasn't a candidate (out of sight, past Monster Range, + // blacklisted...): named with why, so a report shows whether the priority was ignored. + string passedOver = PassedOverNoteForLock(bestId, bestPriority); if (_lockedTargetId != 0) _host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' ({switchWhy}, {DescribeTargetPos(_lockedTargetId)}) " + - $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})"); + $"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})" + passedOver); else _host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})" + - (_ghostsSkippedInScan > 0 ? $" [{_ghostsSkippedInScan} ghost(s) in range skipped]" : "")); + (_ghostsSkippedInScan > 0 ? $" [{_ghostsSkippedInScan} ghost(s) in range skipped]" : "") + passedOver); // [CombatLatency]: time this engagement from the lock to its first attack. double lockMs = Environment.TickCount64; diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 9325311..a28ece0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -75,7 +75,42 @@ public sealed partial class RynthAiPlugin private int _openedContainerId; private int _pendingLootCheckContainerId; // non-corpse container opened natively: run lootcheck on inventory arrival private int _corpseItemsEvaluated; // items checked against loot profile this corpse session - private int _corpseItemsMatched; // items that matched a loot rule this corpse session + // What came of this corpse's (or chest's) items, for the "nothing to loot" line at its end + // (NothingLootedLine). Ids, not counts: every item is classified again on every pass. + private readonly HashSet _corpseMatchedIds = new(); // a loot rule approved it for pickup + private readonly HashSet _corpseCappedIds = new(); // it matched, left at its Keep # / keep count + private int _corpseItemsLooted; // pickups confirmed (the only "looted") + + /// A new corpse or chest session: its tally starts over. + private void ResetLootTally() + { + _corpseItemsEvaluated = 0; + _corpseMatchedIds.Clear(); + _corpseCappedIds.Clear(); + _corpseItemsLooted = 0; + } + + /// + /// The chat line for a corpse or chest that ends with nothing picked up, or null when something + /// was. A match only counts as looted once its pickup is confirmed: an item left at its Keep # + /// or mana-stone keep count, for want of pack room, or as salvage with no UST is not. Items that + /// matched but were all left at their counts used to end with only the "Keep # ... leaving" + /// lines, never a "nothing to loot" (owner, 2026-10-31). + /// + private string? NothingLootedLine(string name, bool chest = false) + { + if (_corpseItemsLooted > 0) return null; + int approved = _corpseMatchedIds.Count; + int capped = _corpseCappedIds.Count(id => !_corpseMatchedIds.Contains(id)); + if (approved == 0 && capped == 0) + return _corpseItemsEvaluated > 0 + ? $"[RynthAi] Nothing {(chest ? "in" : "on")} {name} matches the loot profile." + : $"[RynthAi] Nothing to loot on {name}."; + if (approved == 0) + return $"[RynthAi] Nothing to loot on {name}: {capped} item(s) match, but you already have enough."; + return $"[RynthAi] Nothing to loot on {name}: {approved + capped} item(s) match, but none could be taken" + + (capped > 0 ? $" (you already have enough of {capped})." : "."); + } // Mana stones we've approved for loot but whose cache arrival hasn't landed yet. // Added to haveCount so the KeepCount cap isn't bypassed in the window between // MoveItemExternal confirmation and the player-inventory CreateObject event. @@ -158,6 +193,7 @@ public sealed partial class RynthAiPlugin private string _currentLootItemActionLabel = string.Empty; private string _currentLootItemName = string.Empty; private bool _currentLootItemIsSalvage; + private (string Line, int ChatType)? _currentLootItemChat; // the described "Looted" line; null = the plain one private bool _corpseIdsRequested; private long _corpseIdsRequestedAt; private bool _corpseApproachTurnsActive; @@ -476,8 +512,7 @@ public sealed partial class RynthAiPlugin _openedContainerAt = CorpseNowMs; _openedContainerInventoryObservedAt = 0; _lastLootActionAt = 0; - _corpseItemsEvaluated = 0; - _corpseItemsMatched = 0; + ResetLootTally(); _corpseIdsRequested = false; ResetCurrentLootItem(); if (!sameCorpse) @@ -608,11 +643,76 @@ public sealed partial class RynthAiPlugin Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1); } + // -- Loot stall watch (R-20261031-203155-cea0) --------------------------------------- + // The arbiter held the bot in Looting (HasLootWork: loot=True) while this claim returned + // early every tick, and nothing said why: Boost Nav Priority was on with no route to run, + // so Decide()'s BoostNav clause (guarded by WantNav) let Looting win while the full stop + // below reset every claim. The bot stood at its kill showing "Looting" with not one + // "Corpse loot:" line. Now every early return names its reason, and a Looting tick that + // ends with nothing claimed or open logs it once the stall has lasted LootStallLogMs, + // then again every LootStallRepeatMs while it lasts. + internal const long LootStallLogMs = 3_000; + internal const long LootStallRepeatMs = 15_000; + private string _lootSkipWhy = string.Empty; // why the last loot tick claimed nothing + private string _lootWorkWhy = string.Empty; // what HasLootWork last counted as loot work + private long _lootStallSince; // CorpseNowMs the stall began; 0 = none + private long _lootStallLoggedAt; + private void TickCorpseOpening() + { + _lootSkipWhy = string.Empty; + TickCorpseOpeningCore(); + WatchLootStall(); + } + + /// + /// After each loot tick: the arbiter gave Looting the tick, yet no corpse, chest or ground + /// item is claimed or open. A short gap is normal (the loot grace before a corpse exists, + /// the death animation); one past LootStallLogMs is logged with the skip reason. + /// + private void WatchLootStall() + { + bool stalled = _activity == BotActivity.Looting + && _targetCorpseId == 0 && _openedContainerId == 0 && _groundTargetId == 0; + long now = CorpseNowMs; + if (!stalled) + { + if (_lootStallSince != 0 && _lootStallLoggedAt != 0) + LootDiag($"[RynthAi] Corpse loot: the Looting stall is over after {(now - _lootStallSince) / 1000.0:0.0}s."); + _lootStallSince = 0; + _lootStallLoggedAt = 0; + return; + } + if (_lootStallSince == 0) { _lootStallSince = now; return; } + long held = now - _lootStallSince; + if (held < LootStallLogMs) return; + if (_lootStallLoggedAt != 0 && now - _lootStallLoggedAt < LootStallRepeatMs) return; + _lootStallLoggedAt = now; + string why = _lootSkipWhy.Length > 0 ? _lootSkipWhy : "no reason recorded"; + string work = _lootWorkWhy.Length > 0 ? _lootWorkWhy : "unknown"; + LootDiag($"[RynthAi] Corpse loot: Looting has held the tick {held / 1000.0:0.0}s with nothing claimed: {why} (loot work: {work})."); + } + + /// + /// Boost Nav Priority means no looting at all: corpses are passed by and the bot navigates + /// (owner, 2026-10-31: "when navprio is on it shouldn't loot at all, just bypass all corpses + /// and navigate"), route or not. The looter stood down for the flag, but HasLootWork still + /// offered the corpses, so with no route the arbiter's BoostNav clause (guarded by WantNav) + /// gave Looting the tick and the bot sat in Looting forever with nothing claimed + /// (R-20261031-203155-cea0). Both now read this one test: with the flag on there is no loot + /// work, so Looting never takes the tick. A forced loot (/ra lootthis) still goes. + /// + private static bool BoostNavHoldsLoot(LegacyUiSettings settings) + => settings.BoostNavPriority; + + private void TickCorpseOpeningCore() { var settings = _dashboard?.Settings; if (settings == null || _objectCache == null || _playerId == 0) + { + _lootSkipWhy = "no settings, object cache or player yet"; return; + } SyncCorpseContainerState(); WatchLateLandings(CorpseNowMs); @@ -623,8 +723,10 @@ public sealed partial class RynthAiPlugin // Must come before the Buffing check so that turning off the macro always // clears motion state (smooth turns, autorun) set during corpse approach. // A container flagged with /ra lootthis is looted anyway (only that one). - if ((!settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority) && !ForcedLootHolds()) + if ((!settings.IsMacroRunning || !settings.EnableLooting || BoostNavHoldsLoot(settings)) && !ForcedLootHolds()) { + _lootSkipWhy = !settings.IsMacroRunning ? "the macro is off" + : !settings.EnableLooting ? "looting is off" : "Boost Nav Priority gives the tick to the route"; ResetCorpseTarget(); return; } @@ -640,11 +742,17 @@ public sealed partial class RynthAiPlugin long haltNow = CorpseNowMs; TickUseRefusalWatch(haltNow); if (haltNow < _lootHaltUntil || _useRefusals.HoldsOpens(haltNow)) + { + _lootSkipWhy = haltNow < _lootHaltUntil + ? $"loot-wedge halt ({(_lootHaltUntil - haltNow) / 1000.0:0.0}s left)" + : "the server refuses every use (use-refusal back-off)"; return; + } // ── Buffing: halt loot work but retain target so looting resumes immediately ── if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) { + _lootSkipWhy = "buffing"; FreezeCorpseTimeout(CorpseNowMs); return; } @@ -654,6 +762,7 @@ public sealed partial class RynthAiPlugin // flight finishes first, since its answer is what lets the drain go.) if (!_currentLootItemMovePending && _manaStoneManager?.HoldsLootForDrain() == true) { + _lootSkipWhy = "a mana-tap drain runs first"; FreezeCorpseTimeout(CorpseNowMs); return; } @@ -669,6 +778,7 @@ public sealed partial class RynthAiPlugin && !_lootStarveTurn && _openedContainerId == 0) { + _lootSkipWhy = "combat has targets in range"; LogCorpsesHeldByCombat(); LogChestHeldByCombat(); FreezeCorpseTimeout(CorpseNowMs); @@ -700,7 +810,10 @@ public sealed partial class RynthAiPlugin double maxMeters = GetCorpseApproachRangeMaxMeters(settings); double minMeters = GetCorpseApproachRangeMinMeters(settings, maxMeters); if (maxMeters <= 0.25) + { + _lootSkipWhy = $"corpse approach range is {maxMeters:0.00} m (0.25 m or less)"; return; + } long now = CorpseNowMs; if (_targetCorpseId == 0) @@ -709,17 +822,22 @@ public sealed partial class RynthAiPlugin // decided, so without it a full pack still claimed the next corpse. Your own // corpse is let through unless no pack has a slot at all. if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) + { + _lootSkipWhy = "the pack is full (Stop Looting When Pack Full)"; return; + } // A ground pickup already sent finishes before a corpse is claimed. if (GroundPickupInFlight) { + _lootSkipWhy = "a ground pickup is in flight"; TickGroundLoot(settings, maxMeters); return; } if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _)) { + _lootSkipWhy = $"no lootable corpse within {maxMeters:0.0} m"; // No corpses in range. Loose ground items that match the loot profile // get their turn here; HasLootWork keeps Looting while any remain. TickGroundLoot(settings, maxMeters); @@ -1468,6 +1586,8 @@ public sealed partial class RynthAiPlugin _corpseIdsRequested = true; _corpseIdsRequestedAt = now; _lootEvalLogged.Clear(); + _needsIdCache.Clear(); + _corpseItemIdReaskedAt.Clear(); _manaStoneCapLoggedFor = 0; int requested = 0; int preClassified = 0; @@ -1569,13 +1689,34 @@ public sealed partial class RynthAiPlugin // logs against a 200 ms window). Judged before it, every stat reads 0, a // stat rule fails and the item was marked processed and left for good. // Keep holding it for AppraisalWaitMs, but never into the corpse timeout. - if (now - _corpseIdsRequestedAt < Math.Max(100, settings.LootAssessWindowMs) + AppraisalWaitMs - && now - _corpseTargetSince < GetCorpseTimeoutMs(settings) - AppraisalHoldTimeoutMarginMs) + bool beforeTimeout = now - _corpseTargetSince < GetCorpseTimeoutMs(settings) - AppraisalHoldTimeoutMarginMs; + if (now - _corpseIdsRequestedAt < Math.Max(100, settings.LootAssessWindowMs) + AppraisalWaitMs && beforeTimeout) { pendingDataCount++; continue; } - // Still no appraisal — fall through and classify best-effort. + // Still no appraisal. A rule that decides this item needs it, so judging it now + // reads its stats as 0 and lets a later rule take it: a +9 crossbow went to the + // Salvage rule on its gold (until 2026-10-31, "best-effort" here). Ask again and + // keep holding while the corpse lasts; then leave it, never classify it without. + // (An engine that can't say whether the ID is in still judges it best-effort.) + if (Host.HasHasAppraisalData) + { + if (beforeTimeout) + { + ReaskCorpseItemId(item, now); + pendingDataCount++; + continue; + } + string leftVerdict = "left: no ID came, and a rule that decides it needs one"; + if (!_lootEvalLogged.TryGetValue(item.Id, out string? leftLogged) || leftLogged != leftVerdict) + { + _lootEvalLogged[item.Id] = leftVerdict; + LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} appraised=False timedOut=True -> {leftVerdict}"); + } + _processedCorpseItems.Add(item.Id); + continue; + } } // A keeper already judged on this open is judged again only when its turn comes (it @@ -1753,6 +1894,9 @@ public sealed partial class RynthAiPlugin _currentLootItemActionLabel = matchActionLabel; _currentLootItemName = matchItemName; _currentLootItemIsSalvage = matchIsSalvage; + // Described now, while the item and its ID are surely in the cache (a stack can merge away). + _currentLootItemChat = DescribeLootPickup(firstMatchId, matchActionLabel, matchItemName, + matchRuleLabel, matchIsSalvage, stackable); _lastLootActionAt = now; return; } @@ -2445,6 +2589,7 @@ public sealed partial class RynthAiPlugin } if (answered) _currentLootItemDestsTried.Clear(); // landed: nothing to watch for (ResetCurrentLootItem) _processedCorpseItems.Add(_currentLootItemId); + _corpseItemsLooted++; LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" + $" ({now - _currentLootItemMoveRequestedAt} ms after the send{(_currentLootItemPipelined ? ", queued" : "")})."); // Each item taken is progress, so the corpse/chest timeout counts from the last pickup: @@ -2456,7 +2601,9 @@ public sealed partial class RynthAiPlugin _corpseTargetSince = now; if (_openedContainerId != 0 && _openedContainerId == _ownRecoveryCorpseId) NoteOwnCorpseItemRecovered(now); - if (!string.IsNullOrWhiteSpace(_currentLootItemName)) + if (_currentLootItemChat is { } described) + Host.WriteToChat(described.Line, described.ChatType); + else if (!string.IsNullOrWhiteSpace(_currentLootItemName)) ChatLine($"[RynthAi] Looted [{_currentLootItemActionLabel}] {_currentLootItemName}"); if (_currentLootItemIsSalvage) @@ -2501,9 +2648,15 @@ public sealed partial class RynthAiPlugin private bool HasLootWork(LegacyUiSettings settings, long nowMs) { _lootStarved = false; + _lootWorkWhy = string.Empty; if (!settings.IsMacroRunning || (!settings.EnableLooting && !ForcedLootHolds())) return false; + // The claim's own full stop (TickCorpseOpening): with Boost Nav Priority on the looter + // stands down, so there is no loot work to offer (R-20261031-203155-cea0). + if (BoostNavHoldsLoot(settings) && !ForcedLootHolds()) + return false; + // The server refuses every use (UseRefusalWatch, Stuck): no loot work until the back-off // ends, so the arbiter lets nav and combat run on instead of standing at the corpses. if (_openedContainerId == 0 && _useRefusals.HoldsOpens(CorpseNowMs)) @@ -2516,6 +2669,7 @@ public sealed partial class RynthAiPlugin _lootStarved = current != 0 && _corpseWaitingSince.TryGetValue(current, out long since) && CorpseNowMs - since >= LootStarveMs; + _lootWorkWhy = _openedContainerId != 0 ? "a container is open" : _targetCorpseId != 0 ? "a corpse is claimed" : "corpse autorun"; return true; } @@ -2526,13 +2680,19 @@ public sealed partial class RynthAiPlugin // An open chest the player or a meta opened, eligible to loot (RynthAiPlugin.ChestLoot.cs). if (HasChestLootWork(settings)) + { + _lootWorkWhy = "an open chest"; return true; + } // Loot grace: combat just ended and the corpse CreateObject has not // arrived yet. Hold Looting across that gap so nav doesn't walk away // from a body that is about to exist. if (_combatEndedAt != 0 && (nowMs - _combatEndedAt) < LootGraceMs) + { + _lootWorkWhy = "loot grace after combat"; 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. @@ -2540,6 +2700,7 @@ public sealed partial class RynthAiPlugin { double range = GetCorpseApproachRangeMaxMeters(settings); if (range > 0.25) HasUnlootedCorpsesInRange(range); // keeps _lootableInRange current + _lootWorkWhy = "Boost Loot: the kill's corpse is forming"; return true; } @@ -2547,7 +2708,17 @@ public sealed partial class RynthAiPlugin if (maxMeters <= 0.25) return false; - return HasUnlootedCorpsesInRange(maxMeters) || HasGroundLootWork(settings); + if (HasUnlootedCorpsesInRange(maxMeters)) + { + _lootWorkWhy = $"{_lootableInRange.Count} lootable corpse(s) in range, e.g. 0x{(uint)_lootableInRange[0]:X8}"; + return true; + } + if (HasGroundLootWork(settings)) + { + _lootWorkWhy = "ground loot"; + return true; + } + return false; } /// @@ -2670,6 +2841,7 @@ public sealed partial class RynthAiPlugin /// where most kills leave nothing to wait for). private bool BoostLootCanRun(LegacyUiSettings settings) => settings.BoostLootPriority && settings.IsMacroRunning && settings.EnableLooting + && !BoostNavHoldsLoot(settings) && !settings.LootOnlyRareCorpses && !IsLootingBlockedByPack(settings) && !_useRefusals.HoldsOpens(CorpseNowMs); @@ -2868,7 +3040,10 @@ public sealed partial class RynthAiPlugin } if (!preview) + { + _corpseCappedIds.Add(item.Id); ChatLine($"[RynthAi] Mana stone match: '{item.Name}' (have {haveCount}/{settings.ManaStoneKeepCount}) — at cap, leaving."); + } return false; } @@ -2880,7 +3055,7 @@ public sealed partial class RynthAiPlugin { if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn)) { - if (!preview) _corpseItemsMatched++; + if (!preview) _corpseMatchedIds.Add(item.Id); return true; } return false; @@ -2895,7 +3070,7 @@ public sealed partial class RynthAiPlugin inv => LootEvaluator.Matches(rule, inv, _charSkills), preview)) return false; } - if (!preview) _corpseItemsMatched++; + if (!preview) _corpseMatchedIds.Add(item.Id); actionLabel = nativeAction.ToString(); isSalvage = nativeAction == LootAction.Salvage; return true; @@ -2913,7 +3088,7 @@ public sealed partial class RynthAiPlugin { if (TryClassifyAsManaTap(item, settings, preview, out actionLabel, out ruleLabel, out builtIn)) { - if (!preview) _corpseItemsMatched++; + if (!preview) _corpseMatchedIds.Add(item.Id); return true; } return false; @@ -2931,7 +3106,7 @@ public sealed partial class RynthAiPlugin inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview)) return false; } - if (!preview) _corpseItemsMatched++; + if (!preview) _corpseMatchedIds.Add(item.Id); actionLabel = matchedRule.Action.ToString(); isSalvage = matchedRule.Action == VTankLootAction.Salvage; return true; @@ -2982,6 +3157,7 @@ public sealed partial class RynthAiPlugin if (preview) return LootKeepCap.UnderCap(have, cap); if (!LootKeepCap.UnderCap(have, cap)) { + _corpseCappedIds.Add(item.Id); ChatLine($"[RynthAi] Keep # '{ruleLabel}': have {have}/{cap} — leaving {item.Name}."); return false; } @@ -3114,11 +3290,46 @@ public sealed partial class RynthAiPlugin return manaTapNeedsId || NativeProfileNeedsAppraisalForClass(nativeProfile, item.ObjectClass); if (TryLoadLootProfile(string.Empty, out VTankLootProfile vtankProfile, out _)) - return manaTapNeedsId || VTankProfileNeedsAppraisalForClass(vtankProfile, item.ObjectClass); + { + if (manaTapNeedsId) return true; + // A type not readable yet fails every class condition: wait for the ID, which has it. + if (item.ObjectClass == AcObjectClass.Unknown) return true; + // Per item, as VTank decides: the rules in order, from what the item showed without an + // ID. It needs the ID when the first rule nothing has ruled out needs it (a launcher's + // missile damage keep rules, before a Salvage rule on its material). Decided without it + // (a name rule took it, or no rule can), it's judged now with no ID request. + // The answer can't change until the ID lands, so it's kept for the open (and dropped + // when the item's name or class fills in later). + if (!ReferenceEquals(_needsIdCacheProfile, vtankProfile)) { _needsIdCache.Clear(); _needsIdCacheProfile = vtankProfile; } + if (_needsIdCache.TryGetValue(item.Id, out var cached) && cached.Class == item.ObjectClass && cached.Name == item.Name) + return cached.Needs; + VTankLootContext ctx = new(Host, _playerId) { Cache = _objectCache }; + bool needs = VTankLootEvaluator.Decide(vtankProfile, item, ctx, hasIdData: false, out _) == VTankLootVerdict.NeedsId; + if (_needsIdCache.Count > 2000) _needsIdCache.Clear(); + _needsIdCache[item.Id] = (needs, item.ObjectClass, item.Name); + return needs; + } return false; // No active profile — no ID request needed } + // Corpse items whose ID is late, and when it was last asked again (cleared with each open). + private readonly Dictionary _corpseItemIdReaskedAt = new(); + + /// A held corpse item's ID is late: ask again, at most every CorpseIdReaskMs. + private void ReaskCorpseItemId(WorldObject item, long now) + { + if (_corpseItemIdReaskedAt.TryGetValue(item.Id, out long last) && now - last < CorpseIdReaskMs) return; + _corpseItemIdReaskedAt[item.Id] = now; + if (!Host.HasRequestId) return; + bool sent = Host.RequestId(unchecked((uint)item.Id)); + LootDiag($"[LootEval] '{item.Name}' id=0x{(uint)item.Id:X8}: no ID yet and a rule that decides it needs one; {(sent ? "asked again" : "ID request refused")}, holding it."); + } + + /// ItemNeedsAppraisalForLoot's answer per item for a VTank profile, cleared with each corpse open. + private readonly Dictionary _needsIdCache = new(); + private VTankLootProfile? _needsIdCacheProfile; + private static bool NativeProfileNeedsAppraisalForClass(LootProfile profile, AcObjectClass cls) { foreach (var rule in profile.Rules) @@ -3160,51 +3371,6 @@ public sealed partial class RynthAiPlugin return false; } - private static bool VTankProfileNeedsAppraisalForClass(VTankLootProfile profile, AcObjectClass cls) - { - // Requirement types that need appraisal data from the server. - // 0 = SpellNameMatch: the item's spell list comes from the appraisal, so a - // cantrip rule ("Legendary") never matched a pre-classified item. - static bool TypeNeedsAppraisal(int t) => t is - 0 or 2 or 3 or 4 or 5 or 6 or 8 or 9 or 10 or 11 or 12 or 13 or - 14 or 15 or 16 or 17 or 2000 or 2001 or 2003 or 2005 or 2006 or 2007 or 2008; - - int targetClass = (int)cls; - - foreach (var rule in profile.Rules) - { - if (rule.Conditions.Count == 0) continue; // unconditional - - bool hasClassReq = false; - bool classMatches = false; - bool needsAppraisal = false; - - foreach (var cond in rule.Conditions) - { - if (cond.NodeType == VTankNodeTypes.ObjectClass) - { - hasClassReq = true; - if (cond.DataLines.Count > 0 - && int.TryParse(cond.DataLines[0].Trim(), - System.Globalization.NumberStyles.Integer, - System.Globalization.CultureInfo.InvariantCulture, out int cls2) - && (cls2 == targetClass || (cls2 == (int)AcObjectClass.Scroll && cls == AcObjectClass.Book) - || (cls2 == (int)AcObjectClass.Book && cls == AcObjectClass.Scroll))) // scrolls once filed as Book - classMatches = true; - } - else if (TypeNeedsAppraisal(cond.NodeType)) - { - needsAppraisal = true; - } - } - - bool ruleApplies = !hasClassReq || classMatches; - if (ruleApplies && needsAppraisal) return true; - } - - return false; - } - private void MarkCorpseCompleted(int corpseId) { if (corpseId == 0) @@ -3223,6 +3389,7 @@ public sealed partial class RynthAiPlugin _processedCorpseItems.Clear(); _corpseItemAttempts.Clear(); _corpseIdsRequested = false; + _corpseItemIdReaskedAt.Clear(); _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); ResetCurrentLootItem(); @@ -3247,11 +3414,12 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Corpse loot: completed 0x{(uint)corpseId:X8}, cleared container state."); } - if (_corpseItemsEvaluated > 0 && _corpseItemsMatched == 0) - { - string corpseName = _objectCache?[corpseId]?.Name ?? $"0x{(uint)corpseId:X8}"; - ChatLine($"[RynthAi] Nothing on {corpseName} matches the loot profile."); - } + // Your own death corpse has its own end line (FinishOwnCorpseRecovery). + WorldObject? doneCorpse = _objectCache?[corpseId]; + string corpseName = doneCorpse?.Name is { Length: > 0 } cn ? cn : $"0x{(uint)corpseId:X8}"; + if ((doneCorpse == null || !EvaluateCorpseLootDecision(doneCorpse).IsOwnDeathCorpse) + && NothingLootedLine(corpseName) is { } nothingLine) + ChatLine(nothingLine); LootDiag($"[RynthAi] Corpse loot: completed 0x{(uint)corpseId:X8}, releasing container."); // Lightweight target reset — deliberately NOT ResetCorpseTarget(), so the @@ -3311,6 +3479,7 @@ public sealed partial class RynthAiPlugin _currentLootItemActionLabel = string.Empty; _currentLootItemName = string.Empty; _currentLootItemIsSalvage = false; + _currentLootItemChat = null; } private void ApproachCorpse(int corpseId) @@ -3929,7 +4098,7 @@ public sealed partial class RynthAiPlugin LootDiag($"[RynthAi] Corpse loot: 0x{(uint)id:X8} closed by the server."); return; } - bool stopped = !settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority; + bool stopped = !settings.IsMacroRunning || !settings.EnableLooting || BoostNavHoldsLoot(settings); // A hold that began after the close was deferred (a fight, a full pack) ends the wait too. double maxMeters = GetCorpseApproachRangeMaxMeters(settings); bool blocked = !stopped && maxMeters > 0.25 && !CanClaimNextCorpse(settings, maxMeters); diff --git a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs index 01e5990..2809923 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs @@ -157,7 +157,17 @@ public sealed partial class RynthAiPlugin } if (now - firstAsk < GroundAppraiseWaitMs) continue; - // Appraisal never arrived — classify best-effort, like the corpse assess window. + // The appraisal never arrived. A rule that decides the item needs it, so judged now + // its stats read 0 and a later rule (Salvage on its material) could take a keeper: + // leave it for now and ask again later (until 2026-10-31 it was judged best-effort). + // An engine that can't say whether the ID is in still judges it best-effort. + if (Host.HasHasAppraisalData) + { + _groundAppraiseAt.Remove(wo.Id); + _groundSkipUntil[wo.Id] = now + GroundLeaveCooldownMs; + LootDiag($"[LootEval] ground '{wo.Name}' cls={wo.ObjectClass} dist={dist:F1}m appraised=False -> left for now: no ID came, and a rule that decides it needs one"); + continue; + } } bool keep = ClassifyItemAgainstProfile(wo, settings, out string action, out bool salvage, out string rule); @@ -202,7 +212,11 @@ public sealed partial class RynthAiPlugin if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0) { LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'."); - ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)"); + if (DescribeLootPickup(id, _groundTargetAction, _groundTargetName, _groundTargetRule, + _groundTargetIsSalvage, IsStackAtSend(id), where: "ground") is { } described) + Host.WriteToChat(described.Line, described.ChatType); + else + ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)"); if (_groundTargetIsSalvage) _salvageManager?.EnqueueItem(unchecked((uint)id)); FinishGroundTarget(now, GroundFailCooldownMs); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs new file mode 100644 index 0000000..13efac0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs @@ -0,0 +1,86 @@ +// LootChatLine.cs — the "[RynthAi] Looted [Keep] ..." chat line, with the item's details the way +// Mag-Tools prints them when it loots something (MagItemInfoSettings.LootChat): +// +// [RynthAi] Looted [Keep] Blunt Crossbow (rule "(M) Xbow (OD +9)"): Gold, Pierce Crossbow, +22, +162%, ... +// [RynthAi] Looted [Salvage] Ornate Long Sword (rule "Gold any"): Gold, Craft 6 (Include salvage on) +// [RynthAi] Looted [Keep] Pyreal (stackables: plain) +// +// The head stays "[RynthAi] Looted [] ": the self-test meta and players' metas match it. +using System; +using System.Collections.Generic; +using System.Text; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +internal static class LootChatLine +{ + /// How much of an item a loot line describes. + public enum Detail + { + /// The plain line: action and name. + None, + /// Salvage: the rule, material and workmanship. + Salvage, + /// The rule and the Mag-style fields (the Item Info field settings applied). + Full, + } + + /// The line every pickup printed before, and still prints when it isn't described. + public static string Plain(string action, string name, string where = "") => + $"[RynthAi] Looted [{action}] {name}" + (where.Length > 0 ? $" ({where})" : string.Empty); + + /// + /// What a pickup's line shows. Only items a loot rule took (Keep, Keep #, Salvage, Read, Sell, + /// and RynthAi's built-in keeps under those actions) are described; never stackables (pyreals, + /// trade notes, spell components, anything sold in stacks), and salvage only when asked for. + /// + public static Detail DetailFor(MagItemInfoSettings? s, string action, bool isSalvage, bool stackable, AcObjectClass cls) + { + if (s == null || !s.LootChat) return Detail.None; + if (action is not ("Keep" or "KeepUpTo" or "Salvage" or "Read" or "Sell")) return Detail.None; + if (stackable || cls is AcObjectClass.Money or AcObjectClass.TradeNote or AcObjectClass.SpellComponent) + return Detail.None; + if (isSalvage || action == "Salvage" || cls == AcObjectClass.Salvage) + return s.LootChatSalvage ? Detail.Salvage : Detail.None; + return Detail.Full; + } + + /// Chat type of a described line. + public static int ChatTypeOf(MagItemInfoSettings s) => + s.LootChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.LootChatType; + + /// + /// One line for one pickup. is "" for a corpse or chest, "ground" for + /// ground loot; false adds "not IDed" (the stats may be short). + /// + public static string Format(Detail detail, MagItemInfoSettings? s, IItemPropertySource? item, + string action, string name, string rule, string where = "", bool identified = true) + { + if (detail == Detail.None || s == null || item == null) return Plain(action, name, where); + + MagItemInfoOptions options = MagItemInfoOptions.From(s); + // Salvage: everything off but material and workmanship (still only if those are on). + if (detail == Detail.Salvage) + options = options with + { + Hidden = options.Hidden | ~(MagItemInfoField.Material | MagItemInfoField.Craft), + ShowValueAndBurden = false, + }; + MagItemDescription d = MagItemDescriber.Build(item, options); + + var fields = new List(d.Segments.Count + 3); + if (d.Material.Length > 0 && !name.Contains(d.Material, StringComparison.OrdinalIgnoreCase)) + fields.Add(d.Material); + if (d.TypeMastery.Length > 0) fields.Add(d.TypeMastery); + foreach (var (_, text) in d.Segments) fields.Add(text); + if (!identified) fields.Add("not IDed"); + + var sb = new StringBuilder(Plain(action, name), 256); + string ruleText = rule.Length > 0 ? $"rule \"{rule}\"" : string.Empty; + if (where.Length > 0 && ruleText.Length > 0) sb.Append(" (").Append(where).Append(", ").Append(ruleText).Append(')'); + else if (where.Length > 0 || ruleText.Length > 0) sb.Append(" (").Append(where).Append(ruleText).Append(')'); + if (fields.Count > 0) sb.Append(": ").Append(string.Join(", ", fields)); + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs index b49f8c9..c0512d3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs @@ -87,6 +87,10 @@ internal sealed class MagItemDescription { /// "[Material ]Name[ (DamageType Mastery)]". public string Title = string.Empty; + /// The material name ("Gold"), or "" when none or hidden; set even when the title leaves it out. + public string Material = string.Empty; + /// The title's "(DamageType Mastery)" text without the brackets, or "". + public string TypeMastery = string.Empty; public readonly List<(MagItemSection Section, string Text)> Segments = new(); public void Add(MagItemSection section, string text) @@ -266,6 +270,7 @@ internal static class MagItemDescriber if (material > 0 && Show(MagItemInfoField.Material)) { string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}"; + d.Material = matName; // Loot names usually omit the material; don't double it when the name already starts with it. if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase)) sb.Append(matName).Append(' '); @@ -281,6 +286,7 @@ internal static class MagItemDescriber : string.Empty; string inner = $"{dmgType} {masteryName}".Trim(); if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')'); + d.TypeMastery = inner; } d.Title = sb.ToString(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs index 279eeba..904a480 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs @@ -53,8 +53,8 @@ public sealed class MagItemInfoSettings public const int SameAsHeader = -1; // ── When to print ──────────────────────────────────────────────────────── - /// Print automatically when an item is selected. - public bool OnSelect; + /// Print automatically when an item is selected. On unless the player turned it off (2026-10-31). + public bool OnSelect = true; /// /// Print the selected item after a left () or right () /// click in the game world / inventory — also re-prints an item that was already selected. @@ -68,6 +68,17 @@ public sealed class MagItemInfoSettings /// Seconds to wait for an ID before printing partial data. public float IdTimeoutSec = 3f; + // ── Loot lines ─────────────────────────────────────────────────────────── + /// + /// The "Looted [Keep] ..." line of an item a loot rule took also names the rule and the item's + /// details (one line, the fields below applied). Stackables (pyreals, notes, comps) never do. + /// + public bool LootChat = true; + /// Salvage is described too, short: material and workmanship only. + public bool LootChatSalvage; + /// Chat type of a described loot line, or for . + public int LootChatType = SameAsHeader; + // ── What to print ──────────────────────────────────────────────────────── /// bits that are NOT printed. public int HiddenFields; @@ -115,6 +126,7 @@ public sealed class MagItemInfoSettings MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64); if (ChatType < 0 || ChatType > 31) ChatType = 1; if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader; + if (LootChatType < SameAsHeader || LootChatType > 31) LootChatType = SameAsHeader; if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff; if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines; Prefix ??= string.Empty; @@ -132,6 +144,7 @@ public sealed class MagItemInfoSettings OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor; OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther; IdTimeoutSec = d.IdTimeoutSec; + LootChat = d.LootChat; LootChatSalvage = d.LootChatSalvage; LootChatType = d.LootChatType; HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings; ShowValueAndBurden = d.ShowValueAndBurden; SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index c1c66ab..ef824a8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -1091,6 +1091,7 @@ internal sealed class LegacyAdvancedSettingsUi _settings.ItemInfoSettings.ShowWindow = !_settings.ItemInfoSettings.ShowWindow; if (ImGui.IsItemHovered()) ImGui.SetTooltip("Open the RynthAi Item Info window (fields, ratings, click trigger, layout)."); + LegacyItemInfoUi.RenderLootChat(_settings.ItemInfoSettings, "##advLoot"); ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse); if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs index c069e57..b596a30 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs @@ -127,6 +127,29 @@ internal sealed class LegacyItemInfoUi s.Sanitize(); if (ImGui.IsItemHovered()) ImGui.SetTooltip("How long to wait for an unidentified item's appraisal\nbefore printing what is already known."); + + RenderLootChat(s, "##iiLoot"); + } + + /// + /// "Describe looted items in chat" + "Include salvage". Shared with Advanced Settings → Looting, + /// so keeps the ImGui ids unique per window. + /// + public static void RenderLootChat(MagItemInfoSettings s, string idSuffix) + { + ImGui.Checkbox("Describe looted items in chat" + idSuffix, ref s.LootChat); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "The \"Looted\" line of an item a loot rule took names the rule and\n" + + "the item's details, in one line, with the fields chosen here:\n" + + " Looted [Keep] Blunt Crossbow (rule \"Xbow\"): Gold, Pierce Crossbow, +22, ...\n" + + "Pyreals, trade notes, spell components and other stacks keep the short line."); + ImGui.SameLine(); + ImGui.BeginDisabled(!s.LootChat); + ImGui.Checkbox("Include salvage" + idSuffix + "Salv", ref s.LootChatSalvage); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Describe items taken for salvage too, short: material and workmanship.\nOff: a corpse full of salvage keeps its short lines."); } /// @@ -271,6 +294,14 @@ internal sealed class LegacyItemInfoUi if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above)."); + ImGui.BeginDisabled(!s.LootChat); + ChatTypeCombo("Loot lines colour##iiChatLoot", ref s.LootChatType, allowSameAsHeader: true); + ImGui.SameLine(); + if (ImGui.Button("Test##iiChatLootTest")) _testChatType?.Invoke(LootChatLine.ChatTypeOf(s)); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Chat type of a described \"Looted\" line\n(\"Same as name line\": the chat type above)."); + ImGui.SetNextItemWidth(220); ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32); if (ImGui.IsItemHovered()) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs new file mode 100644 index 0000000..0e08170 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; +using RynthCore.Loot.VTank; + +namespace RynthCore.Plugin.RynthAi.Loot; + +/// +/// /ra loot why: which rule of a VTank profile takes an item, and why the rules above it +/// didn't. Pure (no chat, no host calls beyond the context's reads), so tests can run it. +/// +internal static class LootWhy +{ + /// One rule above the winner that came close: it passed at least one condition before one failed. + public readonly record struct NearMiss(int Index, string RuleName, string Failed); + + public sealed class Result + { + public VTankLootVerdict Verdict { get; init; } + /// The matched rule (Match), the rule that waits for the ID (NeedsId), or -1. + public int Index { get; init; } = -1; + public string RuleName { get; init; } = string.Empty; + public VTankLootAction Action { get; init; } + public List NearMisses { get; } = new(); + } + + public static string NameOf(VTankLootRule rule, int index) + => string.IsNullOrWhiteSpace(rule.Name) ? "#" + index : rule.Name.Trim(); + + /// + /// The decision () and, for each enabled rule above + /// it that passed a condition before failing, the first condition that failed and what it read. + /// Rules that fail on their first condition (another class, weapon type, material or name) + /// aren't listed: they were never close. + /// + public static Result Explain(VTankLootProfile profile, WorldObject item, VTankLootContext? ctx, bool hasIdData) + { + VTankLootVerdict verdict = VTankLootEvaluator.Decide(profile, item, ctx, hasIdData, out int index); + var result = new Result + { + Verdict = verdict, + Index = index, + RuleName = index >= 0 ? NameOf(profile.Rules[index], index) : string.Empty, + Action = index >= 0 ? profile.Rules[index].Action : default, + }; + + int end = index >= 0 ? index : profile.Rules.Count; + for (int i = 0; i < end; i++) + { + VTankLootRule rule = profile.Rules[i]; + if (IsDisabled(rule)) continue; + int passed = 0; + foreach (VTankLootCondition cond in rule.Conditions) + { + if (!hasIdData && VTankLootEvaluator.ConditionNeedsId(cond)) continue; + bool ok; + try { ok = VTankLootEvaluator.MatchCondition(cond, item, ctx); } + catch { ok = false; } + if (ok) { passed++; continue; } + if (passed > 0) + result.NearMisses.Add(new NearMiss(i, NameOf(rule, i), VTankLootEvaluator.Explain(cond, item, ctx))); + break; + } + } + return result; + } + + private static bool IsDisabled(VTankLootRule rule) + { + foreach (VTankLootCondition c in rule.Conditions) + if (c.NodeType == VTankNodeTypes.DisabledRule && c.DataLines.Count > 0 + && string.Equals(c.DataLines[0].Trim(), "true", System.StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs index 14573e3..cd9ac03 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/VTankLootEvaluator.cs @@ -41,6 +41,26 @@ public sealed class VTankLootContext return result; } + private readonly Dictionary _baseSkillCache = new(); + + /// + /// The character's base skill (no enchantments), for VTank's "Character Base Skill" node. It + /// compared the training class (2 trained, 3 specialized) with skill levels like 300 until + /// 2026-10-31. An engine without the base read answers the buffed level. + /// + public int GetBaseSkill(uint stypeSkill) + { + if (_baseSkillCache.TryGetValue(stypeSkill, out int cached)) return cached; + int result = 0; + if (PlayerId != 0 && Host.HasGetObjectSkillBuffed + && Host.TryGetObjectSkillLevel(PlayerId, stypeSkill, raw: 1, out int level)) + result = level; + else + result = GetSkill(stypeSkill).Buffed; + _baseSkillCache[stypeSkill] = result; + return result; + } + public int GetLevel() { if (_level.HasValue) return _level.Value; @@ -130,6 +150,17 @@ public sealed class VTankLootContext internal WorldObjectCache? Cache { get; set; } } +/// What found for an item. +public enum VTankLootVerdict +{ + /// No rule takes the item. + NoMatch, + /// A rule takes it. + Match, + /// The first rule that could take it needs the item's identify data, which isn't in yet. + NeedsId, +} + /// /// Evaluates a VTankLootRule against a WorldObject. All matching logic is here /// so the LootSdk types stay pure-data and the editor can reference them @@ -161,22 +192,107 @@ public static class VTankLootEvaluator /// /// The first rule, in list order, that matches the item (rule Priority is not consulted), /// or null when none does; is its position, or -1. - /// Corpse looting classifies items with this. + /// The item's identify data is taken as in (see for an item without it). /// public static VTankLootRule? FirstMatch(VTankLootProfile profile, WorldObject? item, VTankLootContext? ctx, out int index) + => Decide(profile, item, ctx, hasIdData: true, out index) == VTankLootVerdict.Match ? profile.Rules[index] : null; + + /// + /// The corpse looter's decision, as VTank makes it: the rules in list order, the first that + /// matches wins. For an item whose identify data hasn't arrived ( + /// false), a rule that nothing seen so far rules out but that needs the ID to decide stops the + /// search with : judged now its ID-only values read 0, it + /// fails, and a later rule takes the item (a +9 crossbow's Keep rule failed and the Salvage rule + /// on its gold took it). A rule that a condition known without the ID (class, name, value, + /// material) already fails is passed over, whatever order its conditions are in. A condition + /// that throws (bad data, unknown node type) fails its rule. is the + /// matched rule (Match) or the rule that needs the ID (NeedsId); -1 for NoMatch. + /// + public static VTankLootVerdict Decide(VTankLootProfile profile, WorldObject? item, VTankLootContext? ctx, bool hasIdData, out int index) { + index = -1; + if (item is null) return VTankLootVerdict.NoMatch; + uint itemId = unchecked((uint)item.Id); for (int i = 0; i < profile.Rules.Count; i++) { - if (Match(profile.Rules[i], item, ctx)) + VTankLootRule rule = profile.Rules[i]; + bool failed = false, waitsForId = false; + foreach (var cond in rule.Conditions) { - index = i; - return profile.Rules[i]; + if (!hasIdData && ConditionNeedsId(cond)) { waitsForId = true; continue; } + bool ok; + try { ok = Match(cond, item, itemId, ctx); } + catch { ok = false; } + if (!ok) { failed = true; break; } } + if (failed) continue; + index = i; + return waitsForId ? VTankLootVerdict.NeedsId : VTankLootVerdict.Match; } - index = -1; - return null; + return VTankLootVerdict.NoMatch; } + // STypeInts the CreateObject message carries (the engine answers them before any ID: + // RynthCore PwdLayout.IntStypes). Everything else, workmanship (105) included, comes with the ID. + private static readonly HashSet CreateIntKeys = new() + { + 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 18, 19, 50, 51, 91, 92, 94, 95, 131, 133, 151, 152, 280, + }; + + /// + /// True when the condition reads something only the item's identify (appraisal) data holds: + /// stats, spells, wield requirements, workmanship, ratings, damage. False for what the + /// CreateObject message already gave (name, class, value, burden, material, icon, WCID, stack, + /// palettes) and for the character and disabled nodes. + /// + public static bool ConditionNeedsId(VTankLootCondition cond) + { + var d = cond.DataLines; + switch (cond.NodeType) + { + case VTankNodeTypes.ObjectClass: + case VTankNodeTypes.DisabledRule: + case VTankNodeTypes.DamagePercentGE: // always fails, ID or not + case VTankNodeTypes.AnySimilarColor: + case VTankNodeTypes.SimilarColorArmorType: + case VTankNodeTypes.SlotSimilarColor: + case VTankNodeTypes.SlotExactPalette: // palettes come with the object + case VTankNodeTypes.CharacterSkillGE: + case VTankNodeTypes.CharacterMainPackEmptySlotsGE: + case VTankNodeTypes.CharacterLevelGE: + case VTankNodeTypes.CharacterLevelLE: + case VTankNodeTypes.CharacterBaseSkill: + return false; + case VTankNodeTypes.StringValueMatch: + return !(d.Count > 1 && TryInt(d[1], out int skey) && skey == (int)StringValueKey.Name); + case VTankNodeTypes.LongValKeyLE: + case VTankNodeTypes.LongValKeyGE: + case VTankNodeTypes.LongValKeyE: + case VTankNodeTypes.LongValKeyNE: + case VTankNodeTypes.LongValKeyFlagExists: + return !(d.Count > 1 && TryInt(d[1], out int lkey) && IsCreateIntKey(lkey)); + case VTankNodeTypes.DoubleValKeyLE: + case VTankNodeTypes.DoubleValKeyGE: + // UseRadius and VTank's SalvageWorkmanship (the engine's float 280) come with the object. + return !(d.Count > 1 && TryInt(d[1], out int dkey) && (dkey == (int)DoubleValueKey.UseRadius || unchecked((uint)dkey) == 0x0A000009)); + default: + return true; // spells, damage, buffed values, ratings; unknown types fail anyway + } + } + + private static bool IsCreateIntKey(int key) + { + uint k = unchecked((uint)key); + if (k == WorldObjectCache.DecalTypeKey) return true; // WCID + if (k is 0x0D000001 or 0x0D000002 or 0x0D000008 or 0x0D000029 or 0x0D00002A) return true; // icon, container, spell, overlays + uint stype = WorldObjectCache.DecalIntStype(k); + if (stype != 0) return CreateIntKeys.Contains(unchecked((int)stype)); + return CreateIntKeys.Contains(key); + } + + private static bool TryInt(string s, out int v) + => int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out v); + /// /// One condition on its own, same semantics as inside . /// AutoVendor judges conditions one at a time so it can tell "no" from "can't tell". @@ -185,6 +301,118 @@ public static class VTankLootEvaluator public static bool MatchCondition(VTankLootCondition cond, WorldObject item, VTankLootContext? ctx) => Match(cond, item, unchecked((uint)item.Id), ctx); + /// + /// One condition in words with the value it read, for /ra loot why: "Buffed Missile Damage + /// >= 86: read 84.0 (max 0 + mod 2.65 -> 55.0 + elemental 22 + cantrips 7)". Never throws. + /// + public static string Explain(VTankLootCondition cond, WorldObject item, VTankLootContext? ctx) + { + // Plain ASCII: AC's chat font has no ≥ ≤ ≠. + string what = VTankNodeTypes.DisplayName(cond.NodeType).Replace("≥", ">=").Replace("≤", "<=").Replace("≠", "!=") + + " " + Clip(string.Join(", ", cond.DataLines), 60); + try { return what.Trim() + ": read " + Clip(ReadValue(cond, item, unchecked((uint)item.Id), ctx), 160); } + catch (Exception ex) { return what.Trim() + ": can't evaluate (" + ex.GetType().Name + ")"; } + } + + private static string F(double v) => v.ToString("0.###", CultureInfo.InvariantCulture); + + private static string Clip(string s, int max) => s.Length <= max ? s : s.Substring(0, max - 3) + "..."; + + private static string ReadValue(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx) + { + var d = cond.DataLines; + switch (cond.NodeType) + { + case VTankNodeTypes.StringValueMatch: + return "'" + item.Values((StringValueKey)ReadInt(d, 1), string.Empty) + "'"; + case VTankNodeTypes.LongValKeyLE: + case VTankNodeTypes.LongValKeyGE: + case VTankNodeTypes.LongValKeyE: + case VTankNodeTypes.LongValKeyNE: + case VTankNodeTypes.LongValKeyFlagExists: + return item.Values(ReadInt(d, 1), 0).ToString(CultureInfo.InvariantCulture) + " (key " + ReadInt(d, 1).ToString(CultureInfo.InvariantCulture) + ")"; + case VTankNodeTypes.DoubleValKeyLE: + case VTankNodeTypes.DoubleValKeyGE: + return F(item.Values(FloatKey(ReadInt(d, 1)), 0.0)) + " (key " + ReadInt(d, 1).ToString(CultureInfo.InvariantCulture) + ")"; + case VTankNodeTypes.ObjectClass: + return item.ObjectClass + " (" + ((int)item.ObjectClass).ToString(CultureInfo.InvariantCulture) + ")"; + case VTankNodeTypes.SpellNameMatch: + case VTankNodeTypes.SpellMatch: + case VTankNodeTypes.SpellCountGE: + { + if (ctx is null) return "no spell list"; + string[] names = ctx.GetItemSpellNames(itemId); + return names.Length == 0 ? "no spells" : names.Length + " spell(s): " + string.Join(", ", names); + } + case VTankNodeTypes.MinDamageGE: + { + int max = item.Values(44, 0); + double v = item.Values(DoubleValueKey.DamageVariance, 0.0); + return F(max - v * max) + " (max " + max + ", variance " + F(v) + ")"; + } + case VTankNodeTypes.BuffedMedianDamageGE: + { + int max = BuffedLong(item, itemId, ctx, MaxDamageKey); + double v = item.Values(DoubleValueKey.DamageVariance, 0.0); + return F((max - v * max + max) / 2.0) + " (buffed max " + max + ", variance " + F(v) + ")"; + } + case VTankNodeTypes.BuffedMissileDamageGE: + { + double mod = item.Values(DoubleValueKey.DamageMod, 0.0); + if (mod <= 0) return "no damage modifier (not a launcher)"; + int raw = item.Values(MaxDamageKey, 0); + int buffed = BuffedLong(item, itemId, ctx, MaxDamageKey); + return F(BuffedMissileDamage(item, itemId, ctx)) + " (max " + raw + " + mod " + F(mod) + " -> " + F((mod - 1) * 100 / 3) + + " + elemental " + item.Values(ElementalDamageBonusKey, 0) + " + cantrips " + (buffed - raw) + ")"; + } + case VTankNodeTypes.BuffedLongValKeyGE: + { + int key = ReadInt(d, 1); + int raw = item.Values(key, 0), buffed = BuffedLong(item, itemId, ctx, key); + return buffed + (buffed != raw ? " (" + raw + " + cantrips " + (buffed - raw) + ")" : "") + " (key " + key + ")"; + } + case VTankNodeTypes.BuffedDoubleValKeyGE: + { + int key = ReadInt(d, 1); + double raw = item.Values(FloatKey(key), 0.0), buffed = BuffedDouble(item, itemId, ctx, key); + return F(buffed) + (buffed != raw ? " (" + F(raw) + " with cantrips)" : "") + " (key " + key + ")"; + } + case VTankNodeTypes.CalcdBuffedTinkedDamageGE: + return F(BuffedTinkedDamage(item, itemId, ctx)) + " (" + TinksLeft(item) + " tink(s) left)"; + case VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE: + { + MatchTinkedTargetMelee(item, itemId, ctx, d, out double dot); + return (dot < 0 ? "defense/attack target out of reach" : "damage " + F(dot)) + " (" + TinksLeft(item) + " tink(s) left, melee " + + F(BuffedDouble(item, itemId, ctx, 29)) + ", attack " + F(BuffedDouble(item, itemId, ctx, AttackBonusKey)) + ")"; + } + case VTankNodeTypes.TotalRatingsGE: + return (item.Values(370, 0) + item.Values(371, 0) + item.Values(372, 0) + item.Values(373, 0) + + item.Values(374, 0) + item.Values(375, 0) + item.Values(376, 0) + item.Values(379, 0)).ToString(CultureInfo.InvariantCulture); + case VTankNodeTypes.CharacterSkillGE: + return ctx is null ? "no character" : ctx.GetSkill(unchecked((uint)ReadInt(d, 1))).Buffed.ToString(CultureInfo.InvariantCulture); + case VTankNodeTypes.CharacterBaseSkill: + return ctx is null ? "no character" : ctx.GetBaseSkill(unchecked((uint)ReadInt(d, 0))).ToString(CultureInfo.InvariantCulture); + case VTankNodeTypes.CharacterLevelGE: + case VTankNodeTypes.CharacterLevelLE: + return ctx is null ? "no character" : ctx.GetLevel().ToString(CultureInfo.InvariantCulture); + case VTankNodeTypes.CharacterMainPackEmptySlotsGE: + return ctx is null ? "no character" : ctx.GetMainPackEmptySlots() + " free"; + case VTankNodeTypes.SlotExactPalette: + { + if (ctx is null) return "no palettes"; + var (subIds, _) = ctx.GetItemPalettes(itemId); + int slot = ReadInt(d, 0); + return subIds.Length == 0 ? "no palette data" : slot >= 0 && slot < subIds.Length ? (subIds[slot] & 0x00FFFFFFu).ToString(CultureInfo.InvariantCulture) : "no slot " + slot; + } + case VTankNodeTypes.DisabledRule: + return d.Count > 0 && string.Equals(d[0].Trim(), "true", StringComparison.OrdinalIgnoreCase) ? "rule disabled" : "enabled"; + case VTankNodeTypes.DamagePercentGE: + return "never matches (as VTank)"; + default: + return Match(cond, item, itemId, ctx) ? "passes" : "fails"; + } + } + private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx) { var d = cond.DataLines; @@ -194,8 +422,9 @@ public static class VTankLootEvaluator VTankNodeTypes.StringValueMatch => MatchStringValue(item, d), VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val, VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val, - VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) <= val, - VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val, + // VTank compares double keys as floats: 1.2 + 0.09 must still be >= 1.29. + VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && (float)item.Values(FloatKey(key), 0.0) <= (float)val, + VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && (float)item.Values(FloatKey(key), 0.0) >= (float)val, VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally VTankNodeTypes.ObjectClass => ScrollLearner.ClassMatches(item, ReadInt(d, 0)), // Scroll (42) also matches scroll Books VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0), @@ -213,13 +442,14 @@ public static class VTankLootEvaluator VTankNodeTypes.CharacterLevelGE => ctx is null || ctx.GetLevel() >= ReadInt(d, 0), VTankNodeTypes.CharacterLevelLE => ctx is null || ctx.GetLevel() <= ReadInt(d, 0), VTankNodeTypes.CharacterBaseSkill => MatchCharacterBaseSkill(ctx, d), - VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, d), - VTankNodeTypes.BuffedMissileDamageGE => MatchBuffedMissileDamageGE(item, d), - VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val, - VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val, - VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(44, 0) >= ReadDouble(d, 0), + VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, itemId, ctx, d), + // As floats, like the double keys: 2.65 - 1 is 1.6499999..., and a 385 crossbow must still reach 77. + VTankNodeTypes.BuffedMissileDamageGE => (float)BuffedMissileDamage(item, itemId, ctx) >= (float)ReadDouble(d, 0), + VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && BuffedLong(item, itemId, ctx, key) >= val, + VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && (float)BuffedDouble(item, itemId, ctx, key) >= (float)val, + VTankNodeTypes.CalcdBuffedTinkedDamageGE => (float)BuffedTinkedDamage(item, itemId, ctx) >= (float)ReadDouble(d, 0), VTankNodeTypes.TotalRatingsGE => MatchTotalRatingsGE(item, d), - VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false, // not implemented + VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => MatchTinkedTargetMelee(item, itemId, ctx, d, out _), VTankNodeTypes.DisabledRule => MatchDisabledRule(d), _ => throw new InvalidOperationException($"Unsupported VTank loot node type {cond.NodeType}."), }; @@ -303,28 +533,172 @@ public static class VTankLootEvaluator int min = ReadInt(d, 1); int max = ReadInt(d, 2); if (ctx is null) return true; - var (_, baseVal) = ctx.GetSkill(unchecked((uint)skillId)); + int baseVal = ctx.GetBaseSkill(unchecked((uint)skillId)); return baseVal >= min && baseVal <= max; } - private static bool MatchBuffedMedianDamageGE(WorldObject item, IList d) + private static bool MatchBuffedMedianDamageGE(WorldObject item, uint itemId, VTankLootContext? ctx, IList d) { double threshold = ReadDouble(d, 0); - int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07) + int maxDamage = BuffedLong(item, itemId, ctx, MaxDamageKey); if (maxDamage == 0) return false; double variance = item.Values(DoubleValueKey.DamageVariance, 0.0); double minDamage = maxDamage - (variance * maxDamage); return (minDamage + maxDamage) / 2.0 >= threshold; } - private static bool MatchBuffedMissileDamageGE(WorldObject item, IList d) + // ── Buffed values (VTank's "Buffed ..." and "Calc'd ..." nodes) ───────────── + // + // "Buffed" is the item as it will be once wielded: its value plus what its own cantrips add + // (Legendary Blood Thirst +10 damage, Epic Defender +7% melee defense, ...). Its other item + // spells (Blood Drinker, Defender VI ...) add nothing: the character casts those anyway. + // Only the cantrips below change a buffed value (the same table Mag-Tools shows buffed values + // with); a key with none of them reads as the plain value. Ids are retail's (SpellData.txt). + + /// Decal's MaxDamage (0x0D000022): the weapon profile's max damage, property 44. + internal const int MaxDamageKey = unchecked((int)0x0D000022); + private const int AttackBonusKey = unchecked((int)0x0A00000C); + + // (spell id, amount added) + private static readonly (uint Spell, int Add)[] MaxDamageCantrips = + { (2598, 2), (2586, 4), (4661, 7), (6089, 10) }; // Minor..Legendary Blood Thirst + private static readonly (uint Spell, int Add)[] ArmorLevelCantrips = + { (2604, 20), (2592, 40), (4667, 60), (6095, 80) }; // Minor..Legendary Impenetrability + private static readonly (uint Spell, double Add)[] MeleeDefenseCantrips = + { (2600, 0.03), (3985, 0.04), (2588, 0.05), (4663, 0.07), (6091, 0.09) }; // Minor Defender, Mukkir Sense, Major..Legendary Defender + private static readonly (uint Spell, double Add)[] AttackCantrips = + { (2603, 0.03), (2591, 0.05), (4666, 0.07), (6094, 0.09) }; // Minor..Legendary Heart Thirst + private static readonly (uint Spell, double Add)[] ElementalVsMonsterCantrips = + { (3251, 0.01), (3250, 0.03), (4670, 0.05), (6098, 0.07) }; // Minor..Legendary Spirit Thirst + // Hermetic Link cantrips multiply the mana conversion bonus. + private static readonly (uint Spell, double Mul)[] ManaConversionCantrips = + { (3201, 1.05), (3199, 1.10), (3202, 1.15), (3200, 1.20), (6086, 1.25), (6087, 1.30) }; + + private static uint[] ItemSpells(uint itemId, VTankLootContext? ctx) + => ctx is null ? Array.Empty() : ctx.GetItemSpellIds(itemId); + + /// A long key as VTank's Buffed Long Key reads it: the value plus the item's own cantrips. + internal static int BuffedLong(WorldObject item, uint itemId, VTankLootContext? ctx, int key) { - double threshold = ReadDouble(d, 0); - int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07) + int value = item.Values(key, 0); + (uint Spell, int Add)[]? table = key switch + { + MaxDamageKey or 44 => MaxDamageCantrips, + 28 => ArmorLevelCantrips, + _ => null, + }; + if (table is null) return value; + foreach (uint s in ItemSpells(itemId, ctx)) + foreach (var (spell, add) in table) + if (s == spell) value += add; + return value; + } + + /// A double key as VTank's Buffed Double Key reads it: the value plus (or, for mana + /// conversion, times) the item's own cantrips. + internal static double BuffedDouble(WorldObject item, uint itemId, VTankLootContext? ctx, int key) + { + double value = item.Values(FloatKey(key), 0.0); + if (key == 144) + { + foreach (uint s in ItemSpells(itemId, ctx)) + foreach (var (spell, mul) in ManaConversionCantrips) + if (s == spell) value *= mul; + return value; + } + (uint Spell, double Add)[]? table = key switch + { + 29 => MeleeDefenseCantrips, + AttackBonusKey or 62 => AttackCantrips, + 152 => ElementalVsMonsterCantrips, + _ => null, + }; + if (table is null) return value; + foreach (uint s in ItemSpells(itemId, ctx)) + foreach (var (spell, add) in table) + if (s == spell) value += add; + return value; + } + + /// + /// VTank's "Calc'd Buffed Missile Damage" of a bow, crossbow or atlatl: buffed max damage + /// (0 on launchers) + damage modifier as a percentage over 1, divided by 3 + the elemental + /// damage bonus. A 385 crossbow with a 2.65 modifier and +22 is 0 + 165/3 + 22 = 77, LootSnob's + /// "Xbow (Max 385)"; Legendary Blood Thirst makes it 87 ("OD +10"). -1 for an item with no damage + /// modifier (not a launcher). This read max damage x the wand's elemental modifier (152) until + /// 2026-10-31, which is 0 on every launcher, so no missile damage rule ever matched. + /// + internal static double BuffedMissileDamage(WorldObject item, uint itemId, VTankLootContext? ctx) + { + double mod = item.Values(DoubleValueKey.DamageMod, 0.0); + if (mod <= 0) return -1; + int elemental = item.Values(ElementalDamageBonusKey, 0); + return BuffedLong(item, itemId, ctx, MaxDamageKey) + (mod - 1.0) * 100.0 / 3.0 + elemental; + } + + private const int ElementalDamageBonusKey = 204; // ElementalDamageBonus (Decal ElementalDmgBonus) + private const int NumTimesTinkeredKey = 171; + private const int ImbuedEffectKey = 179; + private const int MaterialTypeKey = 131; + + /// Damage over time as VTank figures it: 10% crits at double damage. + private static double DamageOverTime(double maxDamage, double variance) + => maxDamage * ((1 - 0.1) * (2 - variance) / 2 + 0.1 * 2); + + /// Tinks the item can still take: 10 less those done, one kept for an imbue it lacks; none without a material. + private static int TinksLeft(WorldObject item) + { + if (item.Values(MaterialTypeKey, 0) == 0) return 0; + int left = Math.Max(0, 10 - item.Values(NumTimesTinkeredKey, 0)); + if (item.Values(ImbuedEffectKey, 0) == 0) left = Math.Max(0, left - 1); + return left; + } + + /// Spends on damage (iron +1 or granite variance x0.8, whichever + /// helps more) and returns the damage over time with Blood Drinker's 24. + private static double TinkedDamage(int maxDamage, double variance, int tinks) + { + for (int i = 0; i < tinks; i++) + { + double iron = DamageOverTime(maxDamage + 1 + 24, variance); + double granite = DamageOverTime(maxDamage + 24, variance * 0.8); + if (iron >= granite) maxDamage++; + else variance *= 0.8; + } + return DamageOverTime(maxDamage + 24, variance); + } + + /// VTank's "Calc'd Buffed Tinked Damage": the melee weapon's damage over time with every + /// tink it has left on damage. -1 with no max damage. + internal static double BuffedTinkedDamage(WorldObject item, uint itemId, VTankLootContext? ctx) + { + int maxDamage = BuffedLong(item, itemId, ctx, MaxDamageKey); + if (maxDamage == 0) return -1; + return TinkedDamage(maxDamage, item.Values(DoubleValueKey.DamageVariance, 0.0), TinksLeft(item)); + } + + /// + /// VTank's "Calc'd Buffed Tinked Target Melee" (data: damage over time, melee defense, attack): + /// can the weapon's tinks left reach the melee defense target (brass, +0.01 each), then the + /// attack target (velvet, +0.01 each), and with the tinks still left on damage reach the damage + /// target? Targets are the item's own units (1.17 = +17%). is the damage + /// reached, or -1 when a target is out of reach. This always failed until 2026-10-31. + /// + internal static bool MatchTinkedTargetMelee(WorldObject item, uint itemId, VTankLootContext? ctx, IList d, out double dot) + { + dot = -1; + double targetDot = ReadDouble(d, 0), targetDef = ReadDouble(d, 1), targetAtk = ReadDouble(d, 2); + int maxDamage = BuffedLong(item, itemId, ctx, MaxDamageKey); if (maxDamage == 0) return false; - double elemBonus = item.Values((DoubleValueKey)152, 1.0); - if (elemBonus < 1.0) elemBonus = 1.0; - return maxDamage * elemBonus >= threshold; + int tinks = TinksLeft(item); + double def = BuffedDouble(item, itemId, ctx, 29); + while (tinks > 0 && (float)def < (float)targetDef) { def += 0.01; tinks--; } + if ((float)def < (float)targetDef) return false; + double atk = BuffedDouble(item, itemId, ctx, AttackBonusKey); + while (tinks > 0 && (float)atk < (float)targetAtk) { atk += 0.01; tinks--; } + if ((float)atk < (float)targetAtk) return false; + dot = TinkedDamage(maxDamage, item.Values(DoubleValueKey.DamageVariance, 0.0), tinks); + return (float)dot >= (float)targetDot; } private static bool MatchTotalRatingsGE(WorldObject item, IList d) diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 30519bc..191ab43 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3639,6 +3639,11 @@ internal sealed partial class ExpressionEngine ["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0), ["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0), ["ItemInfoOnSelect"] = (() => B(s.ItemInfoSettings.OnSelect), v => s.ItemInfoSettings.OnSelect = ToDouble(v) != 0), + // The looter's "Looted" line names the rule and the item's details (salvage: on request). + ["ItemInfoLootChat"] = (() => B(s.ItemInfoSettings.LootChat), v => s.ItemInfoSettings.LootChat = ToDouble(v) != 0), + ["ItemInfoLootSalvage"] = (() => B(s.ItemInfoSettings.LootChatSalvage), v => s.ItemInfoSettings.LootChatSalvage = ToDouble(v) != 0), + // -1 = the Item Info chat type. + ["ItemInfoLootChatType"] = (() => I(s.ItemInfoSettings.LootChatType), v => { if (int.TryParse(v, out int i)) s.ItemInfoSettings.LootChatType = Math.Clamp(i, -1, 31); }), ["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0), ["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0), ["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0), diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index c1ab3b0..6b779dd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -124,6 +124,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra lootparse — inspect the selected loot profile"); ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory"); ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)"); + ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item"); ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)"); ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot"); @@ -1697,8 +1698,14 @@ public sealed partial class RynthAiPlugin private void HandleLootCommand(string[] parts) { string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; + if (sub == "why") + { + HandleLootWhyCommand(); + return; + } if (sub != "add") { + ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use"); ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing."); ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor."); @@ -1749,6 +1756,72 @@ public sealed partial class RynthAiPlugin // An add's own chat line comes from OnLootRuleAdded. } + private const int LootWhyChatLines = 10; + + /// + /// /ra loot why: the selected item's loot decision, from the looter itself (built-in keeps and + /// Keep # caps included), then, for a VTank profile, the rule that takes it and, for the rules + /// above it that came close, the first condition that failed and the value it read. The full + /// list goes to the log. An item without its ID says which rule waits for it and asks for it. + /// + private void HandleLootWhyCommand() + { + if (!Host.HasGetSelectedItemId) { ReplyFail("[RynthAi] loot why: this engine can't tell RynthAi the selected item."); return; } + uint selected = Host.GetSelectedItemId(); + if (selected == 0) { ReplyFail("[RynthAi] loot why: select an item first (on a corpse, the ground or in a pack), then /ra loot why."); return; } + WorldObject? item = _objectCache?[unchecked((int)selected)]; + if (item == null) { ReplyFail($"[RynthAi] loot why: item 0x{selected:X8} isn't known yet; select it again in a moment."); return; } + LegacyUiSettings? settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] loot why: settings aren't loaded yet (log in first)."); return; } + + bool hasId = !Host.HasHasAppraisalData || Host.HasAppraisalData(selected); + string idNote = hasId ? "identified" : "not identified yet"; + + bool taken = ClassifyLootItem(item, settings, preview: true, out string action, out _, out string ruleLabel, out string builtIn); + string looter = taken ? $"[{action}] {ruleLabel}" : "left"; + if (builtIn.Length > 0) looter += " (" + builtIn + ")"; + + if (TryLoadNativeLootProfile(out _, out _)) + { + ChatLine($"[RynthAi] Loot why: '{item.Name}' ({idNote}) -> {looter}. (Rule-by-rule detail is for VTank .utl profiles.)"); + return; + } + if (!TryLoadLootProfile(string.Empty, out VTankLootProfile profile, out string path)) + return; // it said why + + VTankLootContext ctx = new(Host, _playerId) { Cache = _objectCache }; + Loot.LootWhy.Result why = Loot.LootWhy.Explain(profile, item, ctx, hasId); + string file = System.IO.Path.GetFileName(path); + string rule = why.Index >= 0 ? $"rule {why.Index + 1} of {profile.Rules.Count} '{why.RuleName}'" : string.Empty; + string decision = why.Verdict switch + { + VTankLootVerdict.Match => $"{file}: {rule} [{why.Action}]", + VTankLootVerdict.NeedsId => $"{file}: {rule} needs the item's ID to decide", + _ => $"{file}: no rule matches", + }; + ChatLine($"[RynthAi] Loot why: '{item.Name}' ({idNote}) -> {looter}"); + ChatLine($"[RynthAi] {decision}"); + Host.Log($"[LootWhy] '{item.Name}' 0x{selected:X8} {idNote} -> {looter}; {decision}"); + if (why.Verdict == VTankLootVerdict.NeedsId && Host.HasRequestId && Host.RequestId(selected)) + ChatLine("[RynthAi] Asked for its ID; /ra loot why again once it's in."); + + if (why.NearMisses.Count == 0) + { + ChatLine("[RynthAi] No rule above it came close (each failed on its first condition)."); + return; + } + ChatLine($"[RynthAi] {why.NearMisses.Count} rule(s) above it came close; the first condition each failed:"); + for (int i = 0; i < why.NearMisses.Count; i++) + { + var m = why.NearMisses[i]; + string line = $"#{m.Index + 1} '{m.RuleName}': {m.Failed}"; + Host.Log("[LootWhy] " + line); + if (i < LootWhyChatLines) ChatLine("[RynthAi] " + line); + } + if (why.NearMisses.Count > LootWhyChatLines) + ChatLine($"[RynthAi] ... {why.NearMisses.Count - LootWhyChatLines} more in the log ([LootWhy] lines)."); + } + private bool TryLoadNativeLootProfile(out RynthCore.Loot.LootProfile profile, out string loadedPath) { string candidatePath = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"'); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs index 6255d8a..5393461 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -26,6 +26,8 @@ namespace RynthCore.Plugin.RynthAi; /// /ra iteminfo verbose on|off list every spell instead of Mag's filter /// /ra iteminfo click left|right|off print the selected item after a mouse click /// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner +/// /ra iteminfo loot on|off describe what the looter takes in its "Looted" line +/// /ra iteminfo loot salvage on|off salvage too (material and workmanship only) /// /ra iteminfo reset restore defaults /// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi). /// @@ -150,6 +152,19 @@ public sealed partial class RynthAiPlugin ReplyOk($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}"); return; + case "loot": + if (arg3.Equals("salvage", StringComparison.OrdinalIgnoreCase)) + { + if (ParseOnOff(arg4) is bool salvageOn) s.LootChatSalvage = salvageOn; + else if (arg4.Length > 0) { ReplyFail("[RynthAi] Usage: /ra iteminfo loot salvage on|off"); return; } + ReplyOk($"[RynthAi] Item info on loot, salvage: {OnOff(s.LootChatSalvage)}"); + return; + } + if (ParseOnOff(arg3) is bool lootOn) s.LootChat = lootOn; + else if (arg3.Length > 0) { ReplyFail("[RynthAi] Usage: /ra iteminfo loot on|off, or /ra iteminfo loot salvage on|off"); return; } + ReplyOk($"[RynthAi] Item info on loot: {OnOff(s.LootChat)} (salvage {OnOff(s.LootChatSalvage)})"); + return; + case "reset": s.ResetToDefaults(); ReplyOk("[RynthAi] Item info settings reset to defaults."); @@ -170,7 +185,7 @@ public sealed partial class RynthAiPlugin if (found != 0) { QueueItemInfo(unchecked((int)found), requestId: true); return; } ReplyFail($"[RynthAi] Item info: no \"{name}\" in your inventory."); } - ReplyFail("[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]"); + ReplyFail("[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|loot on|off|reset]"); } /// @@ -470,6 +485,32 @@ public sealed partial class RynthAiPlugin return string.Join("\n ", lines); } + /// + /// The "Looted" line for a pickup, described when the Item Info loot setting wants it + /// (), with its chat type; null for the plain line. Corpse loot builds it + /// when the pickup goes out (the item and its ID are surely there then), ground loot on arrival. + /// + private (string Line, int ChatType)? DescribeLootPickup(int itemId, string action, string name, string rule, + bool isSalvage, bool stackable, string where = "") + { + MagItemInfoSettings? s = ItemInfoSettings; + WorldObject? wo = _objectCache?[itemId]; + if (s == null || wo == null) return null; + LootChatLine.Detail detail = LootChatLine.DetailFor(s, action, isSalvage, stackable, wo.ObjectClass); + if (detail == LootChatLine.Detail.None) return null; + try + { + bool identified = !Host.HasHasAppraisalData || Host.HasAppraisalData(unchecked((uint)itemId)); + string line = LootChatLine.Format(detail, s, new CacheItemPropertySource(Host, wo), action, name, rule, where, identified); + return (line, LootChatLine.ChatTypeOf(s)); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.General, ex, $"loot line 0x{(uint)itemId:X8}"); + return null; + } + } + /// Item Info window "Test" button: sample line in the chosen chat type. private void TestItemInfoChatType(int chatType) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index 2cd379e..cf53700 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -197,8 +197,7 @@ public sealed partial class RynthAiPlugin _openedContainerAt = _chestCandidateSince != 0 ? _chestCandidateSince : now; _openedContainerInventoryObservedAt = _chestCandidateInvSeenAt; _lastLootActionAt = 0; - _corpseItemsEvaluated = 0; - _corpseItemsMatched = 0; + ResetLootTally(); _corpseIdsRequested = false; ResetCurrentLootItem(); _processedCorpseItems.Clear(); @@ -224,10 +223,11 @@ public sealed partial class RynthAiPlugin if (close) CloseCorpseContainer(chestId, why); - if (sayNothingMatched && _corpseItemsEvaluated > 0 && _corpseItemsMatched == 0) + if (sayNothingMatched) { - string chestName = _objectCache?[chestId]?.Name ?? $"0x{(uint)chestId:X8}"; - ChatLine($"[RynthAi] Nothing in {chestName} matches the loot profile."); + string chestName = _objectCache?[chestId]?.Name is { Length: > 0 } cn ? cn : "the chest"; + if (NothingLootedLine(chestName, chest: true) is { } nothingLine) + ChatLine(nothingLine); } LootDiag($"[RynthAi] Chest loot: done with chest 0x{(uint)chestId:X8} ({why}); not marked, so opening it again loots it again."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 6b387a6..9e2acb4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -304,8 +304,7 @@ public sealed partial class RynthAiPlugin _openedContainerAt = now; _openedContainerInventoryObservedAt = 0; _lastLootActionAt = 0; - _corpseItemsEvaluated = 0; - _corpseItemsMatched = 0; + ResetLootTally(); _corpseIdsRequested = false; ResetCurrentLootItem(); _processedCorpseItems.Clear(); @@ -325,7 +324,7 @@ public sealed partial class RynthAiPlugin } string note = !settings.IsMacroRunning ? " (the macro is off: this container only)" : !settings.EnableLooting ? " (Looting is off: this container only)" - : settings.BoostNavPriority ? " (Boost Nav Priority is on: this container only)" : ""; + : BoostNavHoldsLoot(settings) ? " (Boost Nav Priority is on: this container only)" : ""; LootDiag($"[RynthAi] LootThisCont: 0x{(uint)id:X8} '{name}' flagged{(already ? " (already open as the loot container)" : "")}."); ChatLine($"[RynthAi] LootThisCont: looting {name}{note}."); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 1043e7e..4701928 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -901,6 +901,27 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private long _combatEndedAt; private const long LootGraceMs = 2000; + /// + /// Fellowship-follow steers toward a live leader position and needs no route, so it counts + /// as nav work in its own right: without this, turning Follow on with no route loaded would + /// leave the arbiter's wantNav false and NavigationEngine.Tick would never do the following. + /// + private static bool IsFollowActive(LegacyUiSettings settings) + => (settings.FollowMode && settings.FollowTargetId != 0) + || (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow + && settings.CurrentRoute.FollowTargetName.Length > 0); + + /// + /// The arbiter's WantNav input: the macro runs, navigation is on, and there is a route (or a + /// follow) to run. Travelling back to your corpse (RynthNav walks): RynthAi's own route waits. + /// Also read by BoostNavHoldsLoot, so the looter stands down for Boost Nav Priority exactly + /// when the arbiter's BoostNav clause can give nav the tick. + /// + private bool NavWantsTick(LegacyUiSettings settings) + => settings.IsMacroRunning && settings.EnableNavigation + && ((settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0) || IsFollowActive(settings)) + && !OwnCorpseTravelHoldsNav; + /// /// Stop nav movement once, on the transition into a non-Navigating activity. /// Replaces the four _*PausedNav flags: each existed only to answer "have I @@ -1861,20 +1882,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase bool wantLoot = HasLootWork(settings, nowMs); _lastWantLoot = wantLoot; bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy; - bool routeLoaded = settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0; - - // Fellowship-follow steers toward a live leader position and - // needs no route, so it counts as nav work in its own right — - // without this, turning Follow on with no route loaded would - // leave wantNav false and NavigationEngine.Tick would never be - // called to do the following. - bool followActive = (settings.FollowMode && settings.FollowTargetId != 0) - || (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow - && settings.CurrentRoute.FollowTargetName.Length > 0); - // Travelling back to your corpse (RynthNav walks): RynthAi's own route waits. - bool wantNav = settings.IsMacroRunning && settings.EnableNavigation - && (routeLoaded || followActive) - && !OwnCorpseTravelHoldsNav; + bool followActive = IsFollowActive(settings); + bool wantNav = NavWantsTick(settings); // Loot starvation: a lootable corpse in range has waited LootStarveMs behind // combat and no monster is within LootStarveCloseYards. A busy spawn always // has a monster inside MonsterRange, so without this corpses waited until diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/Quantity.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/Quantity.cs index 838d97b..ee08664 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Model/Quantity.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/Quantity.cs @@ -19,10 +19,21 @@ // can pay for, and your packs and burden take (VendorQuote.MaxBuy). // box a typed number stays as typed (1 .. MaxAmount); "max" and "half" // are of what is selected: the whole stack, or the most you can buy. +// +// A server's bank (2026-10-31): some servers pay a pyreal vendor from the +// bank when the packs are short. The active server's plugin says so in its +// profile values (VendorBank.Read; RynthDefective names no server): +// no bank the pack's pyreals, as before; +// a bank that's read pack + bank pay ("price 1,200; pack 300 + bank 5,000"), +// and "max" counts both; +// a bank that isn't money isn't held against a buy: it goes, and the +// server decides ("the server's bank may cover it"); +// "max" is the vendor's stock, your room and burden. // ============================================================================ using System; using System.Globalization; +using RynthCore.Plugin.Shared; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthDefective.Model; @@ -160,13 +171,42 @@ internal static class QuantityRules public static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture); } +/// +/// The active server's bank, as its plugin says in its profile values: whether it pays a pyreal vendor +/// what the packs are short of (RynthServerProfile.ValueVendorBank), and the pyreals it can add +/// (ValueVendorBankPyreals; -1 = the balance can't be read). : no bank (or no server +/// plugin saying so), and a buy counts the pack only. +/// +internal readonly record struct VendorBank(bool Pays, long Pyreals = -1) +{ + /// The most a bank is taken to hold (anything above reads as this): far past any server's, and exact in the profile's numbers. + public const long MaxPyreals = 1_000_000_000_000_000; + + public static readonly VendorBank None = new(false); + + /// The bank's balance is read. + public bool Known => Pays && Pyreals >= 0; + + /// A profile JSON's bank values; without "vendorBank" above 0 (or for unusable text). Pure. + public static VendorBank Read(string? profileJson) + { + double pays = ServerProfileView.Value(profileJson, RynthServerProfile.ValueVendorBank, 0); + if (!(pays > 0)) return None; + double p = ServerProfileView.Value(profileJson, RynthServerProfile.ValueVendorBankPyreals, -1); + long pyreals = p >= 0 ? (long)Math.Floor(Math.Min(p, MaxPyreals)) : -1; + return new VendorBank(true, pyreals); + } +} + /// /// One vendor item and what the player has: the box's price, its "max" and why a buy can't go. The /// rules are ACE's, as the engine's VendorTrade.EstimateBuy applies them (the engine checks again /// before it sends): a stackable item comes in stacks of MaxStack, each priced on its own /// (max(1, ceil(value x rate - 0.1)), promissory notes at 1.15), anything else one per slot; a /// limited listing (usually what another player sold, handed over whole) costs at least the whole -/// listing. Unknown funds, slots or burden (-1) aren't held against the buy. +/// listing. Unknown funds, slots or burden (-1) aren't held against the buy. A server's bank that +/// pays pyreal vendors () adds its balance to the pack's, or, when the balance +/// can't be read, leaves the money to the server. /// internal sealed record VendorQuote { @@ -193,14 +233,29 @@ internal sealed record VendorQuote public int FreeItemSlots { get; init; } = -1; public int FreeContainerSlots { get; init; } = -1; public long FreeBurden { get; init; } = -1; + /// The server's bank pays this (pyreal) vendor what the pack is short of. + public bool BankPays { get; init; } + /// The pyreals the bank can add (with ); -1 = its balance can't be read. + public long BankFunds { get; init; } = -1; public bool Stackable => MaxStack > 0; - /// From the engine's vendor snapshot (API v67) and what the player has. - public static VendorQuote From(VendorInfo info, VendorItem item, int freeItemSlots, int freeContainerSlots, long freeBurden) + /// A bank pays, and its balance is read: pack + bank count. + public bool BankKnown => BankPays && BankFunds >= 0; + + /// A bank pays, but its balance can't be read: the server decides about the money. + public bool BankUnknown => BankPays && BankFunds < 0; + + /// What a buy may spend: the pack, plus a bank that's read; -1 = money isn't held against a buy (unknown, or an unread bank). + public long Spendable => Funds < 0 || BankUnknown ? -1 : BankKnown ? Funds + Math.Min(BankFunds, VendorBank.MaxPyreals) : Funds; + + /// From the engine's vendor snapshot (API v67), what the player has, and the server's bank (pyreal vendors only). + public static VendorQuote From(VendorInfo info, VendorItem item, int freeItemSlots, int freeContainerSlots, long freeBurden, + VendorBank bank = default) { int stack = Math.Max(1, item.StackSize); bool alt = info.UsesAltCurrency; + bool bankPays = !alt && bank.Pays; return new VendorQuote { Name = item.Name, @@ -220,6 +275,8 @@ internal sealed record VendorQuote FreeItemSlots = freeItemSlots, FreeContainerSlots = freeContainerSlots, FreeBurden = freeBurden, + BankPays = bankPays, + BankFunds = bankPays ? bank.Pyreals : -1, }; } @@ -268,7 +325,8 @@ internal sealed record VendorQuote private bool Fits(int n) { Estimate(n, out long cost, out long slots, out long burden); - if (Funds >= 0 && cost > Funds) return false; + long spend = Spendable; + if (spend >= 0 && cost > spend) return false; if (FreeSlots >= 0 && slots > FreeSlots) return false; if (FreeBurden >= 0 && burden > FreeBurden) return false; return true; @@ -278,11 +336,12 @@ internal sealed record VendorQuote /// The most you can buy now: what the vendor has, you can pay for, and your packs and burden take /// (cost, slots and burden only grow with the count, so a halving search finds it). With nothing /// known to limit an unlimited item, one full stack (one, for an item that doesn't stack). 0 = not even one. + /// With a bank: pack + bank pay when the bank is read; an unread bank leaves only stock, room and burden. /// public int MaxBuy() { int cap = Unlimited ? QuantityRules.MaxAmount : Math.Min(Stock, QuantityRules.MaxAmount); - if (Unlimited && Funds < 0 && FreeSlots < 0 && FreeBurden < 0) cap = Stackable ? Math.Max(1, MaxStack) : 1; + if (Unlimited && Spendable < 0 && FreeSlots < 0 && FreeBurden < 0) cap = Stackable ? Math.Max(1, MaxStack) : 1; if (cap < 1 || !Fits(1)) return 0; int lo = 1, hi = cap; while (lo < hi) @@ -302,8 +361,11 @@ internal sealed record VendorQuote return Stock < 1 ? $"The vendor has no {Name} left." : $"The vendor has only {QuantityRules.N(Stock)} {Name}."; Estimate(n, out long cost, out long slots, out long burden); string what = $"{QuantityRules.N(n)} {Name}"; - if (Funds >= 0 && cost > Funds) - return $"Not enough {Currency}: {what} cost {QuantityRules.N(cost)}, you have {QuantityRules.N(Funds)}{CanBuy()}."; + long spend = Spendable; + if (spend >= 0 && cost > spend) + return BankKnown + ? $"Not enough {Currency}: {what} cost {QuantityRules.N(cost)}, you have {QuantityRules.N(Funds)} in your pack + {QuantityRules.N(BankFunds)} in the bank{CanBuy()}." + : $"Not enough {Currency}: {what} cost {QuantityRules.N(cost)}, you have {QuantityRules.N(Funds)}{CanBuy()}."; int free = FreeSlots; if (free >= 0 && slots > free) { @@ -324,12 +386,35 @@ internal sealed record VendorQuote return max >= 1 ? $" (you can buy {QuantityRules.N(max)})" : string.Empty; } - /// The price line under the Buy button: "300 pyreals · you have 1,250". + /// + /// The price line beside the Buy button: "300 pyreals · you have 1,250"; with a bank that's read + /// "price 1,200; pack 300 + bank 5,000"; with one that isn't "1,200 pyreals · pack 300 + the bank". + /// public string PriceLine(int n) { - string cost = n >= 1 ? QuantityRules.N(Cost(n)) + " " + Currency : "-"; + string price = n >= 1 ? QuantityRules.N(Cost(n)) : "-"; + if (Funds >= 0 && BankKnown) return $"price {price}; pack {QuantityRules.N(Funds)} + bank {QuantityRules.N(BankFunds)}"; + string cost = n >= 1 ? price + " " + Currency : "-"; + if (Funds >= 0 && BankUnknown) return $"{cost} · pack {QuantityRules.N(Funds)} + the bank"; return Funds >= 0 ? $"{cost} · you have {QuantityRules.N(Funds)}" : cost; } + + /// + /// What the bank does for buying , when the pack alone is short (null otherwise, + /// and always without a bank): the box's one-line note. + /// + public string? BankNote(int n) + { + if (!BankPays || Funds < 0 || n < 1) return null; + long cost = Cost(n); + if (cost <= Funds) return null; + if (BankUnknown) + return $"Your pack has {QuantityRules.N(Funds)} of the {QuantityRules.N(cost)} {Currency}: the server's bank may cover it (the server decides)."; + return cost <= Spendable ? $"The bank pays the {QuantityRules.N(cost - Funds)} {Currency} your pack is short." : null; + } + + /// What "max" counts, when that isn't plain: "" without a bank, or with one that's read. + public string MaxNote => BankUnknown ? "max counts the vendor's stock, your pack space and burden only (the bank's balance can't be read)" : string.Empty; } /// What the quantity box's actions say (chat and the Selection window). Pure. @@ -402,5 +487,23 @@ internal static class QtyReplies return $"The vendor didn't sell it: {m}."; } + /// + /// A buy's refusal when the server's bank was to pay part of it (): + /// RynthCore's own money check ("costs ..., you have ...") counts only the pyreals the game shows, + /// so it says that and what to do; anything else as . + /// + public static string BuyRefusal(string? message, bool bankMayPay) + { + string m = (message ?? string.Empty).Trim(); + if (bankMayPay && m.StartsWith("costs ", StringComparison.Ordinal)) + return $"RynthCore didn't send it: it {m}. RynthCore counts the pyreals the game shows, and the bank's aren't in them: take the rest out of the bank, then buy again."; + return VendorRefusal(m); + } + + /// The server answered a buy without selling it. + public static string NotSold(int n, string name, bool bankMayPay, long cost, string currency) => bankMayPay + ? $"The vendor didn't sell {QuantityRules.N(n)} {name}: the server said no (your pack and the bank may not cover {QuantityRules.N(cost)} {currency}, or there's no room)." + : $"The vendor didn't sell {QuantityRules.N(n)} {name}: the server said no (money, room, or too busy)."; + private static string Cap(string s) => s.Length == 0 ? s : char.ToUpperInvariant(s[0]) + s[1..]; } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QtyWorld.cs b/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QtyWorld.cs index 23efe46..f744397 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QtyWorld.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QtyWorld.cs @@ -6,13 +6,16 @@ // // Every call is behind its Has* check: splitting (SplitStackInternal, as old // as the plugin API), giving with a count (GiveObjectTo, v62), vendor trading -// (v67), the server's refusals (v70) and the pack column's order (v80) are -// each used only where the engine has them. Nothing here needs more than the -// live release's API 92, and the Selection window itself needs v90. +// (v67), the server's refusals (v70), the pack column's order (v80) and the +// active server's list (v86, for its plugin's bank values) are each used +// only where the engine has them. Nothing here needs more than the live +// release's API 92, and the Selection window itself needs v90. // ============================================================================ using System; using System.Collections.Generic; +using RynthCore.Plugin.RynthDefective.Model; +using RynthCore.Plugin.Shared; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthDefective.Quantity; @@ -80,6 +83,8 @@ internal interface IQtyWorld int FreeContainerSlots(); /// Burden you can still carry (three times your capacity, as ACE); -1 = unknown. long FreeBurden(); + /// The active server's bank, as its plugin says (VendorBank.None: none, or nobody says). + VendorBank Bank(); } /// The engine host's side (RynthCoreHost). Plugin pump thread only. @@ -97,9 +102,21 @@ internal sealed class HostQtyWorld : IQtyWorld private uint[] _order = new uint[16]; private uint _vendorId, _vendorGeneration; private VendorItem[] _vendorItems = Array.Empty(); + // The active server and its plugin's profile (v86 + "RynthServer.Profile"), for its bank values. + private readonly ServerStateClient _server = new(); + private int _bankRevision = -1; + private VendorBank _bank = VendorBank.None; public HostQtyWorld(RynthCoreHost host) => _h = host; + /// Login or logout: the next server may be another (its bank read afresh). + public void Reset() + { + _server.Clear(); + _bankRevision = -1; + _bank = VendorBank.None; + } + public long NowMs => Environment.TickCount64; public uint PlayerId => _h.HasGetPlayerId ? _h.GetPlayerId() : 0; public uint SelectedId => _h.HasGetSelectedItemId ? _h.GetSelectedItemId() : 0; @@ -249,4 +266,20 @@ internal sealed class HostQtyWorld : IQtyWorld if (carried < 0 || cap <= 0) return -1; // unknown: the engine checks with its own reading return Math.Max(0, 3L * cap - carried); } + + /// + /// The active server's plugin's "vendorBank" / "vendorBankPyreals" values (polled every 2 s; read + /// again only when the server or its profile changed). Before v86, or with no server plugin: none. + /// + public VendorBank Bank() + { + if (!_h.HasGetServerStateJson) return VendorBank.None; + _server.Poll(_h, NowMs); + if (_server.Revision != _bankRevision) + { + _bankRevision = _server.Revision; + _bank = VendorBank.Read(_server.ProfileJson); + } + return _bank; + } } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QuantityController.cs b/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QuantityController.cs index 635c672..ef73d94 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QuantityController.cs +++ b/Plugins/RynthCore.Plugin.RynthDefective/Quantity/QuantityController.cs @@ -9,6 +9,9 @@ // open) or NPC you selected last // an item in a vendor's list Buy N, with the price, your pyreals, the room // in your packs and your burden checked first +// (a server's bank that pays vendors counts +// too, or leaves the money to the server when +// its balance can't be read: VendorQuote) // // The Selection window shows the box under what is selected (QuantityRow); // /rdef qty, split, give and buy do the same from chat, hotkeys and metas. @@ -179,7 +182,7 @@ internal sealed class QuantityController if (p.Free < 0) { free = -1; break; } free += p.Free; } - return VendorQuote.From(info, item, free, w.FreeContainerSlots(), w.FreeBurden()); + return VendorQuote.From(info, item, free, w.FreeContainerSlots(), w.FreeBurden(), w.Bank()); } /// @@ -256,7 +259,8 @@ internal sealed class QuantityController private string About(QtySubject s) => s.Mode switch { QtyMode.Stack => $" (the selected {s.Name}: a stack of {QuantityRules.N(s.Stack)}; a split takes up to {QuantityRules.N(s.Stack - 1)})", - QtyMode.Vendor when s.Quote != null => $" (the vendor's {s.Name}: {s.Quote.PriceLine(Value)}; you can buy {QuantityRules.N(s.MaxBuy)})", + QtyMode.Vendor when s.Quote != null => $" (the vendor's {s.Name}: {s.Quote.PriceLine(Value)}; you can buy {QuantityRules.N(s.MaxBuy)}" + + (s.Quote.MaxNote.Length > 0 ? "; " + s.Quote.MaxNote : string.Empty) + ")", _ => string.Empty, }; @@ -401,16 +405,18 @@ internal sealed class QuantityController string? refusal = q.Refusal(n); if (refusal != null) { Say(w, false, refusal); return; } + // The bank is to pay what the pack is short of (read or not): the answers say so. + bool bankMayPay = q.BankPays && q.Funds >= 0 && q.Cost(n) > q.Funds; uint request = w.Buy(info.VendorId, item.ObjectId, n); if (request == 0) { - Say(w, false, QtyReplies.VendorRefusal(w.TryGetTradeStatus(out VendorTradeStatus st) ? st.Message : null)); + Say(w, false, QtyReplies.BuyRefusal(w.TryGetTradeStatus(out VendorTradeStatus st) ? st.Message : null, bankMayPay)); return; } _pending = new Pending { Kind = PendingKind.Buy, Id = item.ObjectId, Name = item.Name, N = n, RequestId = request, - Cost = q.Cost(n), Currency = q.Currency, AtMs = w.NowMs, + Cost = q.Cost(n), Currency = q.Currency, AtMs = w.NowMs, BankMayPay = bankMayPay, }; } @@ -462,6 +468,8 @@ internal sealed class QuantityController public uint RequestId; public long Cost; public string Currency = string.Empty; + /// Buy: the server's bank was to pay what the pack is short of. + public bool BankMayPay; } /// Plugin tick: the give target, and the answer to the action in flight. @@ -502,7 +510,7 @@ internal sealed class QuantityController { if (s.RequestId == p.RequestId) { - if (s.State == VendorTradeState.Refused) { Finish(w, false, QtyReplies.VendorRefusal(s.Message)); return; } + if (s.State == VendorTradeState.Refused) { Finish(w, false, QtyReplies.BuyRefusal(s.Message, p.BankMayPay)); return; } if (s.State == VendorTradeState.Done) { if (s.Result == VendorTradeResult.Accepted) @@ -510,7 +518,7 @@ internal sealed class QuantityController else if (s.Result == VendorTradeResult.TimedOut) Finish(w, false, $"No answer from the vendor about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again."); else - Finish(w, false, $"The vendor didn't sell {QuantityRules.N(p.N)} {p.Name}: the server said no (money, room, or too busy)."); + Finish(w, false, QtyReplies.NotSold(p.N, p.Name, p.BankMayPay, p.Cost, p.Currency)); return; } } diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj index c853800..a6a9ec9 100644 --- a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj +++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj @@ -44,6 +44,11 @@ + + + + + + + diff --git a/Tools/RynthNet.Tests/LookTests.cs b/Tools/RynthNet.Tests/LookTests.cs new file mode 100644 index 0000000..da46f07 --- /dev/null +++ b/Tools/RynthNet.Tests/LookTests.cs @@ -0,0 +1,166 @@ +using System.Text.Json; +using RynthCore.Plugin.RynthNet; +using RynthCore.Plugin.RynthNet.Characters; + +namespace RynthNet.Tests; + +// The Characters window's two looks (2026-10-31): minimal (one line per character, frameless) and +// full (every column), the low-health colours, the status dot, the minimal line's layout, /rn view, +// the frameless manifest, and the choice kept per character in settings.json. +internal static partial class Program +{ + private static void LookChecks() + { + HealthThresholds(); + StatusDots(); + MinimalLayout(); + ViewNames(); + ViewCommand(); + FramelessManifest(); + ViewPersistence(); + } + + private static CharacterRow Row(float hp, CharStateKind kind = CharStateKind.Idle, bool vitals = true) => new() + { + Name = "Char One", HasVitals = vitals, Hp = new CharVital(hp, "x"), StateKind = kind, + }; + + private static void HealthThresholds() + { + Check(CharactersLook.LowHp == 0.5f && CharactersLook.CriticalHp == 0.25f, "low at half health, critical at a quarter"); + Check(CharactersLook.Hp(1f) == HpWarn.Ok && CharactersLook.Hp(0.51f) == HpWarn.Ok, "over half: fine (the text colour)"); + Check(CharactersLook.Hp(0.5f) == HpWarn.Low && CharactersLook.Hp(0.26f) == HpWarn.Low, "half or less: low (amber)"); + Check(CharactersLook.Hp(0.25f) == HpWarn.Critical && CharactersLook.Hp(0.01f) == HpWarn.Critical, "a quarter or less: critical (red)"); + Check(CharactersLook.Hp(0f) == HpWarn.Dead, "no health: dead (red)"); + Check(CharactersLook.Hp(Row(0.9f, CharStateKind.Dead)) == HpWarn.Dead, "a dead state is dead, whatever the last vitals said"); + Check(CharactersLook.Hp(Row(0.3f)) == HpWarn.Low && CharactersLook.Hp(Row(0.2f)) == HpWarn.Critical, "a row's health share"); + Check(CharactersLook.Hp(Row(0f, vitals: false)) == HpWarn.Unknown, "no vitals yet: unknown, not dead"); + } + + private static void StatusDots() + { + Check(CharactersLook.Dot(new CharacterRow { LoggedOut = true, StateKind = CharStateKind.LoggedOut }) == CharDot.Off, "logged out: an empty ring"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.NoStatus }) == CharDot.Off, "no status yet: an empty ring"); + Check(CharactersLook.Dot(new CharacterRow { IsSelf = true }) == CharDot.Self, "this client"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Dead, Stale = true }) == CharDot.Dead, "dead before stale"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Botting, Stale = true }) == CharDot.Stale, "stale before what the bot was doing"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Botting }) == CharDot.Botting, "botting"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Fighting }) == CharDot.Fighting, "botting: fighting"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Portal }) == CharDot.Portal, "portal space"); + Check(CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.Idle }) == CharDot.Idle + && CharactersLook.Dot(new CharacterRow { StateKind = CharStateKind.CombatMode }) == CharDot.Idle, "idle, in or out of a stance"); + } + + private static void MinimalLayout() + { + // dot 12, gap 6, bars 3 x 24 + 2 x 2 = 76, arrow 14: everything for an 80 px name and a 40 px distance is 234 px. + MinimalLine all = CharactersLook.Minimal(300, 80, 40); + Check(all.Bars && all.Distance && all.NameWidth == 80 && all.BarWidth == 24, "300 px: name, bars, arrow and distance"); + Check(Math.Abs(all.Width(1f, 40) - 234) < 0.01f, $"the whole line is 234 px (got {all.Width(1f, 40)})"); + Check(CharactersLook.Minimal(234, 80, 40).Distance && !CharactersLook.Minimal(233, 80, 40).Distance, "the distance needs the whole line"); + MinimalLine noDist = CharactersLook.Minimal(200, 80, 40); + Check(noDist.Bars && !noDist.Distance && noDist.NameWidth == 80, "200 px: name and bars, no distance"); + MinimalLine squeezed = CharactersLook.Minimal(150, 80, 40); + Check(squeezed.Bars && squeezed.NameWidth == 56 && squeezed.BarWidth == 24, $"150 px: the name gives way first ({squeezed.NameWidth})"); + MinimalLine thin = CharactersLook.Minimal(100, 80, 40); + Check(thin.Bars && thin.NameWidth == 30 && thin.BarWidth == 16, $"100 px: the name at its least, then the bars narrow ({thin.BarWidth})"); + MinimalLine none = CharactersLook.Minimal(60, 80, 40); + Check(!none.Bars && !none.Distance && none.NameWidth == 48, "60 px: just the dot and the name"); + Check(!CharactersLook.Minimal(1000, 80, 0).Distance, "no row has a distance: no distance column"); + MinimalLine big = CharactersLook.Minimal(600, 160, 80, k: 2f); + Check(big.Bars && big.Distance && big.BarWidth == 48, "the sizes grow with the text size"); + Check(CharactersLook.MinimalHeight(0) == 20 && CharactersLook.MinimalHeight(3) == 52 && CharactersLook.MinimalHeight(3, 1.5f) == 78, + "the window asks for one line per character (one for the status when there are none)"); + } + + private static void ViewNames() + { + Check(CharactersLook.Name(CharactersViewMode.Minimal) == "minimal" && CharactersLook.Name(CharactersViewMode.Full) == "full", "names"); + foreach (string s in new[] { "minimal", "MIN", "compact", "bare" }) + Check(CharactersLook.TryParse(s, out CharactersViewMode m) && m == CharactersViewMode.Minimal, $"'{s}' is minimal"); + foreach (string s in new[] { "full", "Edit", "framed" }) + Check(CharactersLook.TryParse(s, out CharactersViewMode m) && m == CharactersViewMode.Full, $"'{s}' is full"); + Check(!CharactersLook.TryParse("huge", out _) && !CharactersLook.TryParse(null, out _), "anything else isn't a view"); + Check(CharactersLook.FromSetting(null) == CharactersViewMode.Minimal && CharactersLook.FromSetting("weird") == CharactersViewMode.Minimal + && CharactersLook.FromSetting("full") == CharactersViewMode.Full, "the setting: minimal unless it says full"); + } + + private static void ViewCommand() + { + var (min, full) = (CharactersViewMode.Minimal, CharactersViewMode.Full); + ViewAnswer a = CharactersLook.Command("", min, loggedIn: false); + Check(a.Ok && !a.Changed && a.Next == min && a.Reply.StartsWith("the Characters window is in the minimal view", StringComparison.Ordinal), + "/rn view alone: the view now (logged in or not): " + a.Reply); + a = CharactersLook.Command("full", min, true); + Check(a.Ok && a.Changed && a.Next == full && a.Reply.StartsWith("the Characters window now shows the full view", StringComparison.Ordinal), "/rn view full: " + a.Reply); + a = CharactersLook.Command("FULL", full, true); + Check(a.Ok && !a.Changed && a.Reply.StartsWith("the Characters window is already in the full view", StringComparison.Ordinal), "already full: " + a.Reply); + Check(CharactersLook.Command("toggle", full, true).Next == min && CharactersLook.Command("toggle", min, true).Next == full, "toggle"); + Check(CharactersLook.Command("minimal", full, true).Reply.Contains("/rn view full", StringComparison.Ordinal), "the minimal reply says how to get the full view back"); + a = CharactersLook.Command("full", min, loggedIn: false); + Check(!a.Ok && a.Reply.StartsWith("log in first", StringComparison.Ordinal), "before login: why (it is kept per character)"); + a = CharactersLook.Command("huge", min, true); + Check(!a.Ok && a.Reply == CharactersLook.Usage && a.Reply.StartsWith("usage: /rn view", StringComparison.Ordinal), "a wrong view: the usage"); + } + + private static void FramelessManifest() + { + Check(CharactersManifest.For(false) == CharactersManifest.Json && CharactersManifest.For(true) == CharactersManifest.FramelessJson, + "the engine framed manifest without frameless windows, the frameless one with them"); + using JsonDocument doc = JsonDocument.Parse(CharactersManifest.FramelessJson); + JsonElement w = doc.RootElement.GetProperty("windows")[0]; + Check(w.GetProperty("title").GetString() == CharactersManifest.Title && w.GetProperty("surface").GetString() == CharactersManifest.Surface, + "the same title (players' saved place) and surface"); + Check(w.GetProperty("chrome").GetString() == "none" && w.GetProperty("fitHeight").GetBoolean(), "frameless, as tall as what it shows"); + Check(w.GetProperty("bar").GetBoolean() && w.GetProperty("minWidth").GetInt32() <= 200, "a bar button; narrow enough for the minimal line"); + using JsonDocument old = JsonDocument.Parse(CharactersManifest.Json); + Check(!old.RootElement.GetProperty("windows")[0].TryGetProperty("chrome", out _), "the framed one has no chrome key (older engines)"); + } + + private static void ViewPersistence() + { + string dir = Path.Combine(AppContext.BaseDirectory, "settings-test-" + Environment.ProcessId); + string? before = Environment.GetEnvironmentVariable("RYNTHNET_DIR"); + Environment.SetEnvironmentVariable("RYNTHNET_DIR", dir); + try + { + Directory.CreateDirectory(dir); + if (File.Exists(RynthNetSettings.FilePath)) File.Delete(RynthNetSettings.FilePath); + Check(RynthNetSettings.FilePath.StartsWith(dir, StringComparison.OrdinalIgnoreCase), "the test's settings file is under its own bin folder"); + + RynthNetSettings fresh = RynthNetSettings.Load(out string? err); + Check(err == null && fresh.ViewFor("TestWorld|Char One") == CharactersViewMode.Minimal, "nothing saved: minimal (the default)"); + + const string a = "TestWorld|Char One", b = "TestWorld|Char Two"; + Check(RynthNetSettings.Update(s => s.Character(a).View = CharactersLook.Name(CharactersViewMode.Full), out _, out err), "saved: " + err); + RynthNetSettings back = RynthNetSettings.Load(out err); + Check(back.ViewFor(a) == CharactersViewMode.Full, "the full view comes back for that character"); + Check(back.ViewFor(b) == CharactersViewMode.Minimal, "another character keeps the default"); + string text = File.ReadAllText(RynthNetSettings.FilePath); + Check(text.Contains("\"view\": \"full\"", StringComparison.Ordinal), "written as \"view\": \"full\" under the character"); + + // Another client's change (tags) on top keeps the view, and the view keeps the tags. + Check(RynthNetSettings.Update(s => s.Character(a).Tags.Add("heal"), out _, out _), "a tag saved alongside"); + back = RynthNetSettings.Load(out _); + Check(back.ViewFor(a) == CharactersViewMode.Full && back.TagsFor(a).Contains("heal"), "the view and the tags live together"); + + // Back to minimal: saved as such; an entry with nothing left is dropped. + Check(RynthNetSettings.Update(s => { s.Character(b).View = "minimal"; s.Character(a).Tags.Clear(); s.Character(a).View = null; }, out _, out _), "minimal saved"); + back = RynthNetSettings.Load(out _); + Check(back.ViewFor(b) == CharactersViewMode.Minimal && back.Characters.ContainsKey(b), "minimal is kept when chosen"); + Check(!back.Characters.ContainsKey(a), "a character with no tags, policy or view isn't written"); + + // A hand-edited file with a view the plugin doesn't know: the default, not an error. + File.WriteAllText(RynthNetSettings.FilePath, "{\"characters\":{\"TestWorld|Char One\":{\"tags\":[],\"view\":\"sideways\"}}}"); + back = RynthNetSettings.Load(out err); + Check(err == null && back.ViewFor(a) == CharactersViewMode.Minimal && back.Characters[a].View == null, "an unknown view: minimal"); + File.WriteAllText(RynthNetSettings.FilePath, "{\"characters\":{\"TestWorld|Char One\":{\"view\":\"FULL\"}}}"); + Check(RynthNetSettings.Load(out _).ViewFor(a) == CharactersViewMode.Full, "any case"); + } + finally + { + Environment.SetEnvironmentVariable("RYNTHNET_DIR", before); + try { Directory.Delete(dir, recursive: true); } catch { } // the test's own output, under bin + } + } +} diff --git a/Tools/RynthNet.Tests/Program.cs b/Tools/RynthNet.Tests/Program.cs index b67c677..15c9c41 100644 --- a/Tools/RynthNet.Tests/Program.cs +++ b/Tools/RynthNet.Tests/Program.cs @@ -29,6 +29,7 @@ internal static partial class Program Vitals(); WindowChecks(); Replies(); + LookChecks(); Console.WriteLine($"{_checks} checks, {_failed} failed"); return _failed == 0 ? 0 : 1; diff --git a/Tools/RynthNet.Tests/RynthNet.Tests.csproj b/Tools/RynthNet.Tests/RynthNet.Tests.csproj index 85067b6..9e4715b 100644 --- a/Tools/RynthNet.Tests/RynthNet.Tests.csproj +++ b/Tools/RynthNet.Tests/RynthNet.Tests.csproj @@ -7,7 +7,10 @@ built from a fake game (CharactersRows.cs), the Atlas names (AtlasNames.cs), the manifest RynthCore hosts the window from (CharactersManifest.cs), and Shared\RynthUi\RynthIcons.cs against the engine's baked icons (the sibling RynthCore's ImGui\PhosphorIcons.cs, when there). - The window itself draws with ImGui and isn't compiled here. + The window's looks (Characters\CharactersLook.cs, 2026-10-31): the minimal line's layout, the + low-health colours, the status dot, /rn view, and the choice kept per character in + settings.json (RynthNetSettings.cs, with RYNTHNET_DIR pointed at a folder under this program's + bin, never C:\Games). The window itself draws with ImGui and isn't compiled here. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -25,6 +28,10 @@ + + + +