Snapshot for release 2026.10.31.2 (internal 4a0710c)
This commit is contained in:
parent
76aca938b6
commit
d54613aa63
50 changed files with 5824 additions and 179 deletions
|
|
@ -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
|
||||
{
|
||||
/// <summary>A monster inside Monster Range the last scan left out, and why.</summary>
|
||||
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<PassedOverMonster> _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<int, string> _passedOverLogged = new();
|
||||
|
||||
/// <summary>How far past Monster Range the lock line still looks for a higher priority.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Tests: the LOS verdict per monster instead of the ray test (true = blocked).</summary>
|
||||
internal Func<int, bool>? LosBlockedOverride { get; set; }
|
||||
|
||||
private void NotePassedOver(int id, double distance, string why)
|
||||
=> _passedOver.Add(new PassedOverMonster { Id = id, Distance = distance, Why = why });
|
||||
|
||||
/// <summary>
|
||||
/// The best monster of a higher Priority than <paramref name="priority"/> 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 <see cref="PassedOverBeyondRangeM"/> past Monster Range.
|
||||
/// The second half walks the landscape, so it is for the lock line only (a lock is rare).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new lock: the lock line names what it passed over; the per-lock log starts over.</summary>
|
||||
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}]";
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<int> _corpseMatchedIds = new(); // a loot rule approved it for pickup
|
||||
private readonly HashSet<int> _corpseCappedIds = new(); // it matched, left at its Keep # / keep count
|
||||
private int _corpseItemsLooted; // pickups confirmed (the only "looted")
|
||||
|
||||
/// <summary>A new corpse or chest session: its tally starts over.</summary>
|
||||
private void ResetLootTally()
|
||||
{
|
||||
_corpseItemsEvaluated = 0;
|
||||
_corpseMatchedIds.Clear();
|
||||
_corpseCappedIds.Clear();
|
||||
_corpseItemsLooted = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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}).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -2670,6 +2841,7 @@ public sealed partial class RynthAiPlugin
|
|||
/// where most kills leave nothing to wait for).</summary>
|
||||
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<int, long> _corpseItemIdReaskedAt = new();
|
||||
|
||||
/// <summary>A held corpse item's ID is late: ask again, at most every CorpseIdReaskMs.</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>ItemNeedsAppraisalForLoot's answer per item for a VTank profile, cleared with each corpse open.</summary>
|
||||
private readonly Dictionary<int, (bool Needs, AcObjectClass Class, string Name)> _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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
86
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs
Normal file
86
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/LootChatLine.cs
Normal file
|
|
@ -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 [<action>] <name>": 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
|
||||
{
|
||||
/// <summary>How much of an item a loot line describes.</summary>
|
||||
public enum Detail
|
||||
{
|
||||
/// <summary>The plain line: action and name.</summary>
|
||||
None,
|
||||
/// <summary>Salvage: the rule, material and workmanship.</summary>
|
||||
Salvage,
|
||||
/// <summary>The rule and the Mag-style fields (the Item Info field settings applied).</summary>
|
||||
Full,
|
||||
}
|
||||
|
||||
/// <summary>The line every pickup printed before, and still prints when it isn't described.</summary>
|
||||
public static string Plain(string action, string name, string where = "") =>
|
||||
$"[RynthAi] Looted [{action}] {name}" + (where.Length > 0 ? $" ({where})" : string.Empty);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Chat type of a described line.</summary>
|
||||
public static int ChatTypeOf(MagItemInfoSettings s) =>
|
||||
s.LootChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.LootChatType;
|
||||
|
||||
/// <summary>
|
||||
/// One line for one pickup. <paramref name="where"/> is "" for a corpse or chest, "ground" for
|
||||
/// ground loot; <paramref name="identified"/> false adds "not IDed" (the stats may be short).
|
||||
/// </summary>
|
||||
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<string>(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();
|
||||
}
|
||||
}
|
||||
|
|
@ -87,6 +87,10 @@ internal sealed class MagItemDescription
|
|||
{
|
||||
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
|
||||
public string Title = string.Empty;
|
||||
/// <summary>The material name ("Gold"), or "" when none or hidden; set even when the title leaves it out.</summary>
|
||||
public string Material = string.Empty;
|
||||
/// <summary>The title's "(DamageType Mastery)" text without the brackets, or "".</summary>
|
||||
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();
|
||||
|
||||
|
|
|
|||
|
|
@ -53,8 +53,8 @@ public sealed class MagItemInfoSettings
|
|||
public const int SameAsHeader = -1;
|
||||
|
||||
// ── When to print ────────────────────────────────────────────────────────
|
||||
/// <summary>Print automatically when an item is selected.</summary>
|
||||
public bool OnSelect;
|
||||
/// <summary>Print automatically when an item is selected. On unless the player turned it off (2026-10-31).</summary>
|
||||
public bool OnSelect = true;
|
||||
/// <summary>
|
||||
/// Print the selected item after a left (<see cref="ClickLeft"/>) or right (<see cref="ClickRight"/>)
|
||||
/// click in the game world / inventory — also re-prints an item that was already selected.
|
||||
|
|
@ -68,6 +68,17 @@ public sealed class MagItemInfoSettings
|
|||
/// <summary>Seconds to wait for an ID before printing partial data.</summary>
|
||||
public float IdTimeoutSec = 3f;
|
||||
|
||||
// ── Loot lines ───────────────────────────────────────────────────────────
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool LootChat = true;
|
||||
/// <summary>Salvage is described too, short: material and workmanship only.</summary>
|
||||
public bool LootChatSalvage;
|
||||
/// <summary>Chat type of a described loot line, or <see cref="SameAsHeader"/> for <see cref="ChatType"/>.</summary>
|
||||
public int LootChatType = SameAsHeader;
|
||||
|
||||
// ── What to print ────────────────────────────────────────────────────────
|
||||
/// <summary><see cref="MagItemInfoField"/> bits that are NOT printed.</summary>
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -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.");
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Describe looted items in chat" + "Include salvage". Shared with Advanced Settings → Looting,
|
||||
/// so <paramref name="idSuffix"/> keeps the ImGui ids unique per window.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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())
|
||||
|
|
|
|||
74
Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs
Normal file
74
Plugins/RynthCore.Plugin.RynthAi/Loot/LootWhy.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
/// <summary>
|
||||
/// /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.
|
||||
/// </summary>
|
||||
internal static class LootWhy
|
||||
{
|
||||
/// <summary>One rule above the winner that came close: it passed at least one condition before one failed.</summary>
|
||||
public readonly record struct NearMiss(int Index, string RuleName, string Failed);
|
||||
|
||||
public sealed class Result
|
||||
{
|
||||
public VTankLootVerdict Verdict { get; init; }
|
||||
/// <summary>The matched rule (Match), the rule that waits for the ID (NeedsId), or -1.</summary>
|
||||
public int Index { get; init; } = -1;
|
||||
public string RuleName { get; init; } = string.Empty;
|
||||
public VTankLootAction Action { get; init; }
|
||||
public List<NearMiss> NearMisses { get; } = new();
|
||||
}
|
||||
|
||||
public static string NameOf(VTankLootRule rule, int index)
|
||||
=> string.IsNullOrWhiteSpace(rule.Name) ? "#" + index : rule.Name.Trim();
|
||||
|
||||
/// <summary>
|
||||
/// The decision (<see cref="VTankLootEvaluator.Decide"/>) 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -41,6 +41,26 @@ public sealed class VTankLootContext
|
|||
return result;
|
||||
}
|
||||
|
||||
private readonly Dictionary<uint, int> _baseSkillCache = new();
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="VTankLootEvaluator.Decide"/> found for an item.</summary>
|
||||
public enum VTankLootVerdict
|
||||
{
|
||||
/// <summary>No rule takes the item.</summary>
|
||||
NoMatch,
|
||||
/// <summary>A rule takes it.</summary>
|
||||
Match,
|
||||
/// <summary>The first rule that could take it needs the item's identify data, which isn't in yet.</summary>
|
||||
NeedsId,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
|||
/// <summary>
|
||||
/// The first rule, in list order, that matches the item (rule Priority is not consulted),
|
||||
/// or null when none does; <paramref name="index"/> is its position, or -1.
|
||||
/// Corpse looting classifies items with this.
|
||||
/// The item's identify data is taken as in (see <see cref="Decide"/> for an item without it).
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<paramref name="hasIdData"/>
|
||||
/// false), a rule that nothing seen so far rules out but that needs the ID to decide stops the
|
||||
/// search with <see cref="VTankLootVerdict.NeedsId"/>: 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. <paramref name="index"/> is the
|
||||
/// matched rule (Match) or the rule that needs the ID (NeedsId); -1 for NoMatch.
|
||||
/// </summary>
|
||||
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<int> 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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// One condition on its own, same semantics as inside <see cref="Match(VTankLootRule, WorldObject?, VTankLootContext?)"/>.
|
||||
/// 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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string> d)
|
||||
private static bool MatchBuffedMedianDamageGE(WorldObject item, uint itemId, VTankLootContext? ctx, IList<string> 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<string> 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).
|
||||
|
||||
/// <summary>Decal's MaxDamage (0x0D000022): the weapon profile's max damage, property 44.</summary>
|
||||
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<uint>() : ctx.GetItemSpellIds(itemId);
|
||||
|
||||
/// <summary>A long key as VTank's Buffed Long Key reads it: the value plus the item's own cantrips.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A double key as VTank's Buffed Double Key reads it: the value plus (or, for mana
|
||||
/// conversion, times) the item's own cantrips.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Damage over time as VTank figures it: 10% crits at double damage.</summary>
|
||||
private static double DamageOverTime(double maxDamage, double variance)
|
||||
=> maxDamage * ((1 - 0.1) * (2 - variance) / 2 + 0.1 * 2);
|
||||
|
||||
/// <summary>Tinks the item can still take: 10 less those done, one kept for an imbue it lacks; none without a material.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Spends <paramref name="tinks"/> on damage (iron +1 or granite variance x0.8, whichever
|
||||
/// helps more) and returns the damage over time with Blood Drinker's 24.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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%). <paramref name="dot"/> is the damage
|
||||
/// reached, or -1 when a target is out of reach. This always failed until 2026-10-31.
|
||||
/// </summary>
|
||||
internal static bool MatchTinkedTargetMelee(WorldObject item, uint itemId, VTankLootContext? ctx, IList<string> 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<string> d)
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// /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.
|
||||
/// </summary>
|
||||
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('"');
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
/// </summary>
|
||||
|
|
@ -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 [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
|
||||
ReplyFail("[RynthAi] Usage: /ra iteminfo [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|loot on|off|reset]");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -470,6 +485,32 @@ public sealed partial class RynthAiPlugin
|
|||
return string.Join("\n ", lines);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The "Looted" line for a pickup, described when the Item Info loot setting wants it
|
||||
/// (<see cref="LootChatLine"/>), 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Item Info window "Test" button: sample line in the chosen chat type.</summary>
|
||||
private void TestItemInfoChatType(int chatType)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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.");
|
||||
|
||||
|
|
|
|||
|
|
@ -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}.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -901,6 +901,27 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private long _combatEndedAt;
|
||||
private const long LootGraceMs = 2000;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static bool IsFollowActive(LegacyUiSettings settings)
|
||||
=> (settings.FollowMode && settings.FollowTargetId != 0)
|
||||
|| (settings.CurrentRoute != null && settings.CurrentRoute.RouteType == NavRouteType.Follow
|
||||
&& settings.CurrentRoute.FollowTargetName.Length > 0);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private bool NavWantsTick(LegacyUiSettings settings)
|
||||
=> settings.IsMacroRunning && settings.EnableNavigation
|
||||
&& ((settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0) || IsFollowActive(settings))
|
||||
&& !OwnCorpseTravelHoldsNav;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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). <see cref="None"/>: no bank (or no server
|
||||
/// plugin saying so), and a buy counts the pack only.
|
||||
/// </summary>
|
||||
internal readonly record struct VendorBank(bool Pays, long Pyreals = -1)
|
||||
{
|
||||
/// <summary>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.</summary>
|
||||
public const long MaxPyreals = 1_000_000_000_000_000;
|
||||
|
||||
public static readonly VendorBank None = new(false);
|
||||
|
||||
/// <summary>The bank's balance is read.</summary>
|
||||
public bool Known => Pays && Pyreals >= 0;
|
||||
|
||||
/// <summary>A profile JSON's bank values; <see cref="None"/> without "vendorBank" above 0 (or for unusable text). Pure.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="BankPays"/>) adds its balance to the pack's, or, when the balance
|
||||
/// can't be read, leaves the money to the server.
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>The server's bank pays this (pyreal) vendor what the pack is short of.</summary>
|
||||
public bool BankPays { get; init; }
|
||||
/// <summary>The pyreals the bank can add (with <see cref="BankPays"/>); -1 = its balance can't be read.</summary>
|
||||
public long BankFunds { get; init; } = -1;
|
||||
|
||||
public bool Stackable => MaxStack > 0;
|
||||
|
||||
/// <summary>From the engine's vendor snapshot (API v67) and what the player has.</summary>
|
||||
public static VendorQuote From(VendorInfo info, VendorItem item, int freeItemSlots, int freeContainerSlots, long freeBurden)
|
||||
/// <summary>A bank pays, and its balance is read: pack + bank count.</summary>
|
||||
public bool BankKnown => BankPays && BankFunds >= 0;
|
||||
|
||||
/// <summary>A bank pays, but its balance can't be read: the server decides about the money.</summary>
|
||||
public bool BankUnknown => BankPays && BankFunds < 0;
|
||||
|
||||
/// <summary>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).</summary>
|
||||
public long Spendable => Funds < 0 || BankUnknown ? -1 : BankKnown ? Funds + Math.Min(BankFunds, VendorBank.MaxPyreals) : Funds;
|
||||
|
||||
/// <summary>From the engine's vendor snapshot (API v67), what the player has, and the server's bank (pyreal vendors only).</summary>
|
||||
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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The price line under the Buy button: "300 pyreals · you have 1,250".</summary>
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the bank does for buying <paramref name="n"/>, when the pack alone is short (null otherwise,
|
||||
/// and always without a bank): the box's one-line note.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>What "max" counts, when that isn't plain: "" without a bank, or with one that's read.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>What the quantity box's actions say (chat and the Selection window). Pure.</summary>
|
||||
|
|
@ -402,5 +487,23 @@ internal static class QtyReplies
|
|||
return $"The vendor didn't sell it: {m}.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A buy's refusal when the server's bank was to pay part of it (<paramref name="bankMayPay"/>):
|
||||
/// 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 <see cref="VendorRefusal"/>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The server answered a buy without selling it.</summary>
|
||||
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..];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
/// <summary>Burden you can still carry (three times your capacity, as ACE); -1 = unknown.</summary>
|
||||
long FreeBurden();
|
||||
/// <summary>The active server's bank, as its plugin says (VendorBank.None: none, or nobody says).</summary>
|
||||
VendorBank Bank();
|
||||
}
|
||||
|
||||
/// <summary>The engine host's side (RynthCoreHost). Plugin pump thread only.</summary>
|
||||
|
|
@ -97,9 +102,21 @@ internal sealed class HostQtyWorld : IQtyWorld
|
|||
private uint[] _order = new uint[16];
|
||||
private uint _vendorId, _vendorGeneration;
|
||||
private VendorItem[] _vendorItems = Array.Empty<VendorItem>();
|
||||
// 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;
|
||||
|
||||
/// <summary>Login or logout: the next server may be another (its bank read afresh).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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;
|
||||
/// <summary>Buy: the server's bank was to pay what the pack is short of.</summary>
|
||||
public bool BankMayPay;
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: the give target, and the answer to the action in flight.</summary>
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,11 @@
|
|||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
|
||||
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
|
||||
<!-- The active server (plugin API v86 GetServerStateJson) and its owner's "RynthServer.Profile"
|
||||
values (2026-10-31): whether its bank pays vendors, and how much, for the quantity box's buys. -->
|
||||
<Compile Include="..\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
|
||||
<Compile Include="..\Shared\ServerStateClient.cs" Link="Shared\ServerStateClient.cs" />
|
||||
<Compile Include="..\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Spell slots (2026-10-28): spell names and whom a spell is cast on, from RynthAi's spell table
|
||||
|
|
|
|||
|
|
@ -117,6 +117,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
_session.Use.ResetSession();
|
||||
_world?.Reset();
|
||||
_qty.Reset();
|
||||
_qtyWorld?.Reset();
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
|
|
@ -129,6 +130,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
|
|||
_session.Use.ResetSession();
|
||||
_world?.Reset();
|
||||
_qty.Reset();
|
||||
_qtyWorld?.Reset();
|
||||
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
|
||||
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow, _settingsWindow })
|
||||
if (w != null) { w.Visible = false; w.NeedsPass = true; }
|
||||
|
|
|
|||
|
|
@ -71,6 +71,10 @@ internal sealed partial class SelectionWindow
|
|||
: $"Half the stack ({QuantityRules.N(QuantityRules.HalfOf(max))}).";
|
||||
if (Chip(dl, "##qty_half", "half", ref x, y, rowH, right, max >= 1, halfTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Half, max);
|
||||
string maxTip = max < 1 ? none
|
||||
: s.Mode == QtyMode.Vendor && s.Quote is { BankUnknown: true } bq
|
||||
? $"The most your packs and burden take of what the vendor has ({QuantityRules.N(max)}): {bq.MaxNote}; the server decides about the money."
|
||||
: s.Mode == QtyMode.Vendor && s.Quote is { BankKnown: true }
|
||||
? $"The most you can buy now ({QuantityRules.N(max)}): what the vendor has, your pack and the bank pay for, and your packs take."
|
||||
: s.Mode == QtyMode.Vendor ? $"The most you can buy now ({QuantityRules.N(max)}): what the vendor has, you can pay for and your packs take."
|
||||
: $"The whole stack ({QuantityRules.N(max)}). A split still leaves one.";
|
||||
if (Chip(dl, "##qty_max", "max", ref x, y, rowH, right, max >= 1, maxTip)) ctl.Value = QuantityRules.ForBox(QtyAmount.Max, max);
|
||||
|
|
@ -184,8 +188,10 @@ internal sealed partial class SelectionWindow
|
|||
QtySubject s = q.Subject;
|
||||
VendorQuote? quote = s.Quote;
|
||||
string? why = quote?.Refusal(value);
|
||||
string? bank = quote?.BankNote(value);
|
||||
string tip = q.Busy ? QtyReplies.Busy
|
||||
: why ?? (quote != null ? $"Buy {QuantityRules.N(value)} {s.Name} for {QuantityRules.N(quote.Cost(value))} {quote.Currency}. The vendor checks again before it sells." : "Buy.");
|
||||
: why ?? (quote != null ? $"Buy {QuantityRules.N(value)} {s.Name} for {QuantityRules.N(quote.Cost(value))} {quote.Currency}. "
|
||||
+ (bank != null ? bank + " " : string.Empty) + "The vendor checks again before it sells." : "Buy.");
|
||||
if (Chip(dl, "##qty_buy", "Buy " + QuantityRules.N(value), ref x, y, h, right, !q.Busy, tip, primary: why == null))
|
||||
QuantityAction?.Invoke(QtyClick.Buy, value);
|
||||
if (quote == null) return;
|
||||
|
|
@ -202,6 +208,9 @@ internal sealed partial class SelectionWindow
|
|||
{
|
||||
string? why = s.Quote?.Refusal(value);
|
||||
if (why != null) { line = why; color = WarnColor; return; }
|
||||
// The bank's part: paid from a bank that's read, or the server's to decide.
|
||||
string? bank = s.Quote?.BankNote(value);
|
||||
if (bank != null) { line = bank; color = s.Quote!.BankUnknown ? WarnColor : _dim; return; }
|
||||
line = s.Quote is { UnitPrice: > 0 } qq ? $"{QuantityRules.N(qq.UnitPrice)} {qq.Currency} each. /rdef buy N does the same." : "/rdef buy N does the same.";
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
171
Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersLook.cs
Normal file
171
Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersLook.cs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
// ============================================================================
|
||||
// RynthNet - Characters/CharactersLook.cs
|
||||
// The Characters window's two looks (2026-10-31, the owner: "our networking
|
||||
// tab should be changed to look similar to our Lua script for components. Very
|
||||
// minimalistic."), pure so Tools/RynthNet.Tests compiles it in:
|
||||
//
|
||||
// Minimal the default: one compact line per character, no frame and no
|
||||
// background on an engine with frameless windows (API v90): a
|
||||
// status dot (botting, fighting, idle, dead, stale...), the name
|
||||
// (amber when its health is low, red when critical or dead), three
|
||||
// thin vital bars, and the arrow and distance when there is room.
|
||||
// Full "edit mode": the framed window with every column (the look the
|
||||
// window had before), where it is moved and resized.
|
||||
//
|
||||
// Here: the view names and /rn view, the low-health thresholds, the status
|
||||
// dot, and the minimal line's layout at a width. Kept per character in
|
||||
// RynthNet's settings.json ("view" under the character).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet.Characters;
|
||||
|
||||
/// <summary>How the Characters window looks.</summary>
|
||||
internal enum CharactersViewMode
|
||||
{
|
||||
/// <summary>One compact line per character, frameless (the default).</summary>
|
||||
Minimal = 0,
|
||||
/// <summary>The framed window with every column.</summary>
|
||||
Full = 1,
|
||||
}
|
||||
|
||||
/// <summary>A character's health, for the minimal line's colour.</summary>
|
||||
internal enum HpWarn { Ok, Low, Critical, Dead, Unknown }
|
||||
|
||||
/// <summary>The minimal line's status dot.</summary>
|
||||
internal enum CharDot { Self, Botting, Fighting, Idle, Dead, Portal, Stale, Off }
|
||||
|
||||
/// <summary>The minimal line at a width (px): the name column, the bars and whether the arrow and distance fit.</summary>
|
||||
internal readonly record struct MinimalLine(float NameWidth, bool Bars, float BarWidth, bool Distance)
|
||||
{
|
||||
/// <summary>How wide the line is drawn (dot, name, bars, distance).</summary>
|
||||
public float Width(float k, float distWidth) =>
|
||||
CharactersLook.DotWidth * k + NameWidth
|
||||
+ (Bars ? CharactersLook.Gap * k + 3 * BarWidth + 2 * CharactersLook.BarGap * k : 0)
|
||||
+ (Distance ? CharactersLook.Gap * k + CharactersLook.ArrowWidth * k + distWidth : 0);
|
||||
}
|
||||
|
||||
/// <summary>What /rn view did.</summary>
|
||||
internal readonly record struct ViewAnswer(bool Ok, CharactersViewMode Next, bool Changed, string Reply);
|
||||
|
||||
internal static class CharactersLook
|
||||
{
|
||||
/// <summary>Health at or below this share is low (amber), at or below <see cref="CriticalHp"/> critical (red).</summary>
|
||||
public const float LowHp = 0.5f, CriticalHp = 0.25f;
|
||||
|
||||
/// <summary>Minimal line metrics (px at 100%).</summary>
|
||||
public const float RowHeight = 16f, DotWidth = 12f, Gap = 6f, BarWidth = 24f, MinBarWidth = 8f, BarGap = 2f,
|
||||
BarHeight = 4f, ArrowWidth = 14f, MinNameWidth = 30f;
|
||||
|
||||
public const string Usage = "usage: /rn view [minimal|full] (alone: the view now)";
|
||||
|
||||
// ── colours ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The health warning for a row: dead (its state, or 0 health), critical, low, fine, or unknown (no vitals).</summary>
|
||||
public static HpWarn Hp(CharacterRow r)
|
||||
{
|
||||
if (r.StateKind == CharStateKind.Dead) return HpWarn.Dead;
|
||||
if (!r.HasVitals) return HpWarn.Unknown;
|
||||
return Hp(r.Hp.Fraction);
|
||||
}
|
||||
|
||||
/// <summary>The warning for a health share (0..1).</summary>
|
||||
public static HpWarn Hp(float fraction)
|
||||
{
|
||||
if (fraction <= 0f) return HpWarn.Dead;
|
||||
if (fraction <= CriticalHp) return HpWarn.Critical;
|
||||
if (fraction <= LowHp) return HpWarn.Low;
|
||||
return HpWarn.Ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The status dot: logged out or no status (off), this client, dead, not updating (stale), portal
|
||||
/// space, fighting, botting, else idle. Dead and stale come before what the bot was doing.
|
||||
/// </summary>
|
||||
public static CharDot Dot(CharacterRow r)
|
||||
{
|
||||
if (r.LoggedOut || r.StateKind == CharStateKind.NoStatus) return CharDot.Off;
|
||||
if (r.IsSelf) return CharDot.Self;
|
||||
if (r.StateKind == CharStateKind.Dead) return CharDot.Dead;
|
||||
if (r.Stale) return CharDot.Stale;
|
||||
return r.StateKind switch
|
||||
{
|
||||
CharStateKind.Portal => CharDot.Portal,
|
||||
CharStateKind.Fighting => CharDot.Fighting,
|
||||
CharStateKind.Botting => CharDot.Botting,
|
||||
_ => CharDot.Idle,
|
||||
};
|
||||
}
|
||||
|
||||
// ── layout ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The minimal line in <paramref name="width"/> px, for names up to <paramref name="nameWidth"/> and a
|
||||
/// distance up to <paramref name="distWidth"/> (k: the text size factor). The name and the bars come
|
||||
/// first; the arrow and distance only when everything fits. Narrower, the name gives way down to
|
||||
/// <see cref="MinNameWidth"/>, then the bars shrink to <see cref="MinBarWidth"/>, then go.
|
||||
/// </summary>
|
||||
public static MinimalLine Minimal(float width, float nameWidth, float distWidth, float k = 1f)
|
||||
{
|
||||
if (k <= 0) k = 1f;
|
||||
float dot = DotWidth * k, gap = Gap * k, barGap = BarGap * k;
|
||||
float bars = 3 * BarWidth * k + 2 * barGap;
|
||||
float dist = gap + ArrowWidth * k + distWidth;
|
||||
if (distWidth > 0 && width >= dot + nameWidth + gap + bars + dist)
|
||||
return new MinimalLine(nameWidth, true, BarWidth * k, true);
|
||||
|
||||
float minName = Math.Min(nameWidth, MinNameWidth * k);
|
||||
float name = Math.Clamp(width - dot - gap - bars, minName, nameWidth);
|
||||
if (width >= dot + name + gap + bars)
|
||||
return new MinimalLine(name, true, BarWidth * k, false);
|
||||
|
||||
float bar = (width - dot - minName - gap - 2 * barGap) / 3f;
|
||||
if (bar >= MinBarWidth * k)
|
||||
return new MinimalLine(minName, true, MathF.Floor(bar), false);
|
||||
return new MinimalLine(Math.Max(0, Math.Min(nameWidth, width - dot)), false, 0, false);
|
||||
}
|
||||
|
||||
/// <summary>The height the minimal window asks for: one line per row (at least one, for the status), and a small margin.</summary>
|
||||
public static float MinimalHeight(int rows, float k = 1f) => MathF.Ceiling((Math.Max(1, rows) * RowHeight + 4f) * (k <= 0 ? 1f : k));
|
||||
|
||||
// ── the view ────────────────────────────────────────────────────────
|
||||
|
||||
public static string Name(CharactersViewMode mode) => mode == CharactersViewMode.Full ? "full" : "minimal";
|
||||
|
||||
/// <summary>"minimal" (or "min", "compact", "bare"), "full" (or "edit", "framed"); any case. False for anything else.</summary>
|
||||
public static bool TryParse(string? text, out CharactersViewMode mode)
|
||||
{
|
||||
switch ((text ?? "").Trim().ToLowerInvariant())
|
||||
{
|
||||
case "minimal": case "min": case "compact": case "bare": mode = CharactersViewMode.Minimal; return true;
|
||||
case "full": case "edit": case "framed": mode = CharactersViewMode.Full; return true;
|
||||
default: mode = CharactersViewMode.Minimal; return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The settings file's value: a known name, else the default (minimal).</summary>
|
||||
public static CharactersViewMode FromSetting(string? text) => TryParse(text, out CharactersViewMode m) ? m : CharactersViewMode.Minimal;
|
||||
|
||||
/// <summary>
|
||||
/// /rn view [minimal|full|toggle]: alone says the view now. <paramref name="loggedIn"/>: the view is
|
||||
/// kept per character, so changing it needs one.
|
||||
/// </summary>
|
||||
public static ViewAnswer Command(string? args, CharactersViewMode current, bool loggedIn)
|
||||
{
|
||||
string a = (args ?? "").Trim().ToLowerInvariant();
|
||||
if (a.Length == 0) return new ViewAnswer(true, current, false, Describe(current, "the Characters window is in the "));
|
||||
CharactersViewMode next;
|
||||
if (a == "toggle") next = current == CharactersViewMode.Full ? CharactersViewMode.Minimal : CharactersViewMode.Full;
|
||||
else if (!TryParse(a, out next)) return new ViewAnswer(false, current, false, Usage);
|
||||
if (!loggedIn) return new ViewAnswer(false, current, false, "log in first: the view is kept per character.");
|
||||
bool changed = next != current;
|
||||
return new ViewAnswer(true, next, changed,
|
||||
Describe(next, changed ? "the Characters window now shows the " : "the Characters window is already in the "));
|
||||
}
|
||||
|
||||
/// <summary>"<head>minimal view (one line per character...). /rn view full for every column."</summary>
|
||||
public static string Describe(CharactersViewMode mode, string head) => head + (mode == CharactersViewMode.Full
|
||||
? "full view (every column; move and resize it here). /rn view minimal for the small one."
|
||||
: "minimal view (one line per character, no frame). /rn view full for every column, to move or resize it.");
|
||||
}
|
||||
|
|
@ -5,6 +5,14 @@
|
|||
// remembered place) and RynthNet draws (RynthPluginRenderEmbed with Surface).
|
||||
// Its title is the panel key players' saved places, /rc characters and hotkeys
|
||||
// already use. An engine before v89 ignores "windows". Pure.
|
||||
//
|
||||
// On an engine with frameless windows (v90, HasFramelessWindows) the window
|
||||
// is declared "chrome": "none" with "fitHeight" (2026-10-31): RynthNet draws
|
||||
// both of its looks itself (CharactersLook.cs), the minimal one without any
|
||||
// frame or background, the full one with its own frame and title row (drag,
|
||||
// pop-out, close), and the window is as tall as what it shows. On an older
|
||||
// engine it keeps the engine's frame (Json, as before) and the minimal look
|
||||
// draws inside it.
|
||||
// ============================================================================
|
||||
|
||||
using System.Globalization;
|
||||
|
|
@ -17,9 +25,19 @@ internal static class CharactersManifest
|
|||
public const string Title = "Characters";
|
||||
public const string Surface = "window:characters";
|
||||
|
||||
/// <summary>The manifest JSON (built once).</summary>
|
||||
public static readonly string Json =
|
||||
private static readonly string Head =
|
||||
"{\"version\":1,\"windows\":[{\"id\":\"characters\",\"title\":\"" + Title + "\",\"surface\":\"" + Surface +
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.UsersThree[0]).ToString("X4", CultureInfo.InvariantCulture) +
|
||||
"\",\"width\":420,\"height\":260,\"minWidth\":280,\"minHeight\":140,\"bar\":true,\"edgeToEdge\":true}]}";
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.UsersThree[0]).ToString("X4", CultureInfo.InvariantCulture) + "\",";
|
||||
|
||||
/// <summary>The manifest JSON for an engine without frameless windows: the engine's frame (built once).</summary>
|
||||
public static readonly string Json =
|
||||
Head + "\"width\":420,\"height\":260,\"minWidth\":280,\"minHeight\":140,\"bar\":true,\"edgeToEdge\":true}]}";
|
||||
|
||||
/// <summary>The manifest JSON for an engine with frameless windows (v90): RynthNet draws every frame (built once).</summary>
|
||||
public static readonly string FramelessJson =
|
||||
Head + "\"width\":420,\"height\":120,\"minWidth\":160,\"minHeight\":20,\"bar\":true,\"edgeToEdge\":true," +
|
||||
"\"chrome\":\"none\",\"fitHeight\":true}]}";
|
||||
|
||||
/// <summary>The manifest for this engine: frameless when it has frameless windows.</summary>
|
||||
public static string For(bool framelessWindows) => framelessWindows ? FramelessJson : Json;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,18 @@
|
|||
// it in game; right-click for /rn commands. Looks: Shared/RynthUi (the
|
||||
// player's theme). AC's render thread: it reads the published rows and the
|
||||
// pose, and queues everything it does for the plugin tick.
|
||||
//
|
||||
// Two looks (2026-10-31, CharactersLook.cs; /rn view, kept per character):
|
||||
// minimal the default, in item-counter.lua's style: one line per
|
||||
// character (status dot, name coloured by its health, three thin
|
||||
// vital bars, the arrow and distance when there is room), no frame
|
||||
// or background on an engine with frameless windows (v90). Hover
|
||||
// it for the pencil that brings the full look back.
|
||||
// full every column, as before. On a v90 engine the window is
|
||||
// frameless, so this look paints its own frame and title row:
|
||||
// drag it to move, Ctrl+wheel for the text size, the buttons for
|
||||
// the minimal look, pop-out and close; the corner resizes it.
|
||||
// Both ask for the height they need (the window fits it, "fitHeight").
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -23,10 +35,12 @@ namespace RynthCore.Plugin.RynthNet.Characters;
|
|||
|
||||
internal sealed class CharactersWindow
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly Action<uint> _select;
|
||||
private readonly Action<string, string> _tell;
|
||||
private readonly Action _followMeAll;
|
||||
private readonly Func<(bool Ok, float Heading)> _heading;
|
||||
private readonly Action<CharactersViewMode> _setView;
|
||||
|
||||
// The vitals colours of RynthAi's dashboard (fixed, whatever the theme).
|
||||
private static readonly uint HpCol = Argb(0xFFD93333), StCol = Argb(0xFF40D973), MpCol = Argb(0xFF268CF2),
|
||||
|
|
@ -42,6 +56,8 @@ internal sealed class CharactersWindow
|
|||
"Click a row to select that character in game (when this client can see it). Right-click for commands: " +
|
||||
"follow me, stop following, start or stop the macro. They go through RynthNet, so the other client's " +
|
||||
"remote command setting (/rn remote) decides whether they run.\n\n" +
|
||||
"The arrows-in button (or /rn view minimal) shows one line per character without the frame; " +
|
||||
"hover it for the pencil (or /rn view full) to come back here. Kept per character.\n\n" +
|
||||
"/rc characters opens and closes this window.";
|
||||
|
||||
private float _k = 1f;
|
||||
|
|
@ -53,33 +69,64 @@ internal sealed class CharactersWindow
|
|||
private bool _menuInView, _menuOtherWorld, _menuSelf, _menuLoggedOut;
|
||||
private bool _openMenu;
|
||||
|
||||
public CharactersWindow(Action<uint> select, Action<string, string> tell, Action followMeAll, Func<(bool, float)> heading)
|
||||
public CharactersWindow(RynthCoreHost host, Action<uint> select, Action<string, string> tell, Action followMeAll,
|
||||
Func<(bool, float)> heading, Action<CharactersViewMode> setView)
|
||||
{
|
||||
_host = host;
|
||||
_select = select;
|
||||
_tell = tell;
|
||||
_followMeAll = followMeAll;
|
||||
_heading = heading;
|
||||
_setView = setView;
|
||||
}
|
||||
|
||||
/// <summary>Draws the window body into the current ImGui window. Render thread.</summary>
|
||||
public void Draw(CharactersView view)
|
||||
/// <summary>
|
||||
/// Draws the window body into the current ImGui window in <paramref name="mode"/>'s look.
|
||||
/// <paramref name="frameless"/>: the engine gave the window no frame (v90), so the full look paints
|
||||
/// its own. <paramref name="popped"/>: drawn in its own OS window, so the minimal look keeps a
|
||||
/// background. Returns the height it needs (pixels; 0 = whatever the window is). Render thread.
|
||||
/// </summary>
|
||||
public float Draw(CharactersView view, CharactersViewMode mode, bool frameless, bool popped = false)
|
||||
{
|
||||
_k = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
|
||||
if (mode == CharactersViewMode.Full) return DrawFull(view, ownFrame: frameless);
|
||||
if (popped)
|
||||
{
|
||||
Vector2 o = ImGui.GetCursorScreenPos();
|
||||
ImGui.GetWindowDrawList().AddRectFilled(o, o + ImGui.GetContentRegionAvail(), Background, 4);
|
||||
}
|
||||
return DrawMinimal(view, frameless && !popped);
|
||||
}
|
||||
|
||||
// ── Full look ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Every column. <paramref name="ownFrame"/>: paint the frame and a title row (the engine gave none)
|
||||
/// and return the height the rows need; otherwise fill the engine's frame and return 0.
|
||||
/// </summary>
|
||||
private float DrawFull(CharactersView view, bool ownFrame)
|
||||
{
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGui.GetContentRegionAvail();
|
||||
if (size.X < 40 || size.Y < 30) return;
|
||||
float titleH = ownFrame ? Px(20) : 0f;
|
||||
float rowsH = view.Rows.Length == 0 ? Px(30) : view.Rows.Length * RowH;
|
||||
// Margin, title, the status line, the rows, and room under them for the corner grip.
|
||||
float want = MathF.Ceiling(6 + titleH + Px(24) + rowsH + 6 + Px(12));
|
||||
if (ownFrame) size.Y = Math.Max(size.Y, want); // a frame late: draw at the height asked for
|
||||
if (size.X < 40 || size.Y < 30) return ownFrame ? want : 0f;
|
||||
ImDrawListPtr frame = ImGui.GetWindowDrawList();
|
||||
frame.AddRectFilled(origin, origin + size, Background, 4);
|
||||
using (PushFont(RynthUiFont.Ui10))
|
||||
{
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
|
||||
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
|
||||
if (ownFrame) DrawTitle(origin, size.X, titleH);
|
||||
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6 + titleH));
|
||||
ImGui.Indent(6);
|
||||
float w = size.X - 12;
|
||||
DrawTop(view, w);
|
||||
DrawTop(view, w, minimalButton: !ownFrame); // framed by the engine: no title row, so the button sits here
|
||||
|
||||
// The host's resize grip sits over the bottom-right corner: the rows end above it.
|
||||
float bodyH = Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(12));
|
||||
float bodyH = ownFrame ? rowsH : Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(12));
|
||||
ImGui.PushStyleColor(ImGuiCol.ChildBg, Field);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGui.BeginChild("##chars_rows", new Vector2(w, bodyH));
|
||||
|
|
@ -93,22 +140,245 @@ internal sealed class CharactersWindow
|
|||
DrawMenu(view);
|
||||
}
|
||||
frame.AddRect(origin, origin + size, Border, 4);
|
||||
return ownFrame ? want : 0f;
|
||||
}
|
||||
|
||||
/// <summary>The full look's own title row (frameless window): drag to move; minimal, pop-out and close.</summary>
|
||||
private void DrawTitle(Vector2 origin, float width, float h)
|
||||
{
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
float bw = Px(20), gap = Px(3);
|
||||
float buttons = 3 * bw + 2 * gap + 6;
|
||||
var top = new Vector2(origin.X, origin.Y + 3);
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.InvisibleButton("##chars_title", new Vector2(Math.Max(10, width - buttons), h + 3));
|
||||
_host.PanelDragWithLastItem();
|
||||
SafeImGui.SetItemTooltip("Drag to move. Ctrl+wheel: text size. The corner resizes it.");
|
||||
ImFontPtr bold = Font(RynthUiFont.UiBold11);
|
||||
DrawCentered(dl, Font(RynthUiFont.Ui11), RynthIcons.UsersThree, new Vector2(origin.X + 6, top.Y), new Vector2(Px(14), h), Accent);
|
||||
dl.AddText(bold, bold.FontSize, new Vector2(origin.X + 6 + Px(18), top.Y + (h - bold.FontSize) * 0.5f), Text, CharactersManifest.Title);
|
||||
|
||||
float bx = origin.X + width - 6 - 3 * bw - 2 * gap;
|
||||
var bsize = new Vector2(bw, h - Px(2));
|
||||
if (IconButton("##chars_minimal", RynthIcons.ArrowsInLineVertical, new Vector2(bx, top.Y), bsize, Text, ButtonFill, font: RynthUiFont.Ui11))
|
||||
_setView(CharactersViewMode.Minimal);
|
||||
ImGui.SetItemTooltip("Minimal: one line per character, no frame (/rn view minimal)");
|
||||
if (IconButton("##chars_popout", RynthIcons.ArrowSquareOut, new Vector2(bx + bw + gap, top.Y), bsize, Text, ButtonFill, font: RynthUiFont.Ui11))
|
||||
_host.SetPanelPopOut(CharactersManifest.Title, RynthPanelPopOut.Toggle);
|
||||
ImGui.SetItemTooltip("Pop out into its own window, or dock it back");
|
||||
if (IconButton("##chars_close", RynthIcons.X, new Vector2(bx + 2 * (bw + gap), top.Y), bsize, Text, ButtonFill, font: RynthUiFont.Ui11))
|
||||
_host.SetPanelOpen(CharactersManifest.Title, RynthPanelOpen.Close);
|
||||
ImGui.SetItemTooltip("Close (/rc characters opens it again)");
|
||||
}
|
||||
|
||||
// ── Minimal look ────────────────────────────────────────────────────
|
||||
|
||||
private static readonly uint Shadow = 0xB0000000;
|
||||
|
||||
/// <summary>
|
||||
/// One line per character: status dot, name (its health's colour), three thin bars, arrow and
|
||||
/// distance when there's room. <paramref name="frameless"/>: no frame or background, the text
|
||||
/// shadowed so it reads over the game. Returns the height it needs.
|
||||
/// </summary>
|
||||
private float DrawMinimal(CharactersView view, bool frameless)
|
||||
{
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
float width = ImGui.GetContentRegionAvail().X;
|
||||
CharacterRow[] rows = view.Rows;
|
||||
float want = CharactersLook.MinimalHeight(rows.Length, _k);
|
||||
if (width < 20) return want;
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
using (PushFont(RynthUiFont.Ui10))
|
||||
{
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, Vector2.Zero);
|
||||
float fontH = ImGui.GetFontSize();
|
||||
float rowH = MathF.Max(Px(CharactersLook.RowHeight), MathF.Ceiling(fontH + 3));
|
||||
want = MathF.Max(want, MathF.Ceiling(Math.Max(1, rows.Length) * rowH + 4));
|
||||
var start = new Vector2(origin.X + 2, origin.Y + 2);
|
||||
bool windowHot = ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
|
||||
float lineW;
|
||||
|
||||
if (rows.Length == 0)
|
||||
{
|
||||
// Nothing to list: the status, faint (and the pencil on hover).
|
||||
DrawDot(dl, new Vector2(start.X + Px(CharactersLook.DotWidth) * 0.5f, start.Y + rowH * 0.5f), CharDot.Off);
|
||||
string s = view.Status;
|
||||
float tw = Math.Min(ImGui.CalcTextSize(s).X, width - Px(CharactersLook.DotWidth) - Px(30));
|
||||
ShadowClip(dl, s, start.X + Px(CharactersLook.DotWidth), start.Y + (rowH - fontH) * 0.5f, tw, Faded(Text), frameless);
|
||||
lineW = Px(CharactersLook.DotWidth) + Math.Max(0, tw);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Columns from the longest name and distance, so the bars line up.
|
||||
float nameW = 0, distW = 0;
|
||||
foreach (CharacterRow r in rows)
|
||||
{
|
||||
nameW = MathF.Max(nameW, ImGui.CalcTextSize(r.Name).X);
|
||||
if (ShowsDistance(r)) distW = MathF.Max(distW, ImGui.CalcTextSize(r.DistanceText).X);
|
||||
}
|
||||
nameW = MathF.Ceiling(nameW + Px(2));
|
||||
float editRoom = Px(20);
|
||||
MinimalLine line = CharactersLook.Minimal(width - 4 - editRoom, nameW, distW, _k);
|
||||
lineW = line.Width(_k, distW);
|
||||
(bool haveHeading, float heading) = _heading();
|
||||
int hovered = -1;
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
CharacterRow r = rows[i];
|
||||
var p = new Vector2(start.X, start.Y + i * rowH);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
ImGui.PushID(i);
|
||||
bool clicked = ImGui.InvisibleButton("##mrow", new Vector2(Math.Max(1, lineW), rowH),
|
||||
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hot = ImGui.IsItemHovered();
|
||||
bool right = clicked && ImGui.IsMouseReleased(ImGuiMouseButton.Right);
|
||||
ImGui.PopID();
|
||||
if (hot) hovered = i;
|
||||
if (clicked && !right && r.InView && r.Id != 0 && !r.IsSelf) _select(r.Id);
|
||||
if (right) OpenMenu(r);
|
||||
DrawMinimalRow(dl, r, p, line, lineW, rowH, fontH, hot, r.Id != 0 && r.Id == view.SelectedId,
|
||||
heading, haveHeading, distW, frameless);
|
||||
}
|
||||
if (hovered >= 0 && rows[hovered].Tooltip.Length > 0 && !ImGui.IsPopupOpen("##chars_menu"))
|
||||
{
|
||||
ImGui.BeginTooltip();
|
||||
ImGui.TextUnformatted(rows[hovered].Tooltip);
|
||||
ImGui.EndTooltip();
|
||||
}
|
||||
}
|
||||
|
||||
// The pencil: back to the full look (shown while the mouse is on the window).
|
||||
if (windowHot)
|
||||
{
|
||||
float bs = rowH - 2;
|
||||
var bp = new Vector2(Math.Min(start.X + lineW + Px(4), origin.X + width - bs - 2), start.Y + 1);
|
||||
if (IconButton("##chars_full", RynthIcons.PencilSimple, bp, new Vector2(bs, bs), Text, WithAlpha(Background, 0xE0),
|
||||
font: RynthUiFont.Ui11))
|
||||
_setView(CharactersViewMode.Full);
|
||||
ImGui.SetItemTooltip("Edit: the full window with every column, to move or resize it (/rn view full)");
|
||||
}
|
||||
|
||||
ImGui.SetCursorScreenPos(origin);
|
||||
ImGui.Dummy(new Vector2(Math.Max(1, width), Math.Max(1, want - 1)));
|
||||
ImGui.PopStyleVar();
|
||||
DrawMenu(view);
|
||||
}
|
||||
return want;
|
||||
}
|
||||
|
||||
private static bool ShowsDistance(CharacterRow r) => !r.IsSelf && !r.LoggedOut && r.DistanceText.Length > 0;
|
||||
|
||||
private void DrawMinimalRow(ImDrawListPtr dl, CharacterRow r, Vector2 p, MinimalLine line, float lineW, float rowH, float fontH,
|
||||
bool hot, bool isSel, float heading, bool haveHeading, float distW, bool frameless)
|
||||
{
|
||||
if (hot) dl.AddRectFilled(p, p + new Vector2(lineW, rowH), WithAlpha(Background, 0xB0), 2);
|
||||
if (isSel) dl.AddRect(p, p + new Vector2(lineW, rowH), Accent, 2);
|
||||
float dim = r.IsSelf || r.LoggedOut ? 0.6f : 1f;
|
||||
float x = p.X;
|
||||
float ty = p.Y + (rowH - fontH) * 0.5f;
|
||||
|
||||
DrawDot(dl, new Vector2(x + Px(CharactersLook.DotWidth) * 0.5f, p.Y + rowH * 0.5f), CharactersLook.Dot(r));
|
||||
x += Px(CharactersLook.DotWidth);
|
||||
|
||||
ShadowClip(dl, r.Name, x, ty, line.NameWidth, Fade(NameColor(r), dim), frameless);
|
||||
x += line.NameWidth;
|
||||
|
||||
if (line.Bars)
|
||||
{
|
||||
x += Px(CharactersLook.Gap);
|
||||
float bh = Math.Max(2f, Px(CharactersLook.BarHeight)), by = MathF.Round(p.Y + (rowH - bh) * 0.5f), gap = Px(CharactersLook.BarGap);
|
||||
if (r.HasVitals)
|
||||
{
|
||||
ThinBar(dl, x, by, line.BarWidth, bh, r.Hp.Fraction, Fade(HpCol, dim));
|
||||
ThinBar(dl, x + line.BarWidth + gap, by, line.BarWidth, bh, r.St.Fraction, Fade(StCol, dim));
|
||||
ThinBar(dl, x + 2 * (line.BarWidth + gap), by, line.BarWidth, bh, r.Mp.Fraction, Fade(MpCol, dim));
|
||||
}
|
||||
x += 3 * line.BarWidth + 2 * gap;
|
||||
}
|
||||
|
||||
if (line.Distance && ShowsDistance(r))
|
||||
{
|
||||
x += Px(CharactersLook.Gap);
|
||||
var mid = new Vector2(x + Px(CharactersLook.ArrowWidth) * 0.5f, p.Y + rowH * 0.5f);
|
||||
uint col = Fade(r.Measured ? Text : Faded(Mute), dim);
|
||||
if (r.Measured && haveHeading && !float.IsNaN(r.Bearing))
|
||||
{
|
||||
if (frameless) DrawArrow(dl, mid + new Vector2(1, 1), r.Bearing - heading, Shadow, _k * 0.8f);
|
||||
DrawArrow(dl, mid, r.Bearing - heading, Fade(StateColor(r), dim), _k * 0.8f);
|
||||
}
|
||||
else if (r.Measured)
|
||||
dl.AddCircleFilled(mid, Px(2f), col);
|
||||
x += Px(CharactersLook.ArrowWidth);
|
||||
ShadowClip(dl, r.DistanceText, x, ty, distW + 1, col, frameless);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The name's colour: its health's warning (amber low, red critical or dead), else the text colour.</summary>
|
||||
private static uint NameColor(CharacterRow r) => r.IsSelf ? Text : CharactersLook.Hp(r) switch
|
||||
{
|
||||
HpWarn.Dead or HpWarn.Critical => Red,
|
||||
HpWarn.Low => Highlight,
|
||||
HpWarn.Unknown when r.LoggedOut => Faded(Mute),
|
||||
_ => Text,
|
||||
};
|
||||
|
||||
private void DrawDot(ImDrawListPtr dl, Vector2 c, CharDot dot)
|
||||
{
|
||||
float r = Px(3f);
|
||||
switch (dot)
|
||||
{
|
||||
case CharDot.Off: dl.AddCircle(c, r, Faded(Mute), 12, Px(1.2f)); break;
|
||||
case CharDot.Stale: dl.AddCircle(c, r, Highlight, 12, Px(1.6f)); break;
|
||||
case CharDot.Self: dl.AddCircleFilled(c, r, Mute, 12); break;
|
||||
case CharDot.Dead: dl.AddCircleFilled(c, r, Red, 12); break;
|
||||
case CharDot.Portal: dl.AddCircleFilled(c, r, Purple, 12); break;
|
||||
case CharDot.Fighting: dl.AddCircleFilled(c, r, Highlight, 12); break;
|
||||
case CharDot.Botting: dl.AddCircleFilled(c, r, Green, 12); break;
|
||||
default: dl.AddCircleFilled(c, r, Faded(Mute), 12); break; // idle
|
||||
}
|
||||
}
|
||||
|
||||
private static void ThinBar(ImDrawListPtr dl, float x, float y, float w, float h, float fraction, uint color)
|
||||
{
|
||||
if (w <= 1) return;
|
||||
fraction = float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f;
|
||||
dl.AddRectFilled(new Vector2(x, y), new Vector2(x + w, y + h), WithAlpha(BarBg, 0xD0), 1);
|
||||
if (fraction > 0) dl.AddRectFilled(new Vector2(x, y), new Vector2(x + w * fraction, y + h), color, 1);
|
||||
}
|
||||
|
||||
/// <summary>Text clipped to <paramref name="width"/>, with a 1 px shadow when it sits over the game.</summary>
|
||||
private static void ShadowClip(ImDrawListPtr dl, string text, float x, float y, float width, uint color, bool shadow)
|
||||
{
|
||||
if (text.Length == 0 || width <= 0) return;
|
||||
dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width + 1, y + 40), true);
|
||||
if (shadow) dl.AddText(new Vector2(x + 1, y + 1), Shadow, text);
|
||||
dl.AddText(new Vector2(x, y), color, text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
// ── Top line ────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawTop(CharactersView view, float w)
|
||||
private void DrawTop(CharactersView view, float w, bool minimalButton)
|
||||
{
|
||||
Vector2 start = ImGui.GetCursorScreenPos();
|
||||
float h = Px(20), iconW = Px(22);
|
||||
int icons = minimalButton ? 3 : 2;
|
||||
float fontH = ImGui.GetFontSize();
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
float textW = Math.Max(10, w - 2 * iconW - Px(8));
|
||||
float textW = Math.Max(10, w - icons * iconW - Px(4) * icons);
|
||||
dl.PushClipRect(start, start + new Vector2(textW, h), true);
|
||||
dl.AddText(new Vector2(start.X, start.Y + (h - fontH) * 0.5f), Mute, view.Status);
|
||||
dl.PopClipRect();
|
||||
|
||||
float bx = start.X + w - 2 * iconW - Px(4);
|
||||
float bx = start.X + w - icons * iconW - Px(4) * (icons - 1);
|
||||
if (minimalButton)
|
||||
{
|
||||
if (IconButton("##chars_minimal", RynthIcons.ArrowsInLineVertical, new Vector2(bx, start.Y), new Vector2(iconW, h), Text, ButtonFill,
|
||||
font: RynthUiFont.Ui11))
|
||||
_setView(CharactersViewMode.Minimal);
|
||||
ImGui.SetItemTooltip("Minimal: one line per character (/rn view minimal)");
|
||||
bx += iconW + Px(4);
|
||||
}
|
||||
bool canFollow = view.MyName.Length > 0;
|
||||
if (IconButton("##chars_followall", RynthIcons.Footprints, new Vector2(bx, start.Y), new Vector2(iconW, h), Text, ButtonFill,
|
||||
enabled: canFollow, font: RynthUiFont.Ui11))
|
||||
|
|
|
|||
|
|
@ -37,8 +37,9 @@ public static unsafe class PluginExports
|
|||
{
|
||||
try
|
||||
{
|
||||
if (Runtime.Plugin == null) return IntPtr.Zero;
|
||||
string json = Characters.CharactersManifest.Json;
|
||||
RynthNetPlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null) return IntPtr.Zero;
|
||||
string json = Characters.CharactersManifest.For(plugin.FramelessWindows);
|
||||
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
|
||||
_sectionsJson = json;
|
||||
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
|
||||
|
|
@ -64,9 +65,10 @@ public static unsafe class PluginExports
|
|||
{
|
||||
if (surface == null) return 0;
|
||||
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
|
||||
if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length];
|
||||
bool popped = name.EndsWith(":popout", StringComparison.Ordinal);
|
||||
if (popped) name = name[..^":popout".Length];
|
||||
RynthNetPlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null || !plugin.RenderEmbed(name, out float wantH)) return 0;
|
||||
if (plugin == null || !plugin.RenderEmbed(name, popped, out float wantH)) return 0;
|
||||
if (wantWidth != null) *wantWidth = width;
|
||||
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
|
||||
return 1;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,11 @@
|
|||
// second while it is on screen (Characters/CharactersRows.cs). The window's
|
||||
// clicks are queued here and run on the tick: selecting a character, and /rn
|
||||
// tell / followme through the same queue as typed commands.
|
||||
//
|
||||
// Its look (2026-10-31): minimal (the default) or full, per character in
|
||||
// settings.json, switched by the window's own button or /rn view. On an engine
|
||||
// with frameless windows (v90) the window has no engine frame and RynthNet
|
||||
// draws both looks; on an older one the minimal look draws inside the frame.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -35,22 +40,67 @@ public sealed partial class RynthNetPlugin
|
|||
private readonly ConcurrentQueue<Action> _uiActions = new();
|
||||
private HostGame? _game;
|
||||
|
||||
/// <summary>The look the window draws now (render thread reads; the tick and /rn view set it).</summary>
|
||||
private volatile int _charsMode = (int)CharactersViewMode.Minimal;
|
||||
|
||||
/// <summary>The engine hosts frameless windows (v90): the manifest asks for one and RynthNet draws every frame.</summary>
|
||||
internal bool FramelessWindows => Host.HasFramelessWindows;
|
||||
|
||||
internal CharactersViewMode CharsLook => (CharactersViewMode)_charsMode;
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed: draws <paramref name="surface"/> (":popout" already off). Render thread.</summary>
|
||||
internal bool RenderEmbed(string surface, out float wantHeight)
|
||||
internal bool RenderEmbed(string surface, bool popped, out float wantHeight)
|
||||
{
|
||||
wantHeight = 0;
|
||||
if (!surface.Equals(CharactersSurface, StringComparison.Ordinal)) return false;
|
||||
System.Threading.Volatile.Write(ref _charsDrawnMs, Environment.TickCount64);
|
||||
AtlasNames.EnsureLoading(Path.Combine(RynthInstallPaths.CoreDir, "NavData", "locations.json"));
|
||||
_charsWindow ??= new CharactersWindow(
|
||||
Host,
|
||||
select: id => _uiActions.Enqueue(() => { if (id != 0) Host.SelectItem(id); }),
|
||||
tell: (name, command) => _localCommands.Enqueue(("/rn tell " + name + ", " + command, false)),
|
||||
followMeAll: () => _localCommands.Enqueue(("/rn followme", false)),
|
||||
heading: CompassHeading);
|
||||
_charsWindow.Draw(_charsView);
|
||||
heading: CompassHeading,
|
||||
setView: mode => _uiActions.Enqueue(() => SetCharactersView(mode, quiet: true)));
|
||||
wantHeight = _charsWindow.Draw(_charsView, CharsLook, FramelessWindows, popped);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets this character's window look and saves it (merged with the other clients' settings). Pump
|
||||
/// thread. Quiet (the window's own button): nothing in chat unless it couldn't be saved.
|
||||
/// </summary>
|
||||
private bool SetCharactersView(CharactersViewMode mode, bool quiet)
|
||||
{
|
||||
if (!_loggedIn)
|
||||
{
|
||||
// Before login there is no character to keep it for: this session only.
|
||||
_charsMode = (int)mode;
|
||||
return true;
|
||||
}
|
||||
string key = CharacterKey;
|
||||
string name = CharactersLook.Name(mode);
|
||||
if (!UpdateSettings(s => s.Character(key).View = name)) return false;
|
||||
_charsMode = (int)mode;
|
||||
if (!quiet) Host.Log("[RynthNet] Characters window: " + name + " view.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>/rn view [minimal|full|toggle]. Pump thread.</summary>
|
||||
private void ViewCommand(string args)
|
||||
{
|
||||
ViewAnswer a = CharactersLook.Command(args, CharsLook, _loggedIn);
|
||||
if (!a.Ok) { ChatFail(a.Reply); return; }
|
||||
if (a.Changed && !SetCharactersView(a.Next, quiet: false)) return; // UpdateSettings said why
|
||||
ChatLine(a.Reply);
|
||||
}
|
||||
|
||||
/// <summary>The look saved for the character logged in here (after login and when the file changes). Pump thread.</summary>
|
||||
private void SyncCharactersView()
|
||||
{
|
||||
if (_loggedIn) _charsMode = (int)_settings.ViewFor(CharacterKey);
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: the window's queued clicks, and its rows while it is on screen.</summary>
|
||||
private void TickCharacters()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -82,6 +82,9 @@ public sealed partial class RynthNetPlugin
|
|||
case "remote":
|
||||
RemoteCommand(args);
|
||||
break;
|
||||
case "view": // the Characters window's look: minimal (the default) or full
|
||||
ViewCommand(args);
|
||||
break;
|
||||
case "allow":
|
||||
ListSetting(p => p.Allow, "allow", args, "remote commands run only if they start with one of these (empty = all)");
|
||||
break;
|
||||
|
|
@ -179,6 +182,7 @@ public sealed partial class RynthNetPlugin
|
|||
ChatLine("/rn followme [tag] - the others /ra follow you; /rn usesel [tag] - they use your selection");
|
||||
ChatLine("/rn status - this client; /rn remote on|off|default - run others' commands on this character");
|
||||
ChatLine("/rn allow|deny|trust [list | add <x> | remove <x> | clear] - what may run here");
|
||||
ChatLine("/rn view [minimal|full] - the Characters window: one line each, or every column (kept per character)");
|
||||
ChatLine("UtilityBelt's /ub bc, /ub bct and /ub netclients work too.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -230,6 +230,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
|
|||
bool wasLoggedIn = _loggedIn;
|
||||
_loggedIn = true;
|
||||
PushIdentity();
|
||||
SyncCharactersView();
|
||||
if (!wasLoggedIn) _nextStatusMs = 0;
|
||||
}
|
||||
|
||||
|
|
@ -293,6 +294,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
|
|||
_settings = RynthNetSettings.Load(out string? error);
|
||||
if (error != null) Host.Log("[RynthNet] " + error);
|
||||
PushIdentity();
|
||||
SyncCharactersView(); // the file edited by hand: its view too
|
||||
}
|
||||
|
||||
// ── Network events ──────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -15,8 +15,11 @@
|
|||
// "logRemoteCommands": true,
|
||||
// "statusIntervalMs": 1000,
|
||||
// "defaults": { "acceptRemoteCommands": true, "allow": [], "deny": [], "trustedSenders": [] },
|
||||
// "characters": { "World|Name": { "tags": ["healer"], "policy": { ...same as defaults... } } }
|
||||
// "characters": { "World|Name": { "tags": ["healer"], "policy": { ...same as defaults... },
|
||||
// "view": "full" } }
|
||||
// }
|
||||
// "view" is how that character's Characters window looks (minimal, the default
|
||||
// when missing, or full: Characters/CharactersLook.cs, /rn view).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -24,6 +27,8 @@ using System.Collections.Generic;
|
|||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using CharactersLook = RynthCore.Plugin.RynthNet.Characters.CharactersLook;
|
||||
using CharactersViewMode = RynthCore.Plugin.RynthNet.Characters.CharactersViewMode;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNet;
|
||||
|
||||
|
|
@ -53,6 +58,8 @@ internal sealed class RynthNetCharacter
|
|||
public List<string> Tags = new();
|
||||
/// <summary>This character's own policy; null = the defaults.</summary>
|
||||
public RynthNetPolicy? Policy;
|
||||
/// <summary>The Characters window's look for this character ("minimal" / "full"); null = the default (minimal).</summary>
|
||||
public string? View;
|
||||
}
|
||||
|
||||
internal sealed class RynthNetSettings
|
||||
|
|
@ -79,6 +86,10 @@ internal sealed class RynthNetSettings
|
|||
public IReadOnlyList<string> TagsFor(string key)
|
||||
=> Characters.TryGetValue(key, out RynthNetCharacter? c) ? c.Tags : Array.Empty<string>();
|
||||
|
||||
/// <summary>The Characters window's look for the character (minimal when it has none saved).</summary>
|
||||
public CharactersViewMode ViewFor(string key)
|
||||
=> Characters.TryGetValue(key, out RynthNetCharacter? c) ? CharactersLook.FromSetting(c.View) : CharactersViewMode.Minimal;
|
||||
|
||||
/// <summary>The character's entry, created when missing.</summary>
|
||||
public RynthNetCharacter Character(string key)
|
||||
{
|
||||
|
|
@ -184,6 +195,9 @@ internal sealed class RynthNetSettings
|
|||
var c = new RynthNetCharacter { Tags = Strings(p.Value, "tags") };
|
||||
if (p.Value.TryGetProperty("policy", out JsonElement pol) && pol.ValueKind == JsonValueKind.Object)
|
||||
c.Policy = ParsePolicy(pol);
|
||||
if (p.Value.TryGetProperty("view", out JsonElement view) && view.ValueKind == JsonValueKind.String
|
||||
&& CharactersLook.TryParse(view.GetString(), out CharactersViewMode mode))
|
||||
c.View = CharactersLook.Name(mode);
|
||||
s.Characters[p.Name] = c;
|
||||
}
|
||||
}
|
||||
|
|
@ -211,7 +225,7 @@ internal sealed class RynthNetSettings
|
|||
w.WriteStartObject("characters");
|
||||
foreach (var kv in Characters)
|
||||
{
|
||||
if (kv.Value.Tags.Count == 0 && kv.Value.Policy == null) continue;
|
||||
if (kv.Value.Tags.Count == 0 && kv.Value.Policy == null && kv.Value.View == null) continue;
|
||||
w.WriteStartObject(kv.Key);
|
||||
WriteList(w, "tags", kv.Value.Tags);
|
||||
if (kv.Value.Policy != null)
|
||||
|
|
@ -219,6 +233,7 @@ internal sealed class RynthNetSettings
|
|||
w.WritePropertyName("policy");
|
||||
WritePolicy(w, kv.Value.Policy);
|
||||
}
|
||||
if (kv.Value.View != null) w.WriteString("view", kv.Value.View);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndObject();
|
||||
|
|
|
|||
|
|
@ -47,8 +47,12 @@
|
|||
// // Void timers apply;
|
||||
// "difficultyTier": 3, // the difficulty tier where the player stands (0 = the unscaled
|
||||
// // world; absent = the server has no tiers, or hasn't said yet),
|
||||
// "difficultyHealthPercent": 5 // and the monster health one tier adds, in percent of tier 0's
|
||||
// } // (RynthAelrynth; RynthAi keeps learned HP and kills per tier)
|
||||
// "difficultyHealthPercent": 5, // and the monster health one tier adds, in percent of tier 0's
|
||||
// // (RynthAelrynth; RynthAi keeps learned HP and kills per tier)
|
||||
// "vendorBank": 1, // the server's bank pays a pyreal vendor what the packs are short
|
||||
// // of (absent or 0 = it doesn't: readers count the packs only),
|
||||
// "vendorBankPyreals": 5000 // and what the bank can add beyond the pyreals the game shows
|
||||
// } // (absent = not known: the server decides). RynthDefective's buys.
|
||||
// }
|
||||
// ============================================================================
|
||||
|
||||
|
|
@ -83,6 +87,22 @@ public static class RynthServerProfile
|
|||
/// so tier 3 is 1.15 times tier 0's). Absent with a tier: 0 (health doesn't scale).
|
||||
/// </summary>
|
||||
public const string ValueDifficultyHealthPercent = "difficultyHealthPercent";
|
||||
|
||||
/// <summary>
|
||||
/// 1: this character's purchases from a pyreal vendor are paid from the server's bank when the
|
||||
/// packs are short (the server's own rule, or the character's choice where the server asks for
|
||||
/// one). Absent or 0: they aren't, and readers count the packs only (as on a retail server). A
|
||||
/// server that already shows pack + bank as the character's pyreals while shopping needs neither
|
||||
/// value: readers count the pyreals the game shows. (2026-10-31, RynthDefective's quantity box.)
|
||||
/// </summary>
|
||||
public const string ValueVendorBank = "vendorBank";
|
||||
|
||||
/// <summary>
|
||||
/// With <see cref="ValueVendorBank"/>: the pyreals the bank can add to a purchase, beyond the
|
||||
/// pyreals the game shows (whole pyreals, 0 or more). Absent (or below 0): not known, and readers
|
||||
/// leave the money to the server.
|
||||
/// </summary>
|
||||
public const string ValueVendorBankPyreals = "vendorBankPyreals";
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
|
|
|
|||
1815
Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl
Normal file
1815
Tools/RynthCore.RynthAiHostTests/Fixtures/lootsnob-excerpt.utl
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -58,6 +58,10 @@ internal static class Program
|
|||
var runner = new Runner();
|
||||
NativeLootTests.Register(runner);
|
||||
VTankLootTests.Register(runner);
|
||||
LootRuleMatchTests.Register(runner);
|
||||
LootLateIdTests.Register(runner);
|
||||
LootChatLineTests.Register(runner);
|
||||
LootSurveyTests.Register(runner);
|
||||
PropertyDumpTests.Register(runner);
|
||||
T11LootTests.Register(runner);
|
||||
MagItemDescriberTests.Register(runner);
|
||||
|
|
@ -86,6 +90,8 @@ internal static class Program
|
|||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
LootRetryTimingTests.Register(runner);
|
||||
LootClaimMismatchTests.Register(runner);
|
||||
LootNothingLineTests.Register(runner);
|
||||
ChestLootTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
UseRefusalTests.Register(runner);
|
||||
|
|
|
|||
|
|
@ -124,6 +124,7 @@ internal static class CommandReplyTests
|
|||
new(null, "/ra settings", K.Act),
|
||||
new(null, "/ra settings loadchar", K.Act),
|
||||
new(null, "/ra loot add banana", K.Act),
|
||||
new(null, "/ra loot why", K.Act), // nothing selected: says so
|
||||
new(null, "/ra lootparse", K.Act),
|
||||
new(null, "/ra lootcheckinv", K.Act),
|
||||
new(null, "/ra autotrade", K.Act),
|
||||
|
|
|
|||
300
Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs
Normal file
300
Tools/RynthCore.RynthAiHostTests/Tests/LootChatLineTests.cs
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-31, a player asked for loot details in chat "like magtools does": the looter's "Looted"
|
||||
// line of an item a loot rule took names the rule and the item's Mag-style details, in one line
|
||||
// (Item Info's "Describe looted items in chat", on by default). Salvage stays short unless
|
||||
// "Include salvage" is on, stackables (pyreals, notes, comps) keep the plain line, and the head stays
|
||||
// "[RynthAi] Looted [<action>] <name>" for the self-test meta. One corpse: a crossbow (Keep rule),
|
||||
// a helm (Salvage rule) and a stack of pyreals (Keep rule). The loot clock (CorpseClock) is moved by hand.
|
||||
internal static class LootChatLineTests
|
||||
{
|
||||
private const uint Player = 0x50000E51;
|
||||
private const uint Corpse = 0x80265100;
|
||||
private const uint Xbow = 0x80265101, Helm = 0x80265102, Coins = 0x80265103;
|
||||
private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100, ItemTypeArmor = 0x2, ItemTypeMoney = 0x40;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Loot Tester";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot chat: a looted keeper prints one line with its rule and its Mag-style details", KeeperDescribed);
|
||||
r.Add("loot chat: salvage is quiet by default, and short (material, workmanship) with Include salvage", SalvageQuietByDefault);
|
||||
r.Add("loot chat: pyreals, notes, comps and other stacks print the plain line only", StackablePlain);
|
||||
r.Add("loot chat: Describe looted items off prints the plain lines", SettingOffPlain);
|
||||
r.Add("loot chat: the settings survive a profile save and load, the settings map and /ra iteminfo loot", SettingsRoundTrip);
|
||||
}
|
||||
|
||||
private static long _now;
|
||||
|
||||
private static void Clocked(Action body)
|
||||
{
|
||||
var old = RynthAiPlugin.CorpseClock;
|
||||
_now = 70_000_000;
|
||||
RynthAiPlugin.CorpseClock = () => _now;
|
||||
try { body(); }
|
||||
finally { RynthAiPlugin.CorpseClock = old; }
|
||||
}
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone";
|
||||
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(Corpse);
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
|
||||
// A gold crossbow, identified: workmanship 6, crossbow, pierce, +22, +162%, 15% melee defense,
|
||||
// Legendary Blood Thirst.
|
||||
Item(Xbow, "Blunt Crossbow", ItemTypeMissile, (19, 12000), (5, 600), (131, 60), (105, 6), (353, 9), (45, 2), (204, 22));
|
||||
FakeHost.Doubles[(Xbow, 63)] = 2.62;
|
||||
FakeHost.Doubles[(Xbow, 29)] = 1.15;
|
||||
FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
|
||||
FakeHost.Appraised.Add(Xbow);
|
||||
|
||||
// A steel helm for salvage, identified: workmanship 5, AL 300.
|
||||
Item(Helm, "Helm", ItemTypeArmor, (19, 900), (5, 300), (131, 64), (105, 5), (28, 300));
|
||||
FakeHost.Appraised.Add(Helm);
|
||||
|
||||
// A stack of 50 pyreals.
|
||||
Item(Coins, "Pyreal", ItemTypeMoney, (19, 50), (11, 25000), (12, 50));
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint itemType, params (uint Key, int Value)[] ints)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = itemType;
|
||||
FakeHost.Containers[id] = Corpse;
|
||||
FakeHost.Ints[(id, 1)] = unchecked((int)itemType);
|
||||
foreach (var (k, v) in ints) FakeHost.Ints[(id, k)] = v;
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
|
||||
|
||||
var p = new VTankLootProfile();
|
||||
p.Rules.Add(Rule("Keep bows", VTankLootAction.Keep, AcObjectClass.MissileWeapon));
|
||||
p.Rules.Add(Rule("Salvage armor", VTankLootAction.Salvage, AcObjectClass.Armor));
|
||||
p.Rules.Add(Rule("Coins", VTankLootAction.Keep, AcObjectClass.Money));
|
||||
string path = Path.Combine(Program.TempRoot, "loot-chat-line.utl");
|
||||
File.WriteAllText(path, VTankLootWriter.Serialize(p));
|
||||
S.CurrentLootPath = path;
|
||||
}
|
||||
|
||||
private static VTankLootRule Rule(string name, VTankLootAction action, AcObjectClass cls)
|
||||
{
|
||||
var rule = new VTankLootRule { Name = name, Action = action };
|
||||
rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { ((int)cls).ToString() }));
|
||||
return rule;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public void Tick()
|
||||
{
|
||||
Set("_activity", BotActivity.Looting);
|
||||
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
|
||||
}
|
||||
public bool Completed(uint corpse) =>
|
||||
Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
|
||||
}
|
||||
|
||||
/// <summary>Opens the corpse and loots it, each item landing in the main pack as soon as its move goes out.</summary>
|
||||
private static List<string> LootCorpse(Action<MagItemInfoSettings>? configure = null)
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
configure?.Invoke(bot.S.ItemInfoSettings);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
foreach (uint id in new[] { Xbow, Helm, Coins }) bot.Cache.OnCreateObject(id);
|
||||
bot.Cache.Tick();
|
||||
bot.Tick();
|
||||
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
|
||||
var landed = new HashSet<uint>();
|
||||
for (int i = 0; i < 3000 && !(bot.Completed(Corpse) && landed.Count == 3); i++)
|
||||
{
|
||||
foreach (var m in FakeHost.ExternalMoves)
|
||||
if (landed.Add(m.Id)) FakeHost.Containers[m.Id] = Player;
|
||||
_now += 20;
|
||||
bot.Tick();
|
||||
}
|
||||
List<string> looted = FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] Looted [", StringComparison.Ordinal)).ToList();
|
||||
Check.Eq(looted.Count, 3, "one Looted line per item: " + string.Join(" | ", looted));
|
||||
Check.False(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi Item]", StringComparison.Ordinal)), "no separate item info lines");
|
||||
return looted;
|
||||
}
|
||||
|
||||
private static string LineFor(List<string> looted, string name) =>
|
||||
looted.SingleOrDefault(l => l.Contains("] " + name, StringComparison.Ordinal)) ?? "(none)";
|
||||
|
||||
private static void KeeperDescribed() => Clocked(() =>
|
||||
{
|
||||
List<string> looted = LootCorpse();
|
||||
string line = LineFor(looted, "Blunt Crossbow");
|
||||
Check.True(line.StartsWith("[RynthAi] Looted [Keep] Blunt Crossbow (rule \"Keep bows\"): Gold, Pierce Crossbow, ", StringComparison.Ordinal),
|
||||
"the head, the rule, material and type: " + line);
|
||||
foreach (string part in new[] { "+22", "+162%", "+15%md", "Legendary Blood Thirst", "Craft 6" })
|
||||
Check.True(line.Contains(part, StringComparison.Ordinal), $"'{part}' in: {line}");
|
||||
Check.False(line.Contains('\n'), "one line");
|
||||
Check.False(line.Contains("not IDed"), "identified");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Looted [Keep] Blunt Crossbow")), 1, "said once");
|
||||
|
||||
// The Item Info field settings apply: spells hidden, no spells on the loot line either.
|
||||
looted = LootCorpse(s => s.SetHidden(MagItemInfoField.Spells, true));
|
||||
line = LineFor(looted, "Blunt Crossbow");
|
||||
Check.False(line.Contains("Blood Thirst"), "a hidden field stays hidden: " + line);
|
||||
Check.True(line.Contains("+22"), "the rest still shows: " + line);
|
||||
});
|
||||
|
||||
private static void SalvageQuietByDefault() => Clocked(() =>
|
||||
{
|
||||
List<string> looted = LootCorpse();
|
||||
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm", "salvage keeps the short line by default");
|
||||
|
||||
looted = LootCorpse(s => s.LootChatSalvage = true);
|
||||
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm (rule \"Salvage armor\"): Steel, Craft 5",
|
||||
"Include salvage: the rule, material and workmanship only (no AL)");
|
||||
});
|
||||
|
||||
private static void StackablePlain() => Clocked(() =>
|
||||
{
|
||||
List<string> looted = LootCorpse(s => s.LootChatSalvage = true);
|
||||
Check.Eq(LineFor(looted, "Pyreal"), "[RynthAi] Looted [Keep] Pyreal", "a pyreal stack keeps the plain line");
|
||||
|
||||
// Notes and comps by class, any other stack by its stack size; a single unstackable item is described.
|
||||
var s = new MagItemInfoSettings { LootChatSalvage = true };
|
||||
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, false, AcObjectClass.TradeNote), LootChatLine.Detail.None, "trade note");
|
||||
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, false, AcObjectClass.SpellComponent), LootChatLine.Detail.None, "spell component");
|
||||
Check.Eq(LootChatLine.DetailFor(s, "Keep", false, true, AcObjectClass.Gem), LootChatLine.Detail.None, "a stack of gems");
|
||||
Check.Eq(LootChatLine.DetailFor(s, "KeepUpTo", false, false, AcObjectClass.Gem), LootChatLine.Detail.Full, "one gem (Keep #)");
|
||||
Check.Eq(LootChatLine.DetailFor(s, "Recover", false, false, AcObjectClass.Armor), LootChatLine.Detail.None, "own corpse recovery: no rule, plain");
|
||||
Check.Eq(LootChatLine.DetailFor(s, "ManaTap", false, false, AcObjectClass.Armor), LootChatLine.Detail.None, "mana tap built-in: plain");
|
||||
});
|
||||
|
||||
private static void SettingOffPlain() => Clocked(() =>
|
||||
{
|
||||
List<string> looted = LootCorpse(s => { s.LootChat = false; s.LootChatSalvage = true; });
|
||||
Check.Eq(LineFor(looted, "Blunt Crossbow"), "[RynthAi] Looted [Keep] Blunt Crossbow", "keeper: plain");
|
||||
Check.Eq(LineFor(looted, "Helm"), "[RynthAi] Looted [Salvage] Helm", "salvage: plain");
|
||||
Check.Eq(LineFor(looted, "Pyreal"), "[RynthAi] Looted [Keep] Pyreal", "pyreals: plain");
|
||||
});
|
||||
|
||||
private static void SettingsRoundTrip()
|
||||
{
|
||||
var fresh = new MagItemInfoSettings();
|
||||
Check.True(fresh.LootChat, "Describe looted items in chat is on by default");
|
||||
Check.False(fresh.LootChatSalvage, "Include salvage is off by default");
|
||||
Check.Eq(fresh.LootChatType, MagItemInfoSettings.SameAsHeader, "loot lines use the Item Info chat type by default");
|
||||
Check.Eq(LootChatLine.ChatTypeOf(new MagItemInfoSettings { ChatType = 7 }), 7, "...which is ChatType");
|
||||
|
||||
// Profile: save, load (CopySettings), save again unchanged.
|
||||
var saved = new LegacyUiSettings();
|
||||
saved.ItemInfoSettings.LootChat = false;
|
||||
saved.ItemInfoSettings.LootChatSalvage = true;
|
||||
saved.ItemInfoSettings.LootChatType = 24;
|
||||
string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
|
||||
.Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live });
|
||||
Check.False(live.ItemInfoSettings.LootChat, "loot chat off survives");
|
||||
Check.True(live.ItemInfoSettings.LootChatSalvage, "include salvage survives");
|
||||
Check.Eq(live.ItemInfoSettings.LootChatType, 24, "loot chat type survives");
|
||||
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged");
|
||||
|
||||
// A profile from before the setting: on.
|
||||
var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
|
||||
var infoKey = doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase));
|
||||
var info = doc[infoKey]!.AsObject();
|
||||
var lootKey = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("LootChat", StringComparison.OrdinalIgnoreCase));
|
||||
Check.True(lootKey != null, "the field is in the profile JSON");
|
||||
if (lootKey != null) info.Remove(lootKey);
|
||||
string old = doc.ToJsonString();
|
||||
var oldLoaded = JsonSerializer.Deserialize(old, RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.True(oldLoaded.ItemInfoSettings.LootChat, "a profile without it loads it on");
|
||||
|
||||
// Reset all to defaults covers them; Sanitize clamps a hand-edited chat type.
|
||||
saved.ItemInfoSettings.ResetToDefaults();
|
||||
Check.True(saved.ItemInfoSettings.LootChat && !saved.ItemInfoSettings.LootChatSalvage
|
||||
&& saved.ItemInfoSettings.LootChatType == MagItemInfoSettings.SameAsHeader, "reset restores the loot options");
|
||||
saved.ItemInfoSettings.LootChatType = 99;
|
||||
saved.ItemInfoSettings.Sanitize();
|
||||
Check.Eq(saved.ItemInfoSettings.LootChatType, MagItemInfoSettings.SameAsHeader, "an out-of-range chat type is cleared");
|
||||
|
||||
// The settings map (metas: vtsetsetting / ragetsetting).
|
||||
var mapSettings = new LegacyUiSettings();
|
||||
var e = ExpressionTests.Engine(settings: mapSettings);
|
||||
Check.Eq(e.Evaluate("ragetsetting[ItemInfoLootChat]"), "1", "map reads it");
|
||||
Check.Eq(e.Evaluate("rasetsetting[ItemInfoLootChat, 0]"), "1", "map sets it");
|
||||
Check.False(mapSettings.ItemInfoSettings.LootChat, "off through the map");
|
||||
e.Evaluate("rasetsetting[ItemInfoLootSalvage, 1]");
|
||||
Check.True(mapSettings.ItemInfoSettings.LootChatSalvage, "include salvage through the map");
|
||||
|
||||
// /ra iteminfo loot on|off answers, and changes the setting.
|
||||
FakeHost.Reset();
|
||||
var bot = new Bot(FakeHost.Create(Player));
|
||||
void Cmd(params string[] words) => typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!
|
||||
.Invoke(bot.P, new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() });
|
||||
Cmd("loot", "off");
|
||||
Check.False(bot.S.ItemInfoSettings.LootChat, "/ra iteminfo loot off");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot: OFF (salvage OFF)"), "replies: " + string.Join(" | ", FakeHost.Chat));
|
||||
Cmd("loot", "on");
|
||||
Check.True(bot.S.ItemInfoSettings.LootChat, "/ra iteminfo loot on");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot: ON (salvage OFF)"), "replies on");
|
||||
Cmd("loot", "salvage", "on");
|
||||
Check.True(bot.S.ItemInfoSettings.LootChatSalvage, "/ra iteminfo loot salvage on");
|
||||
Check.True(FakeHost.Chat.Any(c => c == "[RynthAi] Item info on loot, salvage: ON"), "replies salvage");
|
||||
FakeHost.Chat.Clear();
|
||||
Cmd("loot", "maybe");
|
||||
Check.True(bot.S.ItemInfoSettings.LootChat, "a bad word changes nothing");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Usage: /ra iteminfo loot on|off")), "and gets the usage: " + string.Join(" | ", FakeHost.Chat));
|
||||
}
|
||||
}
|
||||
291
Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs
Normal file
291
Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// R-20261031-203155-cea0 (Conquest, indoors, RynthAi 2026.10.31.1): "Plugin says its looting but it
|
||||
// doesn't." The arbiter logged Looting with want[loot=True] for 12 s after a kill, and not one
|
||||
// "Corpse loot:" line followed (no [LootSettings] line the whole session either). Boost Nav Priority
|
||||
// was on with no route to run: the arbiter's BoostNav clause is guarded by WantNav, so Looting won,
|
||||
// while TickCorpseOpening's full stop took the flag alone and reset every claim. Owner's rule
|
||||
// (2026-10-31): Boost Nav Priority means no looting at all, so HasLootWork offers nothing either. The kill's corpse
|
||||
// ('Treasure of ...', no corpse name) was first filed as a no-position inventory Container and
|
||||
// rescued to Corpse by its weenie flag 3 s later; it must be claimed and looted like any other.
|
||||
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand; the server answers at once.
|
||||
internal static class LootClaimMismatchTests
|
||||
{
|
||||
private const uint Player = 0x50000D51;
|
||||
private const uint Corpse = 0x80265100;
|
||||
private const uint Gem = 0x80265101;
|
||||
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
|
||||
private const uint BfCorpse = 0x2000;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Test Hunter";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const long TickMs = 25;
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x482D0102u, 40f, 60f, 0f);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot claim (R-20261031-203155-cea0): a corpse first filed as a no-position inventory Container, then rescued, is claimed and looted", RescuedCorpseLooted);
|
||||
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with no route: no loot work, never in Looting; looted once the flag is off", BoostNavNoRouteLoots);
|
||||
r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with a route, then none: nav has the tick, nothing claimed either way", BoostNavWithRouteYields);
|
||||
r.Add("loot claim (R-20261031-203155-cea0): Looting with nothing claimed is logged with the reason after 3 s, then throttled", LootStallLogged);
|
||||
}
|
||||
|
||||
// ── Clock and world ───────────────────────────────────────────────────────
|
||||
|
||||
private static long _now;
|
||||
|
||||
private static void Clocked(Action body)
|
||||
{
|
||||
var old = RynthAiPlugin.CorpseClock;
|
||||
_now = 80_000_000;
|
||||
RynthAiPlugin.CorpseClock = () => _now;
|
||||
try { body(); }
|
||||
finally { RynthAiPlugin.CorpseClock = old; }
|
||||
}
|
||||
|
||||
/// <summary>The report's corpse: its name is no corpse name, and it is created before its
|
||||
/// position and weenie flag read (the "nopos-item" branch files it as an inventory Container).</summary>
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Bitfields[Player] = 0; // installs GetObjectBitfield; the corpse's flag reads 0 for now
|
||||
FakeHost.Names[Corpse] = "Treasure of Corrupted Dread";
|
||||
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(Corpse);
|
||||
FakeHost.Names[Gem] = "Black Opal";
|
||||
FakeHost.ItemTypes[Gem] = ItemTypeGem;
|
||||
FakeHost.Containers[Gem] = Corpse; // also installs GetObjectOwnershipInfo
|
||||
FakeHost.Appraised.Add(Gem);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
private int _seenMoves;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "loot-claim-mismatch.json");
|
||||
var p = new LootProfile { Name = "gems" };
|
||||
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
|
||||
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
p.Rules.Add(rule);
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
|
||||
public bool HasLootWork() => (bool)Call("HasLootWork", S, _now)!;
|
||||
public bool NavWants() => (bool)Call("NavWantsTick", S)!;
|
||||
|
||||
/// <summary>The arbiter's decision from the real wants, as OnTick builds it (no buffing, no combat).</summary>
|
||||
public BotActivity Decide()
|
||||
{
|
||||
var inputs = new ArbiterInputs(S.IsMacroRunning, false, false, HasLootWork(), false, NavWants(),
|
||||
boostNav: S.BoostNavPriority, boostLoot: S.BoostLootPriority);
|
||||
return ActivityArbiter.Decide(in inputs);
|
||||
}
|
||||
|
||||
/// <summary>One plugin tick: the clock moves on, the arbiter decides, the looter runs, and
|
||||
/// the server lands each move in the pack at once.</summary>
|
||||
public BotActivity Tick()
|
||||
{
|
||||
_now += TickMs;
|
||||
BotActivity act = Decide();
|
||||
Set("_activity", act);
|
||||
Call("TickCorpseOpening");
|
||||
while (_seenMoves < FakeHost.ExternalMoves.Count)
|
||||
{
|
||||
var m = FakeHost.ExternalMoves[_seenMoves++];
|
||||
FakeHost.Containers[m.Id] = m.Target;
|
||||
}
|
||||
return act;
|
||||
}
|
||||
|
||||
public bool Completed => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
public int Claimed => Get<int>("_targetCorpseId");
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
private static int LoggedCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
/// <summary>The corpse created without a position or flag (filed as inventory), then its
|
||||
/// position and flag land and the 2 s pass rescues it.</summary>
|
||||
private static Bot RescuedCorpse()
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.OnCreateObject(Gem);
|
||||
for (int i = 0; i < 20; i++) bot.Cache.Tick();
|
||||
Check.Eq(bot.Cache[unchecked((int)Corpse)]?.ObjectClass, AcObjectClass.Container, "first filed as a Container (the report's state)");
|
||||
Check.True(bot.Cache.GetInventory().Any(o => o.Id == unchecked((int)Corpse)), "in the inventory");
|
||||
Check.False(bot.HasLootWork(), "no loot work while it sits in the inventory");
|
||||
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
FakeHost.Bitfields[Corpse] = BfCorpse;
|
||||
typeof(WorldObjectCache).GetField("_lastReclassifyTime", Any)!.SetValue(bot.Cache, DateTime.MinValue);
|
||||
bot.Cache.Tick();
|
||||
Check.True(Logged("was filed as Container (inventory, no position when classified); now a Corpse"), "the rescue is logged as in the report");
|
||||
Check.Eq(bot.Cache[unchecked((int)Corpse)]?.ObjectClass, AcObjectClass.Corpse, "rescued to Corpse");
|
||||
Check.True(bot.Cache.GetLandscapeObjects().Any(o => o.Id == unchecked((int)Corpse)), "on the landscape");
|
||||
return bot;
|
||||
}
|
||||
|
||||
/// <summary>Ticks to the end of the corpse; the server opens it on the first use.</summary>
|
||||
private static void LootToTheEnd(Bot bot)
|
||||
{
|
||||
long end = _now + 30_000;
|
||||
bool opened = false;
|
||||
while (_now < end && !bot.Completed)
|
||||
{
|
||||
bot.Tick();
|
||||
if (!opened && FakeHost.Uses.Contains(Corpse))
|
||||
{
|
||||
opened = true;
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 1. The rescued corpse ─────────────────────────────────────────────────
|
||||
|
||||
private static void RescuedCorpseLooted() => Clocked(() =>
|
||||
{
|
||||
World();
|
||||
var bot = RescuedCorpse();
|
||||
Check.True(bot.HasLootWork(), "the arbiter counts it as loot work");
|
||||
Check.Eq(bot.Tick(), BotActivity.Looting, "Looting has the tick");
|
||||
Check.Eq(bot.Claimed, unchecked((int)Corpse), "and the claim takes the rescued corpse");
|
||||
Check.True(Logged("claimed corpse target 0x80265100"), "claim logged");
|
||||
|
||||
LootToTheEnd(bot);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is moved into the pack");
|
||||
Check.True(bot.Completed, "the corpse is finished");
|
||||
Check.False(bot.HasLootWork(), "no loot work left: the bot leaves Looting");
|
||||
});
|
||||
|
||||
// ── 2. The report: Boost Nav Priority on, nothing to navigate ─────────────
|
||||
|
||||
// Owner, 2026-10-31: Boost Nav Priority means no looting at all, route or not.
|
||||
private static void BoostNavNoRouteLoots() => Clocked(() =>
|
||||
{
|
||||
World();
|
||||
var bot = RescuedCorpse();
|
||||
bot.S.BoostNavPriority = true;
|
||||
bot.S.BoostLootPriority = true; // both on, as in the report: nav wins
|
||||
bot.S.EnableNavigation = true; // on, but no route loaded (want[nav=False] in the report)
|
||||
Check.False(bot.NavWants(), "nav has nothing to run");
|
||||
Check.False(bot.HasLootWork(), "Boost Nav Priority: no loot work, the corpse is passed by");
|
||||
Check.True(bot.Decide() != BotActivity.Looting, "the arbiter never gives Looting the tick");
|
||||
|
||||
for (int i = 0; i < 200; i++) Check.True(bot.Tick() != BotActivity.Looting, "never in Looting (5 s)");
|
||||
Check.Eq(bot.Claimed, 0, "nothing claimed");
|
||||
Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened");
|
||||
Check.False(Logged("Looting has held the tick"), "no stall: Looting never had the tick");
|
||||
|
||||
bot.S.BoostNavPriority = false; // the flag off: the corpse is looted as usual
|
||||
Check.True(bot.HasLootWork(), "loot work again");
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Claimed, unchecked((int)Corpse), "the corpse is claimed");
|
||||
LootToTheEnd(bot);
|
||||
Check.True(bot.Completed, "looted to the end");
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is in the pack");
|
||||
});
|
||||
|
||||
// ── 3. Boost Nav Priority with a route still yields to nav ────────────────
|
||||
|
||||
private static void BoostNavWithRouteYields() => Clocked(() =>
|
||||
{
|
||||
World();
|
||||
var bot = RescuedCorpse();
|
||||
bot.S.BoostNavPriority = true;
|
||||
bot.S.EnableNavigation = true;
|
||||
var route = new NavRouteParser { RouteType = NavRouteType.Linear };
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 10.5, EW = -3.25 });
|
||||
route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 11.5, EW = -4.25 });
|
||||
bot.S.CurrentRoute = route;
|
||||
Check.True(bot.NavWants(), "nav has a route to run");
|
||||
Check.False(bot.HasLootWork(), "no loot work to offer: the looter stands down for the route");
|
||||
Check.Eq(bot.Decide(), BotActivity.Navigating, "nav has the tick");
|
||||
|
||||
for (int i = 0; i < 200; i++) bot.Tick(); // 5 s
|
||||
Check.Eq(bot.Claimed, 0, "nothing claimed");
|
||||
Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened");
|
||||
Check.False(Logged("Looting has held the tick"), "not a Looting stall: Looting never had the tick");
|
||||
|
||||
bot.S.CurrentRoute = null; // the route is unloaded: still no looting while the flag is on
|
||||
Check.True(bot.Tick() != BotActivity.Looting, "no route, flag on: still no Looting");
|
||||
Check.Eq(bot.Claimed, 0, "still nothing claimed");
|
||||
});
|
||||
|
||||
// ── 4. A stall is never silent ────────────────────────────────────────────
|
||||
|
||||
private static void LootStallLogged() => Clocked(() =>
|
||||
{
|
||||
World();
|
||||
var bot = RescuedCorpse();
|
||||
bot.Set("_lootHaltUntil", _now + 60_000); // the loot-wedge halt: no claim while the corpse waits in range
|
||||
const string Stall = "Looting has held the tick";
|
||||
|
||||
Check.Eq(bot.Tick(), BotActivity.Looting, "the corpse in range gives Looting the tick");
|
||||
Check.Eq(bot.Claimed, 0, "nothing claimed");
|
||||
for (int i = 0; i < (int)(RynthAiPlugin.LootStallLogMs / TickMs) - 10; i++) bot.Tick();
|
||||
Check.False(Logged(Stall), "a short gap is not a stall");
|
||||
for (int i = 0; i < 20; i++) bot.Tick();
|
||||
Check.Eq(LoggedCount(Stall), 1, "past LootStallLogMs the stall is logged once");
|
||||
string line = FakeHost.Logs.First(l => l.Contains(Stall, StringComparison.Ordinal));
|
||||
Check.True(line.Contains("loot-wedge halt"), $"with the claim's skip reason ({line})");
|
||||
Check.True(line.Contains("loot work: 1 lootable corpse(s) in range, e.g. 0x80265100"), $"and what the arbiter counted as loot work ({line})");
|
||||
|
||||
for (int i = 0; i < 200; i++) bot.Tick(); // 5 s more
|
||||
Check.Eq(LoggedCount(Stall), 1, "throttled: not again within LootStallRepeatMs");
|
||||
for (int i = 0; i < (int)(RynthAiPlugin.LootStallRepeatMs / TickMs); i++) bot.Tick();
|
||||
Check.Eq(LoggedCount(Stall), 2, "logged again after LootStallRepeatMs");
|
||||
|
||||
bot.Set("_lootHaltUntil", 0L);
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Claimed, unchecked((int)Corpse), "once the halt ends the corpse is claimed");
|
||||
Check.True(Logged("the Looting stall is over"), "and the end of the stall is logged");
|
||||
});
|
||||
}
|
||||
180
Tools/RynthCore.RynthAiHostTests/Tests/LootLateIdTests.cs
Normal file
180
Tools/RynthCore.RynthAiHostTests/Tests/LootLateIdTests.cs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-31, the corpse looter with LootSnob (Fixtures\lootsnob-excerpt.utl plus a Salvage rule
|
||||
// on gold alone): a crossbow whose ID is late is held, asked for again, and in the end left on the
|
||||
// corpse; it is never judged without its ID, where its stats read 0 and the gold rule took it
|
||||
// ("best-effort" after the wait, until today). One whose ID comes in time is kept by its rule.
|
||||
// The loot clock (CorpseClock) is moved by hand.
|
||||
internal static class LootLateIdTests
|
||||
{
|
||||
private const uint Player = 0x50000D41;
|
||||
private const uint Corpse = 0x80264100;
|
||||
private const uint Xbow = 0x80264101;
|
||||
private const uint ItemTypeContainer = 0x200, ItemTypeMissile = 0x100;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Ilsa Corvane";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot late ID: a crossbow whose ID never comes is held, asked again, then left - never the Salvage rule", IdNeverComes);
|
||||
r.Add("loot late ID: a crossbow whose ID comes after the wait is kept by its LootSnob rule", IdComesLate);
|
||||
}
|
||||
|
||||
private static long _now;
|
||||
|
||||
private static void Clocked(Action body)
|
||||
{
|
||||
var old = RynthAiPlugin.CorpseClock;
|
||||
_now = 60_000_000;
|
||||
RynthAiPlugin.CorpseClock = () => _now;
|
||||
try { body(); }
|
||||
finally { RynthAiPlugin.CorpseClock = old; }
|
||||
}
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Drone";
|
||||
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(Corpse);
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
// What the CreateObject shows: name, type, slot, value, burden, material (gold).
|
||||
FakeHost.Names[Xbow] = "Blunt Crossbow";
|
||||
FakeHost.ItemTypes[Xbow] = ItemTypeMissile;
|
||||
FakeHost.Containers[Xbow] = Corpse;
|
||||
foreach (var (k, v) in new (uint, int)[] { (1, 0x100), (9, 0x00400000), (19, 12000), (5, 600), (131, 60) })
|
||||
FakeHost.Ints[(Xbow, k)] = v;
|
||||
}
|
||||
|
||||
/// <summary>The ID lands: workmanship, weapon type, wield, +22, damage mod 2.62, Legendary Blood Thirst.</summary>
|
||||
private static void Identify()
|
||||
{
|
||||
foreach (var (k, v) in new (uint, int)[] { (105, 6), (353, 9), (158, 2), (159, 47), (160, 385), (204, 22), (45, 4), (48, 47) })
|
||||
FakeHost.Ints[(Xbow, k)] = v;
|
||||
FakeHost.Doubles[(Xbow, 63)] = 2.62;
|
||||
FakeHost.Doubles[(Xbow, 29)] = 1.15;
|
||||
FakeHost.SpellIds[Xbow] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
|
||||
FakeHost.Appraised.Add(Xbow);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
LootAssessWindowMs = 200, LootCorpseTimeoutMs = 12_000,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
|
||||
|
||||
// LootSnob's excerpt and, last, a Salvage rule on gold alone (no workmanship), so the
|
||||
// crossbow judged without its ID would be salvaged.
|
||||
VTankLootProfile p = VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
|
||||
var gold = new VTankLootRule { Name = "Gold any", Action = VTankLootAction.Salvage };
|
||||
gold.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyE, "0", new[] { "60", "131" }));
|
||||
p.Rules.Add(gold);
|
||||
string path = Path.Combine(Program.TempRoot, "loot-late-id.utl");
|
||||
File.WriteAllText(path, VTankLootWriter.Serialize(p));
|
||||
S.CurrentLootPath = path;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public void Tick()
|
||||
{
|
||||
Set("_activity", BotActivity.Looting);
|
||||
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(P, null);
|
||||
}
|
||||
public void TickFor(long ms)
|
||||
{
|
||||
long end = _now + ms;
|
||||
while (_now < end) { _now += 20; Tick(); }
|
||||
}
|
||||
public bool Completed(uint corpse) =>
|
||||
Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)corpse));
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
private static bool Moved() => FakeHost.ExternalMoves.Any(m => m.Id == Xbow);
|
||||
|
||||
private static Bot OpenCorpse()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.OnCreateObject(Xbow);
|
||||
bot.Cache.Tick();
|
||||
bot.Tick();
|
||||
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.TickFor(100);
|
||||
Check.True(FakeHost.IdRequests.Contains(Xbow), "the crossbow's ID is asked for (a LootSnob rule that could take it needs it)");
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static void IdNeverComes() => Clocked(() =>
|
||||
{
|
||||
var bot = OpenCorpse();
|
||||
bot.TickFor(4_000); // past the assess window and AppraisalWaitMs
|
||||
Check.False(Moved(), "not taken without its ID (the old best-effort took it for Gold salvage)");
|
||||
Check.True(FakeHost.IdRequests.Count(id => id == Xbow) >= 2, "its ID is asked for again");
|
||||
Check.True(Logged("no ID yet and a rule that decides it needs one"), "and that is logged");
|
||||
|
||||
for (int i = 0; i < 1000 && !bot.Completed(Corpse); i++) { _now += 20; bot.Tick(); }
|
||||
Check.False(Moved(), "still not taken when the corpse is given up");
|
||||
Check.True(Logged("left: no ID came, and a rule that decides it needs one"), "left on the corpse, and said why");
|
||||
Check.True(bot.Completed(Corpse), "the corpse is finished");
|
||||
Check.False(FakeHost.Chat.Any(c => c.Contains("Gold any")), "the Salvage rule never named");
|
||||
});
|
||||
|
||||
private static void IdComesLate() => Clocked(() =>
|
||||
{
|
||||
var bot = OpenCorpse();
|
||||
bot.TickFor(5_000); // later than the old wait gave it
|
||||
Check.False(Moved(), "held while the ID is out");
|
||||
Identify();
|
||||
for (int i = 0; i < 200 && !Moved(); i++) { _now += 20; bot.Tick(); }
|
||||
Check.True(Moved(), "taken once the ID is in");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Loot rule: Blunt Crossbow -> [Keep] (M) Xbow (OD +9)")),
|
||||
"by LootSnob's Xbow (OD +9) (chat: " + string.Join(" | ", FakeHost.Chat.Where(c => c.Contains("Loot rule"))) + ")");
|
||||
});
|
||||
}
|
||||
249
Tools/RynthCore.RynthAiHostTests/Tests/LootNothingLineTests.cs
Normal file
249
Tools/RynthCore.RynthAiHostTests/Tests/LootNothingLineTests.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Owner, 2026-10-31: a corpse or chest whose only matching items were Keep # (or mana-stone)
|
||||
// items already at their count ended with just "Keep # '<rule>': have N/N — leaving <item>." and
|
||||
// never a "nothing to loot" line: "It should report nothing to loot as well." The end-of-container
|
||||
// line now counts confirmed pickups, not matches (NothingLootedLine).
|
||||
// The loot clock (CorpseOpenController.CorpseClock) is moved by hand; the server answers at once.
|
||||
internal static class LootNothingLineTests
|
||||
{
|
||||
private const uint Player = 0x50000D61;
|
||||
private const uint Corpse = 0x80266100;
|
||||
private const uint Chest = 0x7A9B6001; // a landblock chest (static id)
|
||||
private const uint Gem = 0x80266101;
|
||||
private const uint PackGem = 0x80266102; // one already in the pack: the Keep # 1 is met
|
||||
private const uint Stone = 0x80266103, PackStone = 0x80266104;
|
||||
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800, ItemTypeManaStone = 0x80000;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Test Hunter";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const long TickMs = 25;
|
||||
private const string Enough = "item(s) match, but you already have enough.";
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nothing to loot: a corpse whose only match is a Keep # at its count ends with 'you already have enough'", CappedCorpseSaysNothingToLoot);
|
||||
r.Add("nothing to loot: a corpse with a looted item says no 'nothing to loot'", LootedCorpseSaysNothing);
|
||||
r.Add("nothing to loot: a chest whose only match is a Keep # at its count ends with 'you already have enough'", CappedChestSaysNothingToLoot);
|
||||
r.Add("nothing to loot: a corpse with no matching item keeps 'matches the loot profile'", NoMatchKeepsOldLine);
|
||||
r.Add("nothing to loot: a corpse whose only match is a mana stone at its keep count ends with 'you already have enough'", CappedManaStoneSaysNothingToLoot);
|
||||
}
|
||||
|
||||
// ── Clock and world ───────────────────────────────────────────────────────
|
||||
|
||||
private static long _now;
|
||||
|
||||
private static void Clocked(Action body)
|
||||
{
|
||||
var old = RynthAiPlugin.CorpseClock;
|
||||
_now = 90_000_000;
|
||||
RynthAiPlugin.CorpseClock = () => _now;
|
||||
try { body(); }
|
||||
finally { RynthAiPlugin.CorpseClock = old; }
|
||||
}
|
||||
|
||||
private static void World(bool chest, bool gemInPack)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
|
||||
FakeHost.ContentsCalls = true; // GetContainerContents: the Keep # count walks the pack
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
uint box = chest ? Chest : Corpse;
|
||||
FakeHost.Names[box] = chest ? "Chest" : "Corpse of Brier Wasp";
|
||||
FakeHost.ItemTypes[box] = ItemTypeContainer;
|
||||
FakeHost.Positions[box] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
FakeHost.NotAttackable.Add(box);
|
||||
if (chest) FakeHost.Containers[Chest] = 0; // lies in the world
|
||||
else FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
|
||||
AddGem(Gem, "Black Opal", box);
|
||||
if (gemInPack) AddGem(PackGem, "Black Opal", Player);
|
||||
}
|
||||
|
||||
private static void AddGem(uint id, string name, uint container)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = ItemTypeGem;
|
||||
FakeHost.Containers[id] = container;
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
public readonly RynthCoreHost Host;
|
||||
private int _seenMoves;
|
||||
|
||||
/// <param name="keepOne">Gems are Keep # 1; otherwise the profile wants only armor.</param>
|
||||
public Bot(RynthCoreHost host, bool keepOne)
|
||||
{
|
||||
Host = host;
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 });
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, keepOne ? "loot-nothing-keep1.json" : "loot-nothing-armor.json");
|
||||
var p = new LootProfile { Name = "nothing-line" };
|
||||
var rule = keepOne
|
||||
? new LootRule { Name = "Gems", Action = LootAction.KeepUpTo, KeepCount = 1 }
|
||||
: new LootRule { Name = "Armor", Action = LootAction.Keep };
|
||||
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = keepOne ? AcObjectClass.Gem : AcObjectClass.Armor });
|
||||
p.Rules.Add(rule);
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
|
||||
/// <summary>One Looting tick; the server lands each move in the pack at once.</summary>
|
||||
public void Tick()
|
||||
{
|
||||
_now += TickMs;
|
||||
Set("_activity", BotActivity.Looting);
|
||||
Call("TickCorpseOpening");
|
||||
while (_seenMoves < FakeHost.ExternalMoves.Count)
|
||||
{
|
||||
var m = FakeHost.ExternalMoves[_seenMoves++];
|
||||
FakeHost.Containers[m.Id] = m.Target;
|
||||
}
|
||||
}
|
||||
|
||||
public void Create(params uint[] ids)
|
||||
{
|
||||
foreach (uint id in ids) Cache.OnCreateObject(id);
|
||||
for (int i = 0; i < 5; i++) Cache.Tick();
|
||||
}
|
||||
|
||||
public bool CorpseDone => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
}
|
||||
|
||||
private static bool Said(string part) => FakeHost.Chat.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
private static string ChatDump() => string.Join(" | ", FakeHost.Chat);
|
||||
|
||||
/// <summary>Claims, opens (the server's ViewContents) and loots the corpse to its end.</summary>
|
||||
private static Bot LootCorpse(bool keepOne, bool gemInPack, Action<Bot>? setUp = null, params uint[] extra)
|
||||
{
|
||||
World(chest: false, gemInPack);
|
||||
foreach (uint id in extra)
|
||||
{
|
||||
FakeHost.Names[id] = "Mana Stone";
|
||||
FakeHost.ItemTypes[id] = ItemTypeManaStone;
|
||||
FakeHost.Containers[id] = id == PackStone ? Player : Corpse;
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host, keepOne);
|
||||
setUp?.Invoke(bot);
|
||||
var ids = new List<uint> { Corpse, Gem };
|
||||
if (gemInPack) ids.Add(PackGem);
|
||||
ids.AddRange(extra);
|
||||
bot.Create(ids.ToArray());
|
||||
long end = _now + 30_000;
|
||||
bool opened = false;
|
||||
while (_now < end && !bot.CorpseDone)
|
||||
{
|
||||
bot.Tick();
|
||||
if (!opened && FakeHost.Uses.Contains(Corpse))
|
||||
{
|
||||
opened = true;
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.GroundContainer = Corpse;
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.P.OnUpdateObjectInventory(Corpse);
|
||||
}
|
||||
}
|
||||
Check.True(opened, "the corpse is opened");
|
||||
Check.True(bot.CorpseDone, "the corpse is finished");
|
||||
return bot;
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void CappedCorpseSaysNothingToLoot() => Clocked(() =>
|
||||
{
|
||||
LootCorpse(keepOne: true, gemInPack: true);
|
||||
Check.True(Said("Keep # 'Gems': have 1/1"), $"the Keep # leave is said as before ({ChatDump()})");
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem is left");
|
||||
Check.True(Said("[RynthAi] Nothing to loot on Corpse of Brier Wasp: 1 " + Enough), $"and the end says there was nothing to loot ({ChatDump()})");
|
||||
Check.False(Said("matches the loot profile"), "not 'nothing matches': the gem did match");
|
||||
});
|
||||
|
||||
private static void LootedCorpseSaysNothing() => Clocked(() =>
|
||||
{
|
||||
LootCorpse(keepOne: true, gemInPack: false);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem && m.Target == Player), "the gem is looted (none in the pack yet)");
|
||||
Check.True(Said("Looted [KeepUpTo] Black Opal"), $"and said ({ChatDump()})");
|
||||
Check.False(Said("Nothing to loot"), "no 'nothing to loot' line");
|
||||
Check.False(Said("matches the loot profile"), "nor 'nothing matches'");
|
||||
});
|
||||
|
||||
private static void CappedChestSaysNothingToLoot() => Clocked(() =>
|
||||
{
|
||||
World(chest: true, gemInPack: true);
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host, keepOne: true);
|
||||
bot.Create(Chest, Gem, PackGem);
|
||||
FakeHost.GroundContainer = Chest; // the player opened it
|
||||
bot.P.OnViewObjectContents(Chest);
|
||||
bot.P.OnUpdateObjectInventory(Chest);
|
||||
long end = _now + 30_000;
|
||||
while (_now < end && !FakeHost.Closes.Contains(Chest)) bot.Tick();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot: done with chest")), "the chest session ends");
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem is left");
|
||||
Check.True(Said("[RynthAi] Nothing to loot on Chest: 1 " + Enough), $"the end says there was nothing to loot ({ChatDump()})");
|
||||
});
|
||||
|
||||
private static void NoMatchKeepsOldLine() => Clocked(() =>
|
||||
{
|
||||
LootCorpse(keepOne: false, gemInPack: false);
|
||||
Check.True(Said("[RynthAi] Nothing on Corpse of Brier Wasp matches the loot profile."), $"the old line ({ChatDump()})");
|
||||
Check.False(Said("Nothing to loot"), "and no second line");
|
||||
});
|
||||
|
||||
private static void CappedManaStoneSaysNothingToLoot() => Clocked(() =>
|
||||
{
|
||||
// The profile wants armor only; the stone is the built-in mana-stone rule (tapping on, keep 1),
|
||||
// which never counted as an evaluated item (alone on a corpse it ended with no line at all).
|
||||
LootCorpse(keepOne: false, gemInPack: false, bot =>
|
||||
{
|
||||
bot.S.EnableManaTapping = true;
|
||||
bot.S.ManaStoneKeepCount = 1;
|
||||
bot.Set("_manaStoneManager", new ManaStoneManager(bot.Host, bot.S, bot.Cache));
|
||||
}, Stone, PackStone);
|
||||
Check.True(Said("Mana stone match: 'Mana Stone' (have 1/1)"), $"the stone is left at its keep count ({ChatDump()})");
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Stone), "the stone stays on the corpse");
|
||||
Check.True(Said("[RynthAi] Nothing to loot on Corpse of Brier Wasp: 1 " + Enough), $"the end says there was nothing to loot ({ChatDump()})");
|
||||
});
|
||||
}
|
||||
271
Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs
Normal file
271
Tools/RynthCore.RynthAiHostTests/Tests/LootRuleMatchTests.cs
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using N = RynthCore.Loot.VTank.VTankNodeTypes;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-31: "a +9 bludg xbow that rynth sees as gold salvage", with LootSnob, which VTank keeps.
|
||||
// Fixtures\lootsnob-excerpt.utl is LootSnobV4's melee head, missile and void wand sections and six
|
||||
// of its Salvage rules (switched on, as players have them), in the file's own order.
|
||||
// Two causes:
|
||||
// 1. "Calc'd Buffed Missile Damage" read max damage x the wand elemental modifier (152). A launcher
|
||||
// has no max damage, so it was 0 and every one of LootSnob's 33 missile damage keeps failed; the
|
||||
// crossbow fell to "(Salv) Gold". VTank: max damage + (mod - 1) x 100 / 3 + elemental bonus,
|
||||
// buffed by the item's cantrips (Legendary Blood Thirst +10): 0 + 54 + 22 + 10 = 86, "Xbow (OD +9)".
|
||||
// 2. An item whose ID was late was judged without it after the wait ("best-effort"): its stats read
|
||||
// 0, the keep rules failed and a Salvage rule on its material took it. Now it waits, and is left.
|
||||
internal static class LootRuleMatchTests
|
||||
{
|
||||
private const uint Player = 0x50000A01;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot rule match: a +9 crossbow (LootSnob 'Xbow (OD +9)') is kept, not Gold salvage", PlusNineCrossbow);
|
||||
r.Add("loot rule match: without its ID the crossbow waits for it, never the Salvage rule", CrossbowWithoutId);
|
||||
r.Add("loot rule match: missile damage of bows, crossbows and atlatls at LootSnob's thresholds", MissileDamageThresholds);
|
||||
r.Add("loot rule match: buffed keys add the item's cantrips (Blood Thirst, Defender, Heart/Spirit Thirst, Impen, Hermetic)", BuffedCantrips);
|
||||
r.Add("loot rule match: double keys compare as floats (1.20 + 0.09 >= 1.29)", FloatCompare);
|
||||
r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes);
|
||||
r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId);
|
||||
r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder);
|
||||
r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains);
|
||||
}
|
||||
|
||||
private static VTankLootProfile Excerpt()
|
||||
=> VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"));
|
||||
|
||||
private static int Spell(string name)
|
||||
{
|
||||
int id = SpellDatabase.GetIdByName(name);
|
||||
if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt");
|
||||
return id;
|
||||
}
|
||||
|
||||
private static VTankLootContext Ctx() => new(FakeHost.Create(), Player);
|
||||
|
||||
private static void WithSpells(Item item, params string[] names)
|
||||
=> FakeHost.SpellIds[unchecked((uint)item.Wo.Id)] = names.Select(n => (uint)Spell(n)).ToArray();
|
||||
|
||||
// A 385 crossbow as ACE's crossbow_elemental mutation makes it: +22, damage mod 2.62, gold,
|
||||
// workmanship 6, Legendary Blood Thirst. No max damage (launchers have none).
|
||||
private static Item PlusNineXbow(bool withId = true)
|
||||
{
|
||||
var x = new Item("Blunt Crossbow", AcObjectClass.MissileWeapon)
|
||||
.Int(1, 0x100).Int(9, 0x00400000).Int(19, 12000).Int(5, 600).Int(131, 60);
|
||||
if (withId)
|
||||
{
|
||||
x.Int(105, 6).Int(353, 9).Int(158, 2).Int(159, 47).Int(160, 385).Int(204, 22).Int(45, 4).Int(48, 47)
|
||||
.Dbl(63, 2.62).Dbl(29, 1.15).Dbl(149, 1.0).Dbl(150, 1.0);
|
||||
WithSpells(x, "Legendary Blood Thirst");
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
private static void PlusNineCrossbow()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
VTankLootProfile p = Excerpt();
|
||||
var xbow = PlusNineXbow();
|
||||
var ctx = Ctx();
|
||||
VTankLootRule? rule = VTankLootEvaluator.FirstMatch(p, xbow, ctx, out int idx);
|
||||
Check.NotNull(rule, "a rule takes it");
|
||||
Check.Eq(rule?.Name.Trim(), "(M) Xbow (OD +9)", "LootSnob's Xbow (OD +9), as VTank");
|
||||
Check.Eq(rule?.Action, VTankLootAction.Keep, "kept");
|
||||
Check.Near(VTankLootEvaluator.BuffedMissileDamage(xbow, unchecked((uint)xbow.Wo.Id), ctx), 86.0, 1e-9, "0 + 162/3 + 22 + 10");
|
||||
|
||||
// Without the cantrip it's 76, under every crossbow damage keep, and its 1.15 melee defense is
|
||||
// under the 20MD rules: VTank salvages that one too.
|
||||
FakeHost.Reset();
|
||||
var plain = PlusNineXbow();
|
||||
FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id));
|
||||
Check.Eq(VTankLootEvaluator.FirstMatch(p, plain, Ctx(), out _)?.Name.Trim(), "(Salv) Gold", "76 with no cantrip: Gold salvage, in VTank too");
|
||||
}
|
||||
|
||||
private static void CrossbowWithoutId()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
VTankLootProfile p = Excerpt();
|
||||
var bare = PlusNineXbow(withId: false); // only what the CreateObject shows: no workmanship, stats or spells
|
||||
Check.Eq(VTankLootEvaluator.Decide(p, bare, Ctx(), hasIdData: false, out int idx), VTankLootVerdict.NeedsId, "waits for the ID");
|
||||
Check.Eq(p.Rules[idx].Name.Trim(), "(M) Bow (OD +10)", "at the first missile rule: its weapon type needs the ID");
|
||||
// Judged as if the ID were in (the old best-effort), it read 0s: no keep, and since the
|
||||
// workmanship is ID data too it was left; with a Salvage rule on material only it was salvaged.
|
||||
Check.Null(VTankLootEvaluator.FirstMatch(p, bare, Ctx(), out _), "judged with 0s nothing keeps it");
|
||||
|
||||
var materialOnly = new VTankLootProfile();
|
||||
materialOnly.Rules.AddRange(p.Rules.Where(r => r.Action == VTankLootAction.Keep));
|
||||
var salvGold = new VTankLootRule { Name = "Gold any", Action = VTankLootAction.Salvage };
|
||||
salvGold.Conditions.Add(new VTankLootCondition(N.LongValKeyE, "0", new[] { "60", "131" }));
|
||||
materialOnly.Rules.Add(salvGold);
|
||||
Check.Eq(VTankLootEvaluator.FirstMatch(materialOnly, bare, Ctx(), out _)?.Name, "Gold any", "the old best-effort: the material rule took it");
|
||||
Check.Eq(VTankLootEvaluator.Decide(materialOnly, bare, Ctx(), hasIdData: false, out _), VTankLootVerdict.NeedsId, "now it waits for the ID");
|
||||
|
||||
// A gem with no rule above that could want it is decided without an ID.
|
||||
var gem = new Item("Opal", AcObjectClass.Gem).Int(1, 0x800).Int(19, 300);
|
||||
Check.Eq(VTankLootEvaluator.Decide(p, gem, Ctx(), hasIdData: false, out _), VTankLootVerdict.NoMatch, "a gem needs no ID here");
|
||||
}
|
||||
|
||||
private static Item Launcher(int weaponType, double mod, int elem)
|
||||
=> new Item("Launcher", AcObjectClass.MissileWeapon).Int(353, weaponType).Int(159, 47).Int(204, elem).Dbl(63, mod).Dbl(29, 1.0);
|
||||
|
||||
private static string? First(VTankLootProfile p, Item item) => VTankLootEvaluator.FirstMatch(p, item, Ctx(), out _)?.Name.Trim();
|
||||
|
||||
private static void MissileDamageThresholds()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
VTankLootProfile p = Excerpt();
|
||||
// LootSnob's maxima at wield 385: crossbow 77, bow 68.6, atlatl 75.3 (2.65 / 2.40 / 2.60 and +22).
|
||||
Check.Eq(First(p, Launcher(9, 2.65, 22)), "(M) Xbow (Max 385)", "crossbow 165/3 + 22 = 77");
|
||||
Check.Eq(First(p, Launcher(8, 2.40, 22)), "(M) Bow (Max 385)", "bow 140/3 + 22 = 68.67");
|
||||
Check.Null(First(p, Launcher(10, 2.60, 22)), "atlatl 75.33: LootSnob's TW (Max 385) is switched off, OD +1 wants 76.3");
|
||||
Check.Null(First(p, Launcher(9, 2.65, 21)), "a 76 crossbow (and no material to salvage): no rule");
|
||||
Check.Eq(First(p, Launcher(9, 2.65, 22).Int(131, 60).Int(105, 5)), "(M) Xbow (Max 385)", "a gold one at 77 is kept, not salvaged");
|
||||
Check.Eq(First(p, Launcher(9, 2.65, 21).Int(131, 60).Int(105, 5)), "(Salv) Gold", "a gold one at 76 is salvaged");
|
||||
var epicAtlatl = Launcher(10, 2.60, 22);
|
||||
WithSpells(epicAtlatl, "Epic Blood Thirst");
|
||||
Check.Eq(First(p, epicAtlatl), "(M) TW (OD +7)", "atlatl 75.33 + Epic Blood Thirst 7 = 82.33");
|
||||
}
|
||||
|
||||
private static void BuffedCantrips()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
// A fresh context each time: one caches the spells it read for its evaluation pass.
|
||||
static bool M(Item i, VTankLootCondition c) => VTankLootEvaluator.Match(new VTankLootRule { Conditions = { c } }, i, Ctx());
|
||||
|
||||
var axe = new Item("Axe").Int(44, 74);
|
||||
Check.False(M(axe, C(N.BuffedLongValKeyGE, "84", "218103842")), "74 alone");
|
||||
WithSpells(axe, "Legendary Blood Thirst");
|
||||
Check.True(M(axe, C(N.BuffedLongValKeyGE, "84", "218103842")), "74 + Legendary Blood Thirst 10 (Decal MaxDamage key)");
|
||||
Check.False(M(axe, C(N.BuffedLongValKeyGE, "85", "218103842")), "and no more");
|
||||
Check.False(M(axe, C(N.LongValKeyGE, "75", "218103842")), "the plain key is not buffed");
|
||||
|
||||
var coat = new Item("Coat").Int(28, 500);
|
||||
WithSpells(coat, "Epic Impenetrability", "Impenetrability VI");
|
||||
Check.True(M(coat, C(N.BuffedLongValKeyGE, "560", "28")), "armor 500 + Epic Impen 60; Impen VI (castable) adds nothing");
|
||||
Check.False(M(coat, C(N.BuffedLongValKeyGE, "561", "28")), "no more");
|
||||
|
||||
var bow = new Item("Bow").Dbl(29, 1.20);
|
||||
WithSpells(bow, "Legendary Defender");
|
||||
Check.True(M(bow, C(N.BuffedDoubleValKeyGE, "1.29", "29")), "melee defense 1.20 + Legendary Defender 0.09");
|
||||
var sword = new Item("Sword").Dbl(62, 1.10);
|
||||
WithSpells(sword, "Major Heart Thirst");
|
||||
Check.True(M(sword, C(N.BuffedDoubleValKeyGE, "1.15", "167772172")), "attack (VTank AttackBonus key) 1.10 + Major Heart Thirst 0.05");
|
||||
var wand = new Item("Nether Baton").Dbl(152, 1.18).Dbl(144, 0.10);
|
||||
WithSpells(wand, "Legendary Spirit Thirst", "Legendary Hermetic Link");
|
||||
Check.True(M(wand, C(N.BuffedDoubleValKeyGE, "1.25", "152")), "elemental vs monsters 1.18 + Legendary Spirit Thirst 0.07");
|
||||
Check.True(M(wand, C(N.BuffedDoubleValKeyGE, "0.13", "144")), "mana conversion 0.10 x Legendary Hermetic Link 1.30");
|
||||
Check.False(M(wand, C(N.BuffedDoubleValKeyGE, "0.131", "144")), "no more");
|
||||
|
||||
var noCtx = new Item("Axe").Int(44, 74);
|
||||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.BuffedLongValKeyGE, "74", "44") } }, noCtx, null), "no context: the plain value");
|
||||
}
|
||||
|
||||
private static void FloatCompare()
|
||||
{
|
||||
var item = new Item("x").Dbl(29, 1.2 + 0.09); // 1.2899999999999998 as a double
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyGE, "1.29", "29") } }, item), "GE as floats");
|
||||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyLE, "1.29", "29") } }, item), "LE as floats");
|
||||
Check.False(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.DoubleValKeyGE, "1.2901", "29") } }, item), "a real difference still counts");
|
||||
}
|
||||
|
||||
private static void TinkedNodes()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
// VTank's worked example: 50 max damage, variance 0.2, unimbued, untinkered: 9 tinks
|
||||
// (2 granite, 7 iron) -> 84.4344.
|
||||
var w = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61);
|
||||
Check.Near(VTankLootEvaluator.BuffedTinkedDamage(w, unchecked((uint)w.Wo.Id), null), 84.4344, 1e-4, "tinked damage 84.4344");
|
||||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcdBuffedTinkedDamageGE, "84.43") } }, w), "node 2006 at 84.43");
|
||||
var imbued = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61).Int(179, 1).Int(171, 3);
|
||||
Check.True(VTankLootEvaluator.BuffedTinkedDamage(imbued, unchecked((uint)imbued.Wo.Id), null) < 84.4344, "imbued with 3 tinks done: 7 left, less damage");
|
||||
|
||||
// Target melee: the same item with no bonuses spends its 9 tinks on melee defense to 0.05,
|
||||
// attack to 0.04, and none on damage: 74.74 (= (50 + 24) x 1.01).
|
||||
var noBonus = new Item("Sword", AcObjectClass.MeleeWeapon).Int(44, 50).Dbl(22, 0.2).Int(131, 61);
|
||||
uint id = unchecked((uint)noBonus.Wo.Id);
|
||||
Check.True(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "74.74", "0.05", "0.04" }, out double dot), "reaches 0.05 / 0.04 / 74.74");
|
||||
Check.Near(dot, 74.74, 1e-9, "damage with no tinks left");
|
||||
Check.False(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "1", "0.06", "0.04" }, out _), "melee 0.06 is out of reach");
|
||||
Check.False(VTankLootEvaluator.MatchTinkedTargetMelee(noBonus, id, null, new[] { "1", "0.05", "0.05" }, out _), "attack 0.05 is out of reach");
|
||||
// LootSnob's "(H) 430 Insane": 109 at 1.17 / 1.17.
|
||||
var mace = new Item("Mace", AcObjectClass.MeleeWeapon).Int(44, 80).Dbl(22, 0.25).Dbl(29, 1.17).Dbl(62, 1.17).Int(131, 57);
|
||||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcedBuffedTinkedTargetMeleeGE, "109", "1.17", "1.17") } }, mace), "an 80 mace at 1.17/1.17 reaches 109");
|
||||
}
|
||||
|
||||
private static void ConditionsNeedingId()
|
||||
{
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.ObjectClass, "9")), "class");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.StringValueMatch, "Bow", "1")), "name");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.StringValueMatch, "x", "16")), "long description");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "60", "131")), "material");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "1000", "19")), "value");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "27704", "218103849")), "icon overlay (Decal key)");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "104", "218103821")), "coverage (Decal key)");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "3", "105")), "workmanship comes with the ID");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "9", "353")), "weapon type");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyE, "47", "159")), "wield skill");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.LongValKeyGE, "70", "218103842")), "max damage (Decal key)");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.DoubleValKeyGE, "1.2", "29")), "melee defense");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.BuffedMissileDamageGE, "77")), "missile damage");
|
||||
Check.True(VTankLootEvaluator.ConditionNeedsId(C(N.SpellNameMatch, "Legendary")), "spells");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.CharacterMainPackEmptySlotsGE, "7")), "pack slots");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.DisabledRule, "true")), "disabled");
|
||||
Check.False(VTankLootEvaluator.ConditionNeedsId(C(N.SlotExactPalette, "1", "1682")), "palette");
|
||||
}
|
||||
|
||||
private static void DecideOrder()
|
||||
{
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
var bowRule = new VTankLootRule { Name = "bow keep", Action = VTankLootAction.Keep };
|
||||
bowRule.Conditions.Add(C(N.LongValKeyE, "8", "353")); // ID first
|
||||
bowRule.Conditions.Add(C(N.ObjectClass, "9")); // class after
|
||||
var name = new VTankLootRule { Name = "trade note", Action = VTankLootAction.Keep };
|
||||
name.Conditions.Add(C(N.StringValueMatch, "Trade Note", "1"));
|
||||
var p = new VTankLootProfile();
|
||||
p.Rules.AddRange(new[] { bowRule, name });
|
||||
|
||||
var note = new Item("Trade Note (250,000)", AcObjectClass.TradeNote);
|
||||
Check.Eq(VTankLootEvaluator.Decide(p, note, null, hasIdData: false, out int i1), VTankLootVerdict.Match, "the bow rule's class rules a note out, though it comes second");
|
||||
Check.Eq(i1, 1, "the name rule takes it with no ID");
|
||||
var bow = new Item("Bow", AcObjectClass.MissileWeapon);
|
||||
Check.Eq(VTankLootEvaluator.Decide(p, bow, null, hasIdData: false, out int i2), VTankLootVerdict.NeedsId, "a bow waits for the bow rule's ID");
|
||||
Check.Eq(i2, 0, "at the bow rule");
|
||||
Check.Eq(VTankLootEvaluator.Decide(p, bow, null, hasIdData: true, out _), VTankLootVerdict.NoMatch, "with the ID (no weapon type 8) nothing takes it");
|
||||
Check.Eq(VTankLootEvaluator.Decide(new VTankLootProfile(), bow, null, hasIdData: false, out int i3), VTankLootVerdict.NoMatch, "empty profile");
|
||||
Check.Eq(i3, -1, "index -1");
|
||||
}
|
||||
|
||||
private static void LootWhyExplains()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
VTankLootProfile p = Excerpt();
|
||||
var plain = PlusNineXbow();
|
||||
FakeHost.SpellIds.Remove(unchecked((uint)plain.Wo.Id)); // 76: Gold salvage
|
||||
LootWhy.Result why = LootWhy.Explain(p, plain, Ctx(), hasIdData: true);
|
||||
Check.Eq(why.Verdict, VTankLootVerdict.Match, "matched");
|
||||
Check.Eq(why.RuleName, "(Salv) Gold", "Gold salvage");
|
||||
var max = why.NearMisses.FirstOrDefault(m => m.RuleName == "(M) Xbow (Max 385)");
|
||||
Check.Eq(max.RuleName, "(M) Xbow (Max 385)", "Xbow (Max 385) came close");
|
||||
Check.True(max.Failed.StartsWith("Buffed Missile Damage >= 77: read 76", StringComparison.Ordinal), $"its failed condition and the value read ({max.Failed})");
|
||||
Check.True(max.Failed.Contains("mod 2.62") && max.Failed.Contains("elemental 22"), "and how it was made");
|
||||
Check.False(why.NearMisses.Any(m => m.RuleName.StartsWith("(M) Bow", StringComparison.Ordinal)), "bow rules failed on their first condition: not listed");
|
||||
Check.False(why.NearMisses.Any(m => m.RuleName.Contains("Max 375")), "switched-off rules are not listed");
|
||||
Check.True(why.NearMisses.Any(m => m.RuleName == "(M) Xbow (20MD)" && m.Failed.Contains("read 1.15")), "the 20MD rules read its 1.15 melee defense");
|
||||
|
||||
var bare = PlusNineXbow(withId: false);
|
||||
LootWhy.Result wait = LootWhy.Explain(p, bare, Ctx(), hasIdData: false);
|
||||
Check.Eq(wait.Verdict, VTankLootVerdict.NeedsId, "no ID: waits");
|
||||
Check.Eq(wait.RuleName, "(M) Bow (OD +10)", "names the rule that needs it");
|
||||
}
|
||||
}
|
||||
245
Tools/RynthCore.RynthAiHostTests/Tests/LootSurveyTests.cs
Normal file
245
Tools/RynthCore.RynthAiHostTests/Tests/LootSurveyTests.cs
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// A survey, not a check of one rule: real item types (bows and crossbows by element, wands,
|
||||
// melee weapons, armor, jewelry, salvage of each material), built the way ACE makes them, run
|
||||
// through the LootSnob profiles players use, with and without their identify data. It prints
|
||||
// the rule each one gets (and writes a TSV when RYNTH_LOOT_SURVEY_OUT names a file), so a change
|
||||
// to the evaluator shows which items it moves. The profiles are read from the install
|
||||
// (C:\Games\RynthSuite\RynthAi\LootProfiles, read only); without them only the excerpt runs.
|
||||
// The checks that matter are in LootRuleMatchTests; this one only checks that it ran.
|
||||
internal static class LootSurveyTests
|
||||
{
|
||||
private const uint Player = 0x50000A01;
|
||||
private const string ProfileDir = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot survey: LootSnob profiles x real item types, with and without ID (prints the rule each gets)", Survey);
|
||||
}
|
||||
|
||||
// CreateObject ints: what an item shows before its ID (RynthCore PwdLayout.IntStypes).
|
||||
private static readonly HashSet<uint> CreateInts = new() { 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 18, 19, 50, 51, 91, 92, 94, 95, 131, 133, 151, 152, 280 };
|
||||
|
||||
internal sealed record SurveyItem(string Label, string Name, AcObjectClass Cls, Dictionary<int, int> Ints, Dictionary<int, double> Dbls, string[] Spells);
|
||||
|
||||
private static int Spell(string name)
|
||||
{
|
||||
int id = SpellDatabase.GetIdByName(name);
|
||||
if (id == 0) throw new InvalidOperationException($"spell '{name}' is not in SpellData.txt");
|
||||
return id;
|
||||
}
|
||||
|
||||
// ── ACE-like items ───────────────────────────────────────────────────────
|
||||
private const int ItemType = 1, Burden = 5, ValidLoc = 9, Value = 19, Damage = 44, DamageType = 45, WeaponSkill = 48,
|
||||
Workmanship = 105, Material = 131, WieldReq = 158, WieldSkill = 159, WieldDiff = 160, ElemBonus = 204,
|
||||
EquipSet = 265, WeaponType = 353, ArmorLevel = 28, Priority = 4, Tinkered = 171, Imbued = 179;
|
||||
private const int Variance = 22, DamageMod = 63, MeleeDef = 29, Offense = 62, MissileDef = 149, MagicDef = 150, ManaConv = 144, ElemVsMonster = 152;
|
||||
|
||||
private static SurveyItem Launcher(string label, string name, int weaponType, int wield, int elem, double mod, double def, int material, int work, int dmgType, params string[] spells)
|
||||
=> new(label, name, AcObjectClass.MissileWeapon,
|
||||
new() { [ItemType] = 0x100, [ValidLoc] = 0x00400000, [Value] = 9000, [Burden] = 500, [Material] = material, [Workmanship] = work,
|
||||
[WeaponType] = weaponType, [WieldReq] = 2, [WieldSkill] = 47, [WieldDiff] = wield, [ElemBonus] = elem,
|
||||
[DamageType] = dmgType, [WeaponSkill] = 47 },
|
||||
new() { [DamageMod] = mod, [MeleeDef] = def, [MissileDef] = 1.0, [MagicDef] = 1.0 },
|
||||
spells);
|
||||
|
||||
private static SurveyItem Melee(string label, string name, int weaponType, int skill, int damage, double variance, double def, double off, int material, int work, params string[] spells)
|
||||
=> new(label, name, AcObjectClass.MeleeWeapon,
|
||||
new() { [ItemType] = 0x1, [ValidLoc] = 0x00100000, [Value] = 9000, [Burden] = 400, [Material] = material, [Workmanship] = work,
|
||||
[WeaponType] = weaponType, [WieldReq] = 2, [WieldSkill] = skill, [WieldDiff] = 430, [Damage] = damage, [DamageType] = 1, [WeaponSkill] = skill },
|
||||
new() { [Variance] = variance, [MeleeDef] = def, [Offense] = off, [MissileDef] = 1.0, [MagicDef] = 1.0 },
|
||||
spells);
|
||||
|
||||
private static SurveyItem Caster(string label, string name, int wield, double elemVsMonster, double def, double manaConv, int material, int work, params string[] spells)
|
||||
=> new(label, name, AcObjectClass.WandStaffOrb,
|
||||
new() { [ItemType] = 0x8000, [ValidLoc] = 0x01000000, [Value] = 9000, [Burden] = 50, [Material] = material, [Workmanship] = work,
|
||||
[WieldReq] = 2, [WieldSkill] = 34, [WieldDiff] = wield },
|
||||
new() { [ElemVsMonster] = elemVsMonster, [MeleeDef] = def, [ManaConv] = manaConv, [MagicDef] = 1.0 },
|
||||
spells);
|
||||
|
||||
private static SurveyItem Armor(string label, string name, int al, int set, int material, int work, params string[] spells)
|
||||
=> new(label, name, AcObjectClass.Armor,
|
||||
new() { [ItemType] = 0x2, [ValidLoc] = 0x00000200, [Priority] = 0x400, [Value] = 9000, [Burden] = 700, [Material] = material,
|
||||
[Workmanship] = work, [ArmorLevel] = al, [EquipSet] = set },
|
||||
new(), spells);
|
||||
|
||||
private static SurveyItem Jewel(string label, string name, int material, int work, params string[] spells)
|
||||
=> new(label, name, AcObjectClass.Jewelry,
|
||||
new() { [ItemType] = 0x8, [ValidLoc] = 0x00040000, [Value] = 7000, [Burden] = 30, [Material] = material, [Workmanship] = work },
|
||||
new(), spells);
|
||||
|
||||
internal static List<SurveyItem> Items()
|
||||
{
|
||||
const int Gold = 60, Iron = 61, Steel = 64, Silver = 63, Mahogany = 74, Oak = 75, Pine = 76, Ebony = 73, Teak = 77, Brass = 57,
|
||||
Granite = 67, Satin = 5;
|
||||
const int Slash = 1, Pierce = 2, Bludge = 4, Cold = 8, Fire = 16, Acid = 32, Elec = 64;
|
||||
var items = new List<SurveyItem>
|
||||
{
|
||||
// Crossbows (WeaponType 9): LootSnob's missile damage = mod% / 3 + elemental + cantrip.
|
||||
Launcher("xbow 385 +22 mod 2.62 Legendary Blood Thirst (OD +9)", "Blunt Crossbow", 9, 385, 22, 2.62, 1.15, Gold, 6, Bludge, "Legendary Blood Thirst"),
|
||||
Launcher("xbow 385 +22 mod 2.65 (Max 385)", "Fire Crossbow", 9, 385, 22, 2.65, 1.12, Iron, 5, Fire),
|
||||
Launcher("xbow 385 +22 mod 2.62 no cantrip (76, under Max 385)", "Blunt Crossbow", 9, 385, 22, 2.62, 1.15, Gold, 6, Bludge),
|
||||
Launcher("xbow 385 +21 mod 2.65 Epic Blood Thirst (OD +6)", "Acid Compound Crossbow", 9, 385, 21, 2.65, 1.10, Mahogany, 7, Acid, "Epic Blood Thirst"),
|
||||
Launcher("xbow 335 +9 mod 2.55 (a '+9' elemental)", "Electric Crossbow", 9, 335, 9, 2.55, 1.10, Gold, 5, Elec),
|
||||
Launcher("xbow 375 +19 MD 1.20 Legendary Defender (29MD)", "Frost Crossbow", 9, 375, 19, 2.60, 1.20, Steel, 6, Cold, "Legendary Defender"),
|
||||
Launcher("xbow 375 +19 MD 1.22 (22MD)", "Slashing Crossbow", 9, 375, 19, 2.60, 1.22, Silver, 6, Slash),
|
||||
// Bows (8)
|
||||
Launcher("bow 385 +22 mod 2.40 (Max 385)", "Fire Compound Bow", 8, 385, 22, 2.40, 1.10, Oak, 5, Fire),
|
||||
Launcher("bow 385 +22 mod 2.40 Legendary Blood Thirst (OD +10)", "Piercing Bow", 8, 385, 22, 2.40, 1.10, Pine, 5, Pierce, "Legendary Blood Thirst"),
|
||||
Launcher("bow 375 +19 mod 2.37 (64.7, rules off)", "Electric Bow", 8, 375, 19, 2.37, 1.10, Ebony, 6, Elec),
|
||||
Launcher("bow 360 +16 mod 2.35 MD 1.21 (21MD)", "Blunt Bow", 8, 360, 16, 2.35, 1.21, Teak, 5, Bludge),
|
||||
Launcher("bow 335 +9 mod 2.30 Iron", "Acid Bow", 8, 335, 9, 2.30, 1.05, Iron, 5, Acid),
|
||||
// Atlatls (10)
|
||||
Launcher("atlatl 385 +22 mod 2.60 Epic Blood Thirst (OD +7)", "Electric Atlatl", 10, 385, 22, 2.60, 1.10, Mahogany, 5, Elec, "Epic Blood Thirst"),
|
||||
Launcher("atlatl 385 +22 mod 2.60 (75.3, Max 385 off)", "Fire Atlatl", 10, 385, 22, 2.60, 1.10, Mahogany, 5, Fire),
|
||||
Launcher("atlatl 360 +16 MD 1.29 (29MD)", "Blunt Atlatl", 10, 360, 16, 2.45, 1.29, Gold, 6, Bludge),
|
||||
// Wands
|
||||
Caster("void wand 1.18 Legendary Spirit Thirst (OD +7)", "Nether Baton", 385, 1.18, 1.10, 0.05, Silver, 6, "Legendary Spirit Thirst"),
|
||||
Caster("void wand 385 1.18 (Max 385)", "Nether Sceptre", 385, 1.18, 1.10, 0.05, Silver, 6),
|
||||
Caster("war sceptre 1.18 MD 1.15 Major Defender (18pvm + 20md)", "Sceptre", 385, 1.18, 1.15, 0.05, Brass, 5, "Major Defender"),
|
||||
Caster("war staff 1.15 MD 1.20 (no rule)", "Staff", 375, 1.12, 1.18, 0.05, Teak, 5),
|
||||
Caster("orb no wield MD 1.21 Minor Defender (24MD)", "Orb", 0, 1.0, 1.21, 0.10, Granite, 5, "Minor Defender"),
|
||||
// Melee (heavy axe 44, light sword 45, finesse dagger 46)
|
||||
Melee("heavy axe 74 (Max 430)", "Silifi", 3, 44, 74, 0.45, 1.12, 1.12, Iron, 6),
|
||||
Melee("heavy axe 74 Legendary Blood Thirst (OD +10)", "Lugian Axe", 3, 44, 74, 0.45, 1.12, 1.12, Iron, 6, "Legendary Blood Thirst"),
|
||||
Melee("heavy axe 72 MD 1.26 Minor Defender (MD +8)", "War Axe", 3, 44, 66, 0.45, 1.26, 1.10, Steel, 6, "Minor Defender"),
|
||||
Melee("heavy mace 80 var .25 def/atk 1.17 (430 Insane)", "Mace", 4, 44, 80, 0.25, 1.17, 1.17, Brass, 7),
|
||||
Melee("light sword 68 (OD +10)", "Broad Sword", 2, 45, 68, 0.40, 1.10, 1.10, Steel, 5),
|
||||
Melee("light sword 60 Epic Blood Thirst (67, OD +9)", "Shamshir", 2, 45, 60, 0.40, 1.10, 1.10, Steel, 5, "Epic Blood Thirst"),
|
||||
Melee("finesse dagger 59 (OD >= +1)", "Poniard", 6, 46, 59, 0.40, 1.10, 1.10, Gold, 5),
|
||||
Melee("2h spear 57 (OD +9)", "Assagai", 5, 41, 57, 0.40, 1.10, 1.10, Iron, 5),
|
||||
// Armor and jewelry
|
||||
Armor("Archer's set coat Legendary Missile Weapon + Epic Impen", "Amuli Coat", 600, 15, Satin, 6, "Legendary Missile Weapon Aptitude", "Epic Impenetrability"),
|
||||
Armor("plain breastplate AL 400 Steel w5", "Breastplate", 400, 0, Steel, 5),
|
||||
Armor("plain coat AL 300 Gold w4", "Chainmail Coat", 300, 0, Gold, 4),
|
||||
Jewel("ring Legendary Strength", "Ring", Silver, 5, "Legendary Strength"),
|
||||
Jewel("necklace no spells Gold w4", "Necklace", Gold, 4),
|
||||
};
|
||||
// Salvage of each material: a plain armor piece, workmanship 5.
|
||||
(string Name, int Id)[] mats =
|
||||
{
|
||||
("Alabaster", 66), ("Armoredillo Hide", 53), ("Bronze", 58), ("Ceramic", 1), ("Marble", 68), ("Peridot", 34), ("Reed Shark Hide", 55),
|
||||
("Steel", 64), ("Wool", 8), ("Yellow Topaz", 49), ("Zircon", 50), ("Amber", 11), ("Copper", 59), ("Diamond", 20), ("Ebony", 73),
|
||||
("Gold", 60), ("Gromnie Hide", 54), ("Linen", 4), ("Moonstone", 31), ("Pine", 76), ("Porcelain", 2), ("Pyreal", 62), ("Ruby", 38),
|
||||
("Sapphire", 39), ("Satin", 5), ("Silver", 63), ("Teak", 77), ("Agate", 10), ("Azurite", 14), ("Black Opal", 16), ("Bloodstone", 17),
|
||||
("Carnelian", 18), ("Citrine", 19), ("Fire Opal", 22), ("Green Garnet", 23), ("Hematite", 25), ("Lapis Lazuli", 28), ("Lavender Jade", 29),
|
||||
("Malachite", 30), ("Opal", 33), ("Red Jade", 36), ("Rose Quartz", 37), ("Smokey Quartz", 40), ("Sunstone", 41), ("Aquamarine", 13),
|
||||
("Black Garnet", 15), ("Brass", 57), ("Emerald", 21), ("Granite", 67), ("Imperial Topaz", 26), ("Iron", 61), ("Jet", 27),
|
||||
("Mahogany", 74), ("Oak", 75), ("Red Garnet", 35), ("Velvet", 7), ("White Sapphire", 47), ("Ivory", 51), ("Leather", 52),
|
||||
("Sandstone", 70), ("Silk", 6), ("Amethyst", 12), ("Green Jade", 24), ("Obsidian", 69), ("Onyx", 32), ("Serpentine", 71),
|
||||
("Tiger Eye", 42), ("Tourmaline", 43), ("Turquoise", 44), ("White Jade", 45), ("White Quartz", 46), ("Yellow Garnet", 48),
|
||||
};
|
||||
foreach (var (n, id) in mats)
|
||||
items.Add(Armor($"salvage: {n} w5 (plain armor)", "Leather Leggings", 150, 0, id, 5));
|
||||
return items;
|
||||
}
|
||||
|
||||
// ── Running one item ─────────────────────────────────────────────────────
|
||||
|
||||
private static readonly MethodInfo? DecideMethod = typeof(VTankLootEvaluator).GetMethod("Decide");
|
||||
|
||||
/// <summary>The rule the looter gives the item: with its ID, or (hasId false) from what it shows before one.</summary>
|
||||
internal static string Classify(VTankLootProfile profile, SurveyItem s, bool hasId)
|
||||
{
|
||||
var (item, ctx) = Build(s, hasId);
|
||||
|
||||
int index;
|
||||
string verdict;
|
||||
if (DecideMethod != null)
|
||||
{
|
||||
object?[] args = { profile, item.Wo, ctx, hasId, -1 };
|
||||
verdict = DecideMethod.Invoke(null, args)!.ToString()!;
|
||||
index = (int)args[4]!;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Before 2026-10-31: no wait for the ID past the timeout, the rules judged what was there.
|
||||
VTankLootRule? hit = VTankLootEvaluator.FirstMatch(profile, item.Wo, ctx, out index);
|
||||
verdict = hit != null ? "Match" : "NoMatch";
|
||||
}
|
||||
if (verdict == "NoMatch" || index < 0) return "leave";
|
||||
string name = profile.Rules[index].Name.Trim();
|
||||
return verdict == "NeedsId" ? $"hold for ID ({name})" : $"{profile.Rules[index].Action}: {name}";
|
||||
}
|
||||
|
||||
/// <summary>The survey item as a test item: with its ID, or only what the CreateObject shows.</summary>
|
||||
private static (Item Item, VTankLootContext Ctx) Build(SurveyItem s, bool hasId)
|
||||
{
|
||||
var item = new Item(s.Name, s.Cls);
|
||||
foreach (var (k, v) in s.Ints)
|
||||
if (hasId || CreateInts.Contains(unchecked((uint)k))) item.Int(k, v);
|
||||
if (hasId)
|
||||
foreach (var (k, v) in s.Dbls) item.Dbl(k, v);
|
||||
uint id = unchecked((uint)item.Wo.Id);
|
||||
var spellIds = new List<uint>();
|
||||
if (hasId) foreach (string sp in s.Spells) spellIds.Add((uint)Spell(sp));
|
||||
FakeHost.SpellIds[id] = spellIds.ToArray();
|
||||
return (item, new VTankLootContext(FakeHost.Create(), Player));
|
||||
}
|
||||
|
||||
internal static VTankLootProfile WithSalvageOn(VTankLootProfile p)
|
||||
{
|
||||
foreach (var r in p.Rules)
|
||||
if (r.Action == VTankLootAction.Salvage)
|
||||
r.Conditions.RemoveAll(c => c.NodeType == VTankNodeTypes.DisabledRule);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void Survey()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var profiles = new List<(string Name, VTankLootProfile Profile)>
|
||||
{
|
||||
("lootsnob-excerpt (fixture)", VTankLootParser.Load(Path.Combine(AppContext.BaseDirectory, "Fixtures", "lootsnob-excerpt.utl"))),
|
||||
};
|
||||
string snob = Path.Combine(ProfileDir, "LootSnobV4.utl"), cq = Path.Combine(ProfileDir, "CQ_Lootsnob_lite.utl");
|
||||
if (File.Exists(snob))
|
||||
{
|
||||
profiles.Add(("LootSnobV4", VTankLootParser.Load(snob)));
|
||||
profiles.Add(("LootSnobV4 salvage on", WithSalvageOn(VTankLootParser.Load(snob))));
|
||||
}
|
||||
if (File.Exists(cq))
|
||||
{
|
||||
profiles.Add(("CQ_Lootsnob_lite", VTankLootParser.Load(cq)));
|
||||
profiles.Add(("CQ_Lootsnob_lite salvage on", WithSalvageOn(VTankLootParser.Load(cq))));
|
||||
}
|
||||
|
||||
var tsv = new StringBuilder("profile\titem\tname\twith ID\twithout ID\n");
|
||||
foreach (var (pname, profile) in profiles)
|
||||
{
|
||||
Console.WriteLine($" -- {pname} ({profile.Rules.Count} rules)");
|
||||
foreach (SurveyItem s in Items())
|
||||
{
|
||||
string withId = Classify(profile, s, hasId: true);
|
||||
string noId = Classify(profile, s, hasId: false);
|
||||
tsv.Append(pname).Append('\t').Append(s.Label).Append('\t').Append(s.Name).Append('\t').Append(withId).Append('\t').Append(noId).Append('\n');
|
||||
if (!s.Label.StartsWith("salvage:", StringComparison.Ordinal) || withId != "leave")
|
||||
Console.WriteLine($" {s.Label,-62} ID: {withId,-40} no ID: {noId}");
|
||||
}
|
||||
}
|
||||
// What /ra loot why says for the reported crossbow without its cantrip (76: Gold salvage).
|
||||
var (whyProfileName, whyProfile) = profiles[profiles.Count > 2 ? 2 : 0];
|
||||
SurveyItem plain = Items().Find(i => i.Label.StartsWith("xbow 385 +22 mod 2.62 no cantrip", StringComparison.Ordinal))!;
|
||||
var (whyItem, whyCtx) = Build(plain, hasId: true);
|
||||
LootWhy.Result why = LootWhy.Explain(whyProfile, whyItem.Wo, whyCtx, hasIdData: true);
|
||||
Console.WriteLine($" -- /ra loot why, {whyProfileName}, '{plain.Label}': {why.Verdict} rule {why.Index + 1} '{why.RuleName}' [{why.Action}], {why.NearMisses.Count} came close:");
|
||||
foreach (var m in why.NearMisses)
|
||||
Console.WriteLine($" #{m.Index + 1} '{m.RuleName}': {m.Failed}");
|
||||
|
||||
string? outPath = Environment.GetEnvironmentVariable("RYNTH_LOOT_SURVEY_OUT");
|
||||
if (!string.IsNullOrWhiteSpace(outPath)) File.WriteAllText(outPath, tsv.ToString());
|
||||
Check.True(profiles[0].Profile.Rules.Count > 100, "the excerpt fixture loads");
|
||||
}
|
||||
}
|
||||
|
|
@ -143,6 +143,16 @@ internal static class ProfileLoadTests
|
|||
Check.Eq(l.Layout, MagItemInfoSettings.LayoutOneLine, "layout");
|
||||
Check.Eq(l.ChatType, 7, "chat type");
|
||||
Check.Eq(l.Prefix, "[ii] ", "prefix");
|
||||
|
||||
// 2026-10-31: Describe items when selected is on by default; a saved "off" stays off.
|
||||
Check.True(new MagItemInfoSettings().OnSelect, "Describe items when selected: on by default");
|
||||
var off = new LegacyUiSettings();
|
||||
off.ItemInfoSettings.OnSelect = false;
|
||||
var offLoaded = JsonSerializer.Deserialize(JsonSerializer.Serialize(off, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
var offLive = new LegacyUiSettings();
|
||||
CopySettings(offLoaded, offLive);
|
||||
Check.False(offLive.ItemInfoSettings.OnSelect, "a saved 'off' stays off");
|
||||
Check.True(live.EnableGroundLoot, "ground loot");
|
||||
Check.False(live.PetAutoRefill, "pet auto refill");
|
||||
Check.True(live.MonsterNameBlacklist.Contains("Drudge Skulker"), "monster blacklist");
|
||||
|
|
|
|||
|
|
@ -33,6 +33,9 @@ internal static class TargetingTests
|
|||
r.Add("targeting: lock off switches only past each scheme's margin", LockOffMargins);
|
||||
r.Add("targeting: lock off never switches with an attack at the target in flight", NoSwitchInFlight);
|
||||
r.Add("targeting: settings default to lowest health with the lock on", Defaults);
|
||||
r.Add("targeting: a higher priority out of sight is named as passed over, once per reason", PassedOverOutOfSight);
|
||||
r.Add("targeting: a higher priority just past Monster Range is named on the lock line", PassedOverBeyondRange);
|
||||
r.Add("targeting: nothing is named when no higher priority was left out", PassedOverNothingHigher);
|
||||
}
|
||||
|
||||
// ── Schemes ───────────────────────────────────────────────────────────────
|
||||
|
|
@ -235,6 +238,132 @@ internal static class TargetingTests
|
|||
Check.Eq(s.TargetSelection, 3, "an out-of-range choice is clamped");
|
||||
}
|
||||
|
||||
// ── Passed over (R-20261031-201214-8be7) ──────────────────────────────────
|
||||
// A report said a Priority 5 monster was ignored for Priority 1 ones; the log showed only
|
||||
// that some monsters in range were LOS-blocked, not which. The lock line now names the best
|
||||
// higher-priority monster that wasn't a candidate, and why. Selection itself is unchanged.
|
||||
|
||||
private static void PassedOverOutOfSight()
|
||||
{
|
||||
var t = new ScanPick(monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
|
||||
t.Place(A, "Mob A", north: 2);
|
||||
t.Place(Boss, "Boss", east: 3);
|
||||
t.Blocked.Add(Boss);
|
||||
Check.Eq(t.Tick(), A, "the Boss is behind a wall: Mob A, the only candidate, is locked");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000401")
|
||||
&& l.Contains("[passed over 0x80000404 'Boss' priority 5, 3.0 m: line of sight blocked]")),
|
||||
"the lock line names the Boss and why it wasn't picked");
|
||||
|
||||
int lines = PassedLines();
|
||||
t.Tick();
|
||||
t.Tick();
|
||||
Check.Eq(PassedLines(), lines, "still behind the wall: not logged again");
|
||||
|
||||
FakeHost.NotAttackable.Add(Boss);
|
||||
t.Tick();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] passed over 0x80000404 'Boss' priority 5, 3.0 m: not attackable")
|
||||
&& l.Contains("the target stays 0x80000401 'Mob A' priority 1")),
|
||||
"a new reason is one new line, with the target that stays");
|
||||
int after = PassedLines();
|
||||
t.Tick();
|
||||
Check.Eq(PassedLines(), after, "and only once");
|
||||
|
||||
FakeHost.NotAttackable.Remove(Boss);
|
||||
t.Blocked.Remove(Boss);
|
||||
Check.Eq(t.Tick(), Boss, "in sight and attackable: the Boss takes over at once");
|
||||
string sw = FakeHost.Logs.Last(l => l.Contains("[CombatTarget] switch"));
|
||||
Check.True(sw.Contains("priority 1 < 5") && !sw.Contains("passed over"), "the switch says priority, with nothing passed over");
|
||||
}
|
||||
|
||||
private static void PassedOverBeyondRange()
|
||||
{
|
||||
var t = new ScanPick(monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
|
||||
t.Place(A, "Mob A", north: 2);
|
||||
t.Place(Boss, "Boss", north: -12);
|
||||
Check.Eq(t.Tick(), A, "the Boss at 12 m is past Monster Range 10: Mob A");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000401")
|
||||
&& l.Contains("[passed over 0x80000404 'Boss' priority 5, 12.0 m: beyond Monster Range (10 m)]")),
|
||||
"the lock line names the Boss past the range");
|
||||
|
||||
t = new ScanPick(monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
|
||||
t.Place(A, "Mob A", north: 2);
|
||||
t.Place(Boss, "Boss", north: -30);
|
||||
t.Tick();
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "30 m out (more than 15 m past the range): not named");
|
||||
}
|
||||
|
||||
private static void PassedOverNothingHigher()
|
||||
{
|
||||
var t = new ScanPick(monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
|
||||
t.Place(A, "Mob A", north: 2);
|
||||
t.Place(B, "Mob B", east: 3);
|
||||
t.Place(C, "Mob C", north: -12);
|
||||
t.Blocked.Add(B);
|
||||
Check.Eq(t.Tick(), A, "Mob A is locked");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")),
|
||||
"a same-priority monster behind a wall or past the range isn't named");
|
||||
|
||||
t = new ScanPick(monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 5 });
|
||||
t.Place(A, "Mob A", north: 2);
|
||||
t.Place(Boss, "Boss", east: 3);
|
||||
Check.Eq(t.Tick(), Boss, "the Boss in sight is the target");
|
||||
t.Blocked.Add(Boss);
|
||||
t.Tick();
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("passed over")), "the target itself out of sight isn't 'passed over'");
|
||||
}
|
||||
|
||||
private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over"));
|
||||
|
||||
/// <summary>The real scan (ScanNearbyTargets) over placed monsters, then the pick.</summary>
|
||||
private sealed class ScanPick
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly HashSet<uint> Blocked = new();
|
||||
private readonly List<uint> _ids = new();
|
||||
private CombatManager? _c;
|
||||
private static readonly FieldInfo LastScan =
|
||||
typeof(CombatManager).GetField("_lastScanTime", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
|
||||
public ScanPick(int monsterRange)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
TargetingTests.Place(Player, "Me", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = Closest, TargetLock = true };
|
||||
}
|
||||
|
||||
/// <summary>A monster <paramref name="north"/>/<paramref name="east"/> m from the player.</summary>
|
||||
public void Place(uint id, string name, double north = 0, double east = 0)
|
||||
{
|
||||
TargetingTests.Place(id, name, (float)(96 + east), (float)(96 + north));
|
||||
if (!_ids.Contains(id)) _ids.Add(id);
|
||||
}
|
||||
|
||||
/// <summary>One combat tick's selection: scan, pick, and the passed-over note.</summary>
|
||||
public uint Tick()
|
||||
{
|
||||
if (_c == null)
|
||||
{
|
||||
var host = FakeHost.Create();
|
||||
var cache = FakeHost.MakeCache(host, Player, _ids, null);
|
||||
_c = new CombatManager(host, S, cache);
|
||||
_c.SetPlayerId(Player);
|
||||
_c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
_c.LosBlockedOverride = id => Blocked.Contains(unchecked((uint)id));
|
||||
}
|
||||
LastScan.SetValue(_c, DateTime.MinValue);
|
||||
_c.ScanNearbyTargets();
|
||||
_c.HandleCombatTrigger();
|
||||
_c.NotePassedOverWhileEngaged();
|
||||
return unchecked((uint)_c.activeTargetId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
|
|
|
|||
|
|
@ -256,18 +256,26 @@ internal static class VTankLootTests
|
|||
Check.False(M(sword, C(N.MinDamageGE, "20.5")), "min above");
|
||||
Check.True(M(sword, C(N.BuffedMedianDamageGE, "30")), "median 30");
|
||||
Check.False(M(sword, C(N.BuffedMedianDamageGE, "30.1")), "median above");
|
||||
Check.True(M(sword, C(N.CalcdBuffedTinkedDamageGE, "40")), "tinked damage reads max damage");
|
||||
// No material: it can't be tinked, so the damage over time is max + Blood Drinker's 24,
|
||||
// 10% crits at double: (40 + 24) x (0.9 x 1.5 / 2 + 0.2) = 56
|
||||
Check.True(M(sword, C(N.CalcdBuffedTinkedDamageGE, "56")), "tinked damage: no material, no tinks");
|
||||
Check.False(M(sword, C(N.CalcdBuffedTinkedDamageGE, "56.01")), "tinked damage just above");
|
||||
Check.False(M(sword, C(N.DamagePercentGE, "0")), "damage percent always fails (as VTank)");
|
||||
var nodmg = new Item("Stick");
|
||||
Check.False(M(nodmg, C(N.MinDamageGE, "0")), "no max damage: min damage fails even at 0");
|
||||
Check.False(M(nodmg, C(N.BuffedMedianDamageGE, "0")), "no max damage: median fails");
|
||||
Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no max damage: missile fails");
|
||||
Check.False(M(nodmg, C(N.BuffedMissileDamageGE, "0")), "no damage modifier (not a launcher): missile fails");
|
||||
|
||||
var bow = new Item("Bow").Int(44, 50).Dbl(152, 1.2);
|
||||
Check.True(M(bow, C(N.BuffedMissileDamageGE, "60")), "50 * elemental 1.2 = 60");
|
||||
Check.False(M(bow, C(N.BuffedMissileDamageGE, "60.1")), "just above");
|
||||
var weakBow = new Item("Bow").Int(44, 50).Dbl(152, 0.5);
|
||||
Check.True(M(weakBow, C(N.BuffedMissileDamageGE, "50")), "an elemental bonus below 1 counts as 1");
|
||||
// Missile damage = max damage + (damage mod - 1) x 100 / 3 + elemental bonus (204); a
|
||||
// launcher has no max damage. VTank's own example: a 50 max damage bow with mod 1.15 is 55.
|
||||
var bow = new Item("Bow").Int(44, 50).Dbl(63, 1.15);
|
||||
Check.True(M(bow, C(N.BuffedMissileDamageGE, "55")), "50 + 15/3 = 55");
|
||||
Check.False(M(bow, C(N.BuffedMissileDamageGE, "55.01")), "just above");
|
||||
var xbow = new Item("Crossbow").Dbl(63, 2.65).Int(204, 22);
|
||||
Check.True(M(xbow, C(N.BuffedMissileDamageGE, "77")), "a 385 crossbow: 165/3 + 22 = 77");
|
||||
Check.False(M(xbow, C(N.BuffedMissileDamageGE, "77.01")), "and no more");
|
||||
var noElem = new Item("Crossbow").Dbl(63, 2.2);
|
||||
Check.True(M(noElem, C(N.BuffedMissileDamageGE, "40")), "no elemental bonus reads 0: 120/3 = 40");
|
||||
}
|
||||
|
||||
private static void BuffedKeysAndRatings()
|
||||
|
|
@ -288,7 +296,7 @@ internal static class VTankLootTests
|
|||
Check.True(M(item, C(N.AnySimilarColor, "1", "2", "3", "4", "5")), "any similar colour passes");
|
||||
Check.True(M(item, C(N.SimilarColorArmorType, "1", "2", "3", "4", "5", "6")), "armor-type colour passes");
|
||||
Check.True(M(item, C(N.SlotSimilarColor, "1", "2", "3", "4", "5", "6")), "slot colour passes");
|
||||
Check.False(M(item, C(N.CalcedBuffedTinkedTargetMeleeGE, "1", "1", "1")), "tinked target melee is not implemented: fails");
|
||||
Check.False(M(item, C(N.CalcedBuffedTinkedTargetMeleeGE, "1", "1", "1")), "tinked target melee: no max damage, fails");
|
||||
}
|
||||
|
||||
private static void SpellNodesNoContext()
|
||||
|
|
@ -355,6 +363,7 @@ internal static class VTankLootTests
|
|||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Skills[(Player, 34)] = (Buffed: 400, Training: 3);
|
||||
FakeHost.SkillLevels[(Player, 34, 1)] = 320; // base (no enchantments)
|
||||
FakeHost.Ints[(Player, 25)] = 275; // LEVEL
|
||||
var ctx = new VTankLootContext(FakeHost.Create(), Player);
|
||||
var item = new Item("x");
|
||||
|
|
@ -362,9 +371,11 @@ internal static class VTankLootTests
|
|||
Check.True(MC(item, ctx, C(N.CharacterSkillGE, "400", "34")), "skill 400 >= 400");
|
||||
Check.False(MC(item, ctx, C(N.CharacterSkillGE, "401", "34")), "skill 400 < 401");
|
||||
Check.False(MC(item, ctx, C(N.CharacterSkillGE, "1", "33")), "a skill the host has no value for reads 0");
|
||||
// "Base skill" is checked against the training class (2 trained, 3 specialized).
|
||||
Check.True(MC(item, ctx, C(N.CharacterBaseSkill, "34", "3", "3")), "specialized in [3,3]");
|
||||
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "0", "2")), "not in [0,2]");
|
||||
// "Base skill" is the unbuffed skill level (it was the training class, 2 or 3, until 2026-10-31,
|
||||
// so LootSnob's "Heavy Weapon 300" = base heavy in [300, 999] never matched).
|
||||
Check.True(MC(item, ctx, C(N.CharacterBaseSkill, "34", "300", "999")), "base 320 in [300,999]");
|
||||
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "330", "999")), "base 320 not in [330,999] (buffed is 400)");
|
||||
Check.False(MC(item, ctx, C(N.CharacterBaseSkill, "34", "3", "3")), "not the training class any more");
|
||||
Check.True(MC(item, ctx, C(N.CharacterLevelGE, "275")), "level GE at the value");
|
||||
Check.False(MC(item, ctx, C(N.CharacterLevelGE, "276")), "level GE above");
|
||||
Check.True(MC(item, ctx, C(N.CharacterLevelLE, "275")), "level LE at the value");
|
||||
|
|
|
|||
|
|
@ -114,6 +114,8 @@ namespace RynthDefective.Tests
|
|||
Run("quantity: give - the last player or NPC selected, all of it, refusals", QtyGive);
|
||||
Run("quantity: buy - the selected item or by name, checks first, the vendor's answer", QtyBuy);
|
||||
Run("quantity: /rdef qty and the Selection window's view", QtyBoxAndView);
|
||||
Run("quantity: a server's bank - its values, pack + bank, one that can't be read, max", QtyBankRules);
|
||||
Run("quantity: buy and max with no bank, a bank that covers it, one that doesn't, one that can't be read", QtyBankBuy);
|
||||
Run("store: the quantity box setting; files from before read it on", QtyStore);
|
||||
}
|
||||
finally
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ namespace RynthDefective.Tests
|
|||
public string? BuyRefusedWith;
|
||||
public int FreeContainers = 3;
|
||||
public long Burden = -1;
|
||||
public VendorBank BankInfo = VendorBank.None;
|
||||
|
||||
public bool TryGetName(uint id, out string name)
|
||||
{
|
||||
|
|
@ -123,6 +124,7 @@ namespace RynthDefective.Tests
|
|||
}
|
||||
public int FreeContainerSlots() => FreeContainers;
|
||||
public long FreeBurden() => Burden;
|
||||
public VendorBank Bank() => BankInfo;
|
||||
public void Advance(long ms) => NowMs += ms;
|
||||
}
|
||||
|
||||
|
|
@ -779,6 +781,176 @@ namespace RynthDefective.Tests
|
|||
Check(c.Into == 0 && !c.Busy && c.StatusAt(w.NowMs) == null, "logout forgets the action, the pack and the line");
|
||||
}
|
||||
|
||||
// ── A server's bank (2026-10-31) ────────────────────────────────────
|
||||
// A player report: on a server whose bank pays vendors, the box refused a buy the pack alone
|
||||
// couldn't pay for. The server plugin's profile values say whether a bank pays and how much.
|
||||
|
||||
private static void QtyBankRules()
|
||||
{
|
||||
// The values, as the active server's plugin publishes them.
|
||||
Eq(VendorBank.Read(null), VendorBank.None, "no profile: no bank");
|
||||
Eq(VendorBank.Read("{\"values\":{}}"), VendorBank.None, "no bank values: no bank");
|
||||
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":0,\"vendorBankPyreals\":5000}}"), VendorBank.None, "vendorBank 0: no bank, whatever the balance");
|
||||
Eq(VendorBank.Read("not json"), VendorBank.None, "unusable text: no bank");
|
||||
VendorBank read = VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":5000}}");
|
||||
Check(read.Pays && read.Known && read.Pyreals == 5000, "a bank that pays, with its balance");
|
||||
read = VendorBank.Read("{\"values\":{\"vendorBank\":1}}");
|
||||
Check(read.Pays && !read.Known && read.Pyreals == -1, "a bank that pays, balance not said: unread");
|
||||
Check(!VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":-3}}").Known, "a negative balance: unread");
|
||||
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":1e30}}").Pyreals, VendorBank.MaxPyreals, "a huge balance is capped");
|
||||
Eq(VendorBank.Read("{\"values\":{\"vendorBank\":1,\"vendorBankPyreals\":12.9}}").Pyreals, 12L, "whole pyreals");
|
||||
|
||||
// No bank: today's check, word for word.
|
||||
VendorQuote none = Scarabs(funds: 300);
|
||||
Eq(none.Refusal(100), "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 (you can buy 25).", "no bank: the pack's pyreals");
|
||||
Eq(none.MaxBuy(), 25, "no bank: max is what the pack pays for");
|
||||
Eq(none.PriceLine(25), "300 pyreals · you have 300", "no bank: the price line as before");
|
||||
Eq(none.BankNote(100), null, "no bank: no note");
|
||||
Eq(none.MaxNote, string.Empty, "no bank: max needs no note");
|
||||
Eq(none.Spendable, 300L, "no bank: the pack");
|
||||
|
||||
// A bank that's read and covers it: pack + bank, said both ways.
|
||||
VendorQuote covers = Scarabs(funds: 300) with { BankPays = true, BankFunds = 5000 };
|
||||
Eq(covers.Refusal(100), null, "pack 300 + bank 5,000 pay 1,200");
|
||||
Eq(covers.PriceLine(100), "price 1,200; pack 300 + bank 5,000", "the price line says both");
|
||||
Eq(covers.BankNote(100), "The bank pays the 900 pyreals your pack is short.", "the bank's part");
|
||||
Eq(covers.BankNote(25), null, "the pack alone pays 25: no note");
|
||||
Eq(covers.MaxBuy(), 441, "max counts pack + bank: 441 (5,292), not 442 (5,304)");
|
||||
Eq(covers.MaxNote, string.Empty, "a bank that's read: max needs no note");
|
||||
|
||||
// A bank that's read and doesn't cover it.
|
||||
VendorQuote shortOf = Scarabs(funds: 300) with { BankPays = true, BankFunds = 500 };
|
||||
Eq(shortOf.Refusal(100), "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 in your pack + 500 in the bank (you can buy 66).",
|
||||
"pack + bank short: both said, and how many they pay for");
|
||||
Eq(shortOf.MaxBuy(), 66, "max: 800 at 12 is 66");
|
||||
Eq(shortOf.BankNote(100), null, "no note for a buy that can't go");
|
||||
|
||||
// A bank that can't be read: money isn't held against a buy; max is stock, room and burden.
|
||||
VendorQuote unread = Scarabs(funds: 300) with { BankPays = true, BankFunds = -1 };
|
||||
Eq(unread.Refusal(100), null, "the server decides about the money");
|
||||
Eq(unread.Spendable, -1L, "nothing to count against");
|
||||
Eq(unread.BankNote(100), "Your pack has 300 of the 1,200 pyreals: the server's bank may cover it (the server decides).", "the one-line note");
|
||||
Eq(unread.BankNote(25), null, "the pack alone pays: no note");
|
||||
Eq(unread.PriceLine(100), "1,200 pyreals · pack 300 + the bank", "the price line");
|
||||
Eq(unread.MaxBuy(), 5000, "max: 50 free slots of 100");
|
||||
Eq((unread with { FreeBurden = 55 }).MaxBuy(), 11, "max: the burden");
|
||||
Eq((unread with { FreeItemSlots = -1 }).MaxBuy(), 100, "max with nothing known: one stack");
|
||||
Check(unread.MaxNote.Contains("can't be read", StringComparison.Ordinal), "max says what it counts");
|
||||
string? why = unread.Refusal(6000);
|
||||
Check(why != null && why.StartsWith("Not enough room in your packs", StringComparison.Ordinal) && why.Contains("you can buy 5,000", StringComparison.Ordinal),
|
||||
$"room is still checked: {why}");
|
||||
Check((unread with { Unlimited = false, Stock = 5, ListingValue = 50 }).Refusal(6)!.StartsWith("The vendor has only 5", StringComparison.Ordinal), "and the stock");
|
||||
|
||||
// The bank pays pyreal vendors only.
|
||||
var altInfo = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyWcid = 1234, AltCurrencyName = "Ancient Coin", AltCurrencyHave = 3, PlayerCoins = 300 };
|
||||
var relic = new VendorItem { ObjectId = QVScarab, Name = "Relic", UnitValue = 2, Value = 2, StackSize = 1, MaxStackSize = 0, Amount = -1, Unlimited = true };
|
||||
VendorQuote alt = VendorQuote.From(altInfo, relic, 10, 2, -1, new VendorBank(true, 5000));
|
||||
Check(!alt.BankPays && alt.Funds == 3 && alt.Refusal(2) != null, "the vendor's own currency: no bank");
|
||||
var pyInfo = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyHave = -1, PlayerCoins = 300 };
|
||||
VendorQuote py = VendorQuote.From(pyInfo, relic, 10, 2, -1, new VendorBank(true, 5000));
|
||||
Check(py.BankKnown && py.BankFunds == 5000 && py.Spendable == 5300, "a pyreal vendor: pack + bank");
|
||||
Check(!VendorQuote.From(pyInfo, relic, 10, 2, -1).BankPays, "and without a bank, none");
|
||||
|
||||
// The answers.
|
||||
Eq(QtyReplies.BuyRefusal("costs 300 pyreals, you have 200", false), QtyReplies.VendorRefusal("costs 300 pyreals, you have 200"), "no bank: the engine's refusal as before");
|
||||
Check(QtyReplies.BuyRefusal("costs 1200 pyreals, you have 300", true).StartsWith("RynthCore didn't send it: it costs 1200 pyreals, you have 300.", StringComparison.Ordinal),
|
||||
"a bank was to pay: RynthCore's own money check said so");
|
||||
Eq(QtyReplies.BuyRefusal("vendor window is closed", true), QtyReplies.VendorRefusal("vendor window is closed"), "other refusals as before");
|
||||
Check(QtyReplies.NotSold(25, "Mana Scarab", true, 300, "pyreals").Contains("the bank may not cover 300 pyreals", StringComparison.Ordinal), "the server said no, with a bank");
|
||||
Check(QtyReplies.NotSold(25, "Mana Scarab", false, 300, "pyreals").EndsWith("(money, room, or too busy).", StringComparison.Ordinal), "and without one, as before");
|
||||
}
|
||||
|
||||
private static void QtyBankBuy()
|
||||
{
|
||||
// The controller: the box's max and Buy, from the window and from /rdef buy, in each case.
|
||||
// The world: 66 free pack slots (52 + 14), burden unknown, 300 pyreals in the pack.
|
||||
var w = QWorld();
|
||||
var (c, said) = QController();
|
||||
QVendorOpen(w, coins: 300);
|
||||
w.SelectedId = QVScarab;
|
||||
uint Last() => w.NextRequest - 1;
|
||||
|
||||
// No bank: refused before sending, as before; max 25.
|
||||
int sent = w.Sent.Count;
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
Eq(said.Last(), (false, "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 (you can buy 25)."), "no bank: refused");
|
||||
Eq(w.Sent.Count, sent, "nothing sent");
|
||||
c.SetBox(w, QtyAmount.Max);
|
||||
Eq(c.Value, 25, "no bank: the box's max");
|
||||
c.Buy(w, QtyAmount.Max, "");
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 25", "no bank: buy max sends 25");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 300, IsBuy = true };
|
||||
c.Tick(w);
|
||||
Eq(said.Last(), (true, "Bought 25 Mana Scarab for 300 pyreals."), "bought");
|
||||
|
||||
// A bank that's read and covers it.
|
||||
w.BankInfo = new VendorBank(true, 5000);
|
||||
c.SetBox(w, QtyAmount.Max);
|
||||
Eq(c.Value, 441, "the box's max counts pack + bank");
|
||||
Check(said.Last().Text.Contains("price 5,292; pack 300 + bank 5,000", StringComparison.Ordinal), $"/rdef qty says both: {said.Last().Text}");
|
||||
Check(c.View(w)!.Subject.MaxBuy == 441, "the window's max too");
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 100", "100 for 1,200: sent");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 1200, IsBuy = true };
|
||||
c.Tick(w);
|
||||
Eq(said.Last(), (true, "Bought 100 Mana Scarab for 1,200 pyreals."), "bought with the bank's help");
|
||||
DefCommand cmd = DefCommandParser.Parse("buy max Mana Scarab");
|
||||
c.Buy(w, cmd.Amount, cmd.Text);
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 441", "/rdef buy max: pack + bank");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Refused, Message = "costs 5292 pyreals, you have 300" };
|
||||
c.Tick(w);
|
||||
Check(!said.Last().Ok && said.Last().Text.StartsWith("RynthCore didn't send it", StringComparison.Ordinal)
|
||||
&& said.Last().Text.Contains("out of the bank", StringComparison.Ordinal), $"RynthCore's own money check, said: {said.Last().Text}");
|
||||
|
||||
// A bank that's read and doesn't cover it: refused before sending, both said.
|
||||
w.BankInfo = new VendorBank(true, 500);
|
||||
sent = w.Sent.Count;
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
Eq(said.Last(), (false, "Not enough pyreals: 100 Mana Scarab cost 1,200, you have 300 in your pack + 500 in the bank (you can buy 66)."), "pack + bank short: refused");
|
||||
Eq(w.Sent.Count, sent, "nothing sent");
|
||||
c.SetBox(w, QtyAmount.Max);
|
||||
Eq(c.Value, 66, "the box's max: 66");
|
||||
cmd = DefCommandParser.Parse("buy 100 Mana Scarab");
|
||||
c.Buy(w, cmd.Amount, cmd.Text);
|
||||
Check(!said.Last().Ok && said.Last().Text.Contains("in the bank", StringComparison.Ordinal), "/rdef buy 100 replies the same");
|
||||
|
||||
// A bank that can't be read: sent, and the server decides.
|
||||
w.BankInfo = new VendorBank(true);
|
||||
c.SetBox(w, QtyAmount.Max);
|
||||
Eq(c.Value, 6600, "the box's max: 66 free slots of 100 (money not counted)");
|
||||
Check(said.Last().Ok && said.Last().Text.Contains("max counts the vendor's stock, your pack space and burden only", StringComparison.Ordinal),
|
||||
$"with the note: {said.Last().Text}");
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 100", "100 for 1,200 with 300 in the pack: sent");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.Accepted, Estimate = 1200, IsBuy = true };
|
||||
c.Tick(w);
|
||||
Eq(said.Last(), (true, "Bought 100 Mana Scarab for 1,200 pyreals."), "the server's bank covered it");
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.AnsweredNoRefresh, IsBuy = true };
|
||||
c.Tick(w);
|
||||
Check(!said.Last().Ok && said.Last().Text.Contains("the bank may not cover 1,200 pyreals", StringComparison.Ordinal), $"the server's own no, reported: {said.Last().Text}");
|
||||
c.Buy(w, QtyAmount.Of(100), "");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Refused, Message = "costs 1200 pyreals, you have 300" };
|
||||
c.Tick(w);
|
||||
Check(!said.Last().Ok && said.Last().Text.StartsWith("RynthCore didn't send it", StringComparison.Ordinal), "RynthCore's own money check, said");
|
||||
cmd = DefCommandParser.Parse("buy max Mana Scarab");
|
||||
c.Buy(w, cmd.Amount, cmd.Text);
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 6600", "/rdef buy max: room only");
|
||||
w.Status = null;
|
||||
w.Advance(QuantityController.BuyAnswerMs);
|
||||
c.Tick(w);
|
||||
Check(!said.Last().Ok && said.Last().Text.StartsWith("No answer about 6,600 Mana Scarab", StringComparison.Ordinal), "and it always answers");
|
||||
c.Buy(w, QtyAmount.Of(7000), "");
|
||||
Check(!said.Last().Ok && said.Last().Text.StartsWith("Not enough room in your packs", StringComparison.Ordinal), "room is still checked first");
|
||||
|
||||
// The pack alone pays: the same with any bank.
|
||||
c.Buy(w, QtyAmount.Of(20), "");
|
||||
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 20", "20 for 240: sent");
|
||||
w.Status = new VendorTradeStatus { RequestId = Last(), State = VendorTradeState.Done, Result = VendorTradeResult.AnsweredNoRefresh, IsBuy = true };
|
||||
c.Tick(w);
|
||||
Check(said.Last().Text.EndsWith("(money, room, or too busy).", StringComparison.Ordinal), "the pack paid: no bank in the answer");
|
||||
}
|
||||
|
||||
private static void QtyStore()
|
||||
{
|
||||
var store = new DefStore(System.IO.Path.Combine(_temp, "qty"));
|
||||
|
|
|
|||
|
|
@ -41,6 +41,10 @@
|
|||
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
|
||||
<!-- The server plugin's bank values for the quantity box's buys (2026-10-31). -->
|
||||
<Compile Include="..\..\Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerStateClient.cs" Link="Shared\ServerStateClient.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
|
||||
<!-- The shortcut bar, panel buttons and Selection windows (2026-10-22) draw with the shared ImGui look. -->
|
||||
<Compile Include="..\..\Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
|
|
|
|||
166
Tools/RynthNet.Tests/LookTests.cs
Normal file
166
Tools/RynthNet.Tests/LookTests.cs
Normal file
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ internal static partial class Program
|
|||
Vitals();
|
||||
WindowChecks();
|
||||
Replies();
|
||||
LookChecks();
|
||||
|
||||
Console.WriteLine($"{_checks} checks, {_failed} failed");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
|
|
@ -25,6 +28,10 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\AtlasNames.cs" Link="RynthNet\AtlasNames.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersManifest.cs" Link="RynthNet\CharactersManifest.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\CommandParser.cs" Link="RynthNet\CommandParser.cs" />
|
||||
<!-- The window's two looks (minimal / full) and where the choice is kept (settings.json, under the test's own folder). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersLook.cs" Link="RynthNet\CharactersLook.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\RynthNetSettings.cs" Link="RynthNet\RynthNetSettings.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthIcons.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
Loading…
Reference in a new issue