Snapshot for release 2026.10.30.1 (internal 50ae062)

This commit is contained in:
Tom Bohar 2026-10-31 06:01:30 -04:00
commit 76aca938b6
52 changed files with 6242 additions and 60 deletions

View file

@ -233,7 +233,7 @@ public partial class BuffManager
// Cast on the shield in this run: done, unless a higher level is castable now.
if (_shieldRunLevels.TryGetValue(spell.Family, out int ran)) return UpgradeParked(spell.Family) || level <= ran;
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, BatchRebuffLineSec);
}
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
if (!_shieldSpellTimers.TryGetValue(ShieldKey(shieldId, spell.Family), out ItemSpellRecord? rec)) return false;

View file

@ -352,6 +352,57 @@ public partial class BuffManager : IDisposable
private bool InCombatNow() => InCombatOverride?.Invoke()
?? _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
// ── Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes; VTank's "idlebufftopoff") ──
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
// (RebuffSecondsRemaining), or dispelled, is recast as always, in a fight or not. With the option
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
// at the next safe point (no cast in flight) when the bot stops being idle; the regular rules take
// over. Margin 0: nothing added. Force Buff, heals and vitals are not touched.
/// <summary>The bot is idle enough for an early top-off (set by RynthAiPlugin.IdleForBuffTopOff;
/// tests set it). Null = never: no early top-off.</summary>
internal Func<bool>? IdleForTopOff { get; set; }
/// <summary>Rebuff When Idle's margin in seconds (0 when off or set to 0).</summary>
internal int IdleMarginSec => _settings.RebuffWhenIdle ? Math.Max(0, _settings.RebuffIdleMarginMinutes) * 60 : 0;
/// <summary>An early top-off may run now: the option is on with a margin, and the bot is idle.</summary>
internal bool IdleTopOffNow()
{
if (IdleMarginSec <= 0 || IdleForTopOff == null) return false;
try { return IdleForTopOff(); } catch { return false; }
}
/// <summary>The line a buff is rebuffed at now: Rebuff With, plus the idle margin while an idle
/// top-off may run.</summary>
internal int RebuffLineSec() => _settings.RebuffSecondsRemaining + (IdleTopOffNow() ? IdleMarginSec : 0);
/// <summary>The rebuff run under way was started by the idle margin alone (nothing was at or under
/// Rebuff With): it stops when the bot stops being idle.</summary>
private bool _isIdleTopOffRun;
/// <summary>The line an automatic run tops off under (with RebuffTopOffSecondsRemaining): Rebuff With,
/// plus the margin for an early top-off run, so the buff that started it is always in it.</summary>
private int BatchRebuffLineSec => _settings.RebuffSecondsRemaining + (_isIdleTopOffRun ? IdleMarginSec : 0);
/// <summary>Early top-off runs started (tests, status).</summary>
internal int IdleTopOffRuns { get; private set; }
/// <summary>An early top-off run stops (a fight, a corpse, salvage): the regular rules take over.</summary>
private void EndIdleTopOffRun()
{
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
ClearRunFamilies();
_chain.PassEnd("idle top-off stopped", s => _host.Log(s));
_host.Log("[Buff] Rebuff When Idle: the bot is no longer idle (a fight, a corpse or salvage): the early top-off stops; buffs under Rebuff With are still rebuffed as usual.");
}
/// <summary>
/// A spell's mana cost: its BaseMana from the portal.dat SpellTable, the most it can cost
/// (ACE Creature.CalculateManaUsage; Mana Conversion only lowers it on a skill roll, so the
@ -1048,6 +1099,7 @@ public partial class BuffManager : IDisposable
{
_isForceRebuffing = true;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
ClearRunFamilies();
_buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns
_silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too
@ -1076,6 +1128,7 @@ public partial class BuffManager : IDisposable
{
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
_isRechargingMana = false;
_isRechargingStamina = false;
_isHealingSelf = false;
@ -1348,6 +1401,12 @@ public partial class BuffManager : IDisposable
// A Magic stance we asked for: watch the client's mode every tick (see ObserveStance).
ObserveStance();
// Rebuff When Idle: an early top-off run stops once the bot isn't idle (a fight, a corpse,
// salvage), at the first heartbeat with no cast of ours in flight (a sent cast resolves first),
// and before the arbiter reads NeedsAnyBuff this tick. The regular rules take over.
if (_isIdleTopOffRun && _isForceRebuffing && _pendingSpellId == 0 && !IdleTopOffNow())
EndIdleTopOffRun();
// RefreshFromLiveMemory at OnLoginComplete fails when the server-time
// packet hasn't landed yet (GetServerTime returns 0). On those
// logins we have NO timers and would recast every buff that has
@ -1863,6 +1922,7 @@ public partial class BuffManager : IDisposable
bool wasAutoBatch = _isAutoBatchRebuff;
_isForceRebuffing = false;
_isAutoBatchRebuff = false;
_isIdleTopOffRun = false;
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families{(wasAutoBatch ? " (auto batch)" : "")}");
// Order matters: the flag must already be false (IsBuffActive
// short-circuits on _forceRebuffCastFamilies while it is set, so
@ -2855,7 +2915,9 @@ public partial class BuffManager : IDisposable
public bool NeedsAnyBuff()
{
if (!_settings.EnableBuffing) return false;
return _isForceRebuffing || AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
// RebuffLineSec: Rebuff With, plus Rebuff When Idle's margin while the bot is idle. An early
// top-off run ends at the heartbeat (before the arbiter) once the bot isn't idle.
return _isForceRebuffing || AnyBuffBelowThreshold(BuildDynamicBuffList(), RebuffLineSec());
}
// Returns true if any castable buff in the list has < thresholdSec remaining.
@ -2904,8 +2966,18 @@ public partial class BuffManager : IDisposable
// Auto batch-rebuff: when any buff drops below the configured threshold,
// trigger a full rebuff so ALL timers re-align in one session rather than
// each buff trickling in one at a time as it individually expires.
if (!_isForceRebuffing && AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining))
int rebuffLine = _isForceRebuffing ? 0 : RebuffLineSec();
if (!_isForceRebuffing && AnyBuffBelowThreshold(BuildDynamicBuffList(), rebuffLine))
{
// Rebuff When Idle: a run the margin alone started (nothing at or under Rebuff With) is an
// early top-off, which stops if the bot stops being idle.
_isIdleTopOffRun = rebuffLine > _settings.RebuffSecondsRemaining
&& !AnyBuffBelowThreshold(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
if (_isIdleTopOffRun)
{
IdleTopOffRuns++;
_host.Log($"[Buff] Rebuff When Idle: idle, and a buff has under {rebuffLine} s left (Rebuff With {_settings.RebuffSecondsRemaining} s + {_settings.RebuffIdleMarginMinutes} min): topping off early.");
}
// Batch trigger — reuse FR family-tracking but do NOT clear timers.
// ForceFullRebuff clears _ramBuffTimers, which causes an immediate
// re-trigger: any spell that can't be resolved (spellId=0) never
@ -3301,7 +3373,7 @@ public partial class BuffManager : IDisposable
return UpgradeParked(targetSpell.Family)
|| !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, BatchRebuffLineSec);
}
int targetLevel = GetSpellLevel(targetSpell);

View file

@ -107,6 +107,9 @@ internal sealed class HudController
/// <summary>The Mini Remote's session stats (the same SessionStats code as RynthTracker); null if it failed to start.</summary>
public RynthCore.Plugin.Shared.SessionStatsTracker? SessionStats { get; init; }
/// <summary>Opens or closes the Monster Stats window (the Session Stats view's "Monster stats" button); null without one.</summary>
public Action? ToggleMonsterStats { get; init; }
/// <summary>Latest pack view (render thread safe).</summary>
public HudPackSnapshot Pack => _pack;

View file

@ -524,6 +524,13 @@ internal sealed class MiniRemoteHud
ImGui.EndTable();
}
RenderStatButtons(_hud.Remote());
// Combat per kind of monster since login: the fallback Monster Stats window, only on an engine whose
// Damage panel doesn't show the numbers (RynthAiPlugin.MonsterStats.cs; null otherwise).
if (_hud.ToggleMonsterStats is Action toggle)
{
if (ImGui.Button("Monster stats", new Vector2(Math.Max(ImGui.GetContentRegionAvail().X, 140f), 0))) toggle();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Evades, resists, hits and kills per kind of monster since login (/ra mstats).");
}
}
/// <summary>One Session Stats row: label, session total, per hour (and an optional tooltip on the label).</summary>

View file

@ -77,19 +77,28 @@ internal static class SectionsManifest
public const string DashboardTitle = "RynthAi", DashboardSurface = "window:dashboard";
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/>.
/// The Monster Stats window (RynthAiPlugin.MonsterStats.cs, 2026-10-30): combat per kind of monster
/// since login, drawn by RynthAi in the engine's frame (plugin API v89), declared only where the
/// Damage panel doesn't show the numbers under each monster. No bar button: the Session Stats view's
/// "Monster stats" button and /ra mstats show open it.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false)
public const string MonsterStatsTitle = RynthAiPlugin.MonsterStatsTitle, MonsterStatsSurface = RynthAiPlugin.MonsterStatsSurface;
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/> and the Monster Stats window when <paramref name="monsterStats"/>.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false, bool monsterStats = false)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
if (dashboard || monsterStats)
w.WriteStartArray("windows");
if (dashboard)
{
w.WriteStartArray("windows");
w.WriteStartObject();
w.WriteString("id", "dashboard");
w.WriteString("title", DashboardTitle);
@ -105,8 +114,24 @@ internal static class SectionsManifest
w.WriteString("chrome", "none");
w.WriteBoolean("fitHeight", true);
w.WriteEndObject();
w.WriteEndArray();
}
if (monsterStats)
{
w.WriteStartObject();
w.WriteString("id", "monsterstats");
w.WriteString("title", MonsterStatsTitle);
w.WriteString("surface", MonsterStatsSurface);
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.ChartBar);
w.WriteNumber("width", 560);
w.WriteNumber("height", 360);
w.WriteNumber("minWidth", 380);
w.WriteNumber("minHeight", 160);
w.WriteBoolean("bar", false);
w.WriteBoolean("edgeToEdge", true);
w.WriteEndObject();
}
if (dashboard || monsterStats)
w.WriteEndArray();
w.WriteStartArray("sections");
foreach (Section s in sections)
{

View file

@ -926,6 +926,26 @@ internal sealed class LegacyAdvancedSettingsUi
case "Buffing":
ImGui.Checkbox("Enable Buffing", ref _settings.EnableBuffing);
ImGui.Checkbox("Rebuff When Idle", ref _settings.RebuffWhenIdle);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Top buffs off early between fights. When the bot is idle (no target, no\n" +
"monster within Monster Range, no corpse to loot), it rebuffs as soon as a\n" +
"buff has 'Rebuff With' + 'Idle Margin' left, instead of waiting for\n" +
"'Rebuff With'. So fewer buffs run out in the next fight.\n" +
"It never stops a rebuff: a buff under 'Rebuff With' (or dispelled) is\n" +
"recast as always, in a fight too. An early top-off never starts in a\n" +
"fight, and one under way stops when a fight starts.");
if (_settings.RebuffWhenIdle)
{
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Idle Margin (minutes)", ref _settings.RebuffIdleMarginMinutes, 0, 60);
if (_settings.RebuffIdleMarginMinutes < 0) _settings.RebuffIdleMarginMinutes = 0;
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"How much earlier than 'Rebuff With' an idle top-off may start.\n" +
"Default 2: with 'Rebuff With' 300 s, an idle bot rebuffs at 7 minutes\n" +
"left instead of 5. 0 = Rebuff When Idle adds nothing.");
}
ImGui.Spacing();
ImGui.SetNextItemWidth(180);

View file

@ -1303,6 +1303,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffWhenIdle = s.RebuffWhenIdle,
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
@ -1565,6 +1566,7 @@ internal sealed partial class LegacyDashboardRenderer
s.RebuffWhenIdle = p.RebuffWhenIdle;
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
if (p.RebuffIdleMarginMinutes is int idleMargin) s.RebuffIdleMarginMinutes = Math.Max(0, idleMargin); // absent = unchanged
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
@ -2051,6 +2053,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.RebuffIdleMarginMinutes = tmp.RebuffIdleMarginMinutes;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;

View file

@ -319,8 +319,20 @@ public sealed class LegacyUiSettings
/// </summary>
[JsonPropertyName("FastWeaponSwapOn")]
public bool FastWeaponSwap = true;
/// <summary>
/// Rebuff When Idle (VTank's "idlebufftopoff"): between fights, top buffs off early. When the bot
/// is idle (no fight target, no monster within Monster Range, no corpse to loot, no salvage), a
/// rebuff starts once a buff has RebuffSecondsRemaining + RebuffIdleMarginMinutes left instead of
/// waiting for RebuffSecondsRemaining. The regular rebuff is unchanged, in a fight or not.
/// Read by BuffManager.RebuffLineSec (nothing read it before 2026-10-30). Off by default.
/// </summary>
public bool RebuffWhenIdle;
/// <summary>
/// Rebuff When Idle's margin, minutes: how much earlier than RebuffSecondsRemaining an idle
/// top-off may start. Default 2; 0 = the option adds nothing. A profile saved without it loads 2.
/// </summary>
public int RebuffIdleMarginMinutes = 2;
/// <summary>
/// Re-cast a self buff when its remaining duration drops below this many seconds.
/// Default 300 (5 minutes). Lower values rebuff more eagerly; very low values
/// (under ~60s) risk recasting between an old buff dropping and the new one
@ -1290,6 +1302,8 @@ public sealed class SettingsBridgePayload
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; }
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
// Nullable: the engine's Settings face doesn't know it; absent = unchanged (0 is a real value).
public int? RebuffIdleMarginMinutes { get; set; }
// Nullable: an engine that predates the setting doesn't send it, and a save from its
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }

View file

@ -3698,6 +3698,7 @@ internal sealed partial class ExpressionEngine
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["RebuffIdleMarginMinutes"] = (() => I(s.RebuffIdleMarginMinutes), v => { if (int.TryParse(v, out int i)) s.RebuffIdleMarginMinutes = Math.Max(0, i); }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),

View file

@ -0,0 +1,83 @@
// ============================================================================
// RynthAi - MonsterStats/CombatEvents.cs
// Melee and missile attacks between you and a monster, from the server's own
// combat game events (plugin API v78 server messages, opcode 0xF7B0), which
// name the monster. The client turns the same events into chat lines ("X
// evaded your attack.", "You evaded X!", "You slash X for 12 points of ..."),
// which are not read: the typed event is exact and can't be imitated.
//
// 0x01B1 AttackerNotification you hit it (name, type, share, damage, crit, conditions)
// 0x01B2 DefenderNotification it hit you (name, type, share, damage, location, crit, conditions)
// 0x01B3 EvasionAttackerNotification it evaded your attack (name)
// 0x01B4 EvasionDefenderNotification you evaded its attack (name)
//
// The killing blow sends no 0x01B1: the kill notice comes instead (ACE
// Player_Combat.cs; MonsterCombatStats.OnKill counts it). Spells send none of
// these (CombatLines.cs reads theirs). Pure; uses the SDK's bounds-checked reader.
// ============================================================================
using System;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>One melee or missile attack, from whose side.</summary>
internal enum PhysicalEvent
{
/// <summary>Your attack hit it.</summary>
YouHit,
/// <summary>It evaded your attack.</summary>
ItEvaded,
/// <summary>Its attack hit you.</summary>
ItHit,
/// <summary>You evaded its attack.</summary>
YouEvaded,
}
internal static class CombatEvents
{
public const uint AttackerNotification = 0x01B1;
public const uint DefenderNotification = 0x01B2;
public const uint EvasionAttackerNotification = 0x01B3;
public const uint EvasionDefenderNotification = 0x01B4;
/// <summary>The game events to ask the engine for (RynthAiPlugin.Initialize).</summary>
public static readonly uint[] GameEvents =
{ AttackerNotification, DefenderNotification, EvasionAttackerNotification, EvasionDefenderNotification };
public static bool IsCombatEvent(uint eventType) =>
eventType is AttackerNotification or DefenderNotification or EvasionAttackerNotification or EvasionDefenderNotification;
/// <summary>
/// Reads one combat game event's body (the bytes after its event type). True with what
/// happened, the monster's name and the damage of a hit (0 for an evade); false for another
/// event or a body too short to hold its fields.
/// </summary>
public static bool TryParse(uint eventType, ReadOnlySpan<byte> body, out PhysicalEvent kind, out string name, out int damage)
{
kind = default;
name = string.Empty;
damage = 0;
var r = new NetReader(body);
switch (eventType)
{
case AttackerNotification:
case DefenderNotification:
if (!r.String16L(out name) || !r.U32(out _) || !r.F64(out _) || !r.U32(out uint dmg)) return false;
damage = dmg > int.MaxValue ? int.MaxValue : (int)dmg;
kind = eventType == AttackerNotification ? PhysicalEvent.YouHit : PhysicalEvent.ItHit;
break;
case EvasionAttackerNotification:
if (!r.String16L(out name)) return false;
kind = PhysicalEvent.ItEvaded;
break;
case EvasionDefenderNotification:
if (!r.String16L(out name)) return false;
kind = PhysicalEvent.YouEvaded;
break;
default:
return false;
}
name = name.Trim();
return name.Length > 0;
}
}

View file

@ -0,0 +1,172 @@
// ============================================================================
// RynthAi - MonsterStats/CombatLines.cs
// The spell lines of the combat log that say what became of a spell between
// you and a monster: it landed, it was resisted, or it could do nothing. The
// server reports spells only as text (Magic chat, type 7); swings, hits and
// evades come as typed game events (CombatEvents.cs), so no melee or missile
// line is read here.
//
// One table, the server's exact strings (ACE's, which follow retail; the ACE
// source line is next to each row). MonsterStatsTests checks every row and the
// near-misses below. Lines whose form is also used for items ("Frost Hand
// Wraps cast ... on you") are marked MayBeItem: the plugin counts them only
// for a creature (RynthAiPlugin.MonsterStats.cs).
//
// Not counted, on purpose:
// "You cast X on yourself..." your own buffs
// "<item> cast X on you" an item's spell (MayBeItem rows)
// "X tried and failed to cast a spell at you!" a fizzle: it never reached you
// "You <verb> X for N points of periodic nether damage!" a damage-over-time tick, not a cast
// "You receive N points of periodic ..." the same, on you
// "With S you restore N points of V to X." / "X casts S and restores ..." heals
// "You lose N points of V due to casting S on X" an infusion you cast (it gives)
// "You gain N points of V due to X casting S on you" a gift to you
// "Your cloak reduced the damage ..." / "The cloak of X reduced ..." a cloak (player gear)
// "X evaded your attack." / "You evaded X!" / "You slash X for N points of slashing damage!"
// the client's own lines for the typed events
// Absorbs and partial resists: ACE reduces magic damage by absorb gear without a
// word (the damage line just shows less), and a resist is all or nothing; there
// is no line to count.
//
// Pure (no host), so the host tests drive it directly.
// ============================================================================
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>What became of one spell.</summary>
internal enum SpellOutcome
{
/// <summary>It reached its target and took hold (damage, a drain, an enchantment).</summary>
Landed,
/// <summary>The target's magic defense stopped it.</summary>
Resisted,
/// <summary>It passed the resist check but could do nothing (the target is immune to it).</summary>
NoEffect,
}
/// <summary>
/// One spell line: whose spell (<see cref="ByYou"/>: yours at <see cref="Name"/>, else
/// <see cref="Name"/>'s at you), what became of it, the health damage it did (0 when the line
/// gives none), and whether the name may be an item's (<see cref="MayBeItem"/>).
/// </summary>
internal readonly record struct CombatLine(string Rule, bool ByYou, SpellOutcome Outcome, string Name, int Damage, bool MayBeItem);
internal static class CombatLines
{
/// <summary>One form of line: its id, whose spell and its outcome, a word it must contain, and the pattern.</summary>
internal sealed record Row(string Id, bool ByYou, SpellOutcome Outcome, bool MayBeItem, string Hint, string Source, Regex Pattern);
private const RegexOptions Opt = RegexOptions.CultureInvariant;
// "Critical hit! ", "Overpower! ", "Sneak Attack! " in front of a damage line (SpellProjectile.cs critMsg etc.).
private const string Prefix = "(?:(?:Critical hit|Overpower|Sneak Attack)! )*";
private const string Num = @"(?<n>\d[\d,]*)";
private const string Vital = "(?<vital>health|stamina|mana)";
// What follows an enchantment that met one already there (WorldObject_Magic.cs suffix).
private const string EnchantTail = ", (?:refreshing|surpassing|but it is surpassed by) .+";
/// <summary>Every line counted, in the order tried.</summary>
internal static readonly Row[] Rows =
{
// ── Your spells at a monster ──
new("you-damage", true, SpellOutcome.Landed, false, " points with ",
"SpellProjectile.cs: {crit}{overpower}{sneak}You {verb} {target} for {amount} points with {spell}.{critProt}",
new Regex("^" + Prefix + "You (?<verb>[a-z]+) (?<name>.+?) for " + Num + " points? with (?<spell>.+?)\\."
+ "(?: Your critical hit was avoided with their augmentation!)?$", Opt)),
new("you-drain", true, SpellOutcome.Landed, false, " you drain ",
"SpellProjectile.cs / WorldObject_Magic.cs: With {spell} you drain {amount} points of {vital} from {target}.",
new Regex("^With (?<spell>.+?) you drain " + Num + " points? of " + Vital + " from (?<name>.+?)\\.$", Opt)),
new("you-transfer", true, SpellOutcome.Landed, false, " due to casting ",
"WorldObject_Magic.cs: You gain {n} points of {vital} due to casting {spell} on {target}",
new Regex("^You gain " + Num + " points? of " + Vital + " due to casting (?<spell>.+?) on (?<name>.+)$", Opt)),
new("you-enchant", true, SpellOutcome.Landed, true, "You cast ",
"WorldObject_Magic.cs: You cast {spell} on {target}{suffix} (and the dispel forms)",
new Regex("^You cast (?<spell>.+?) on (?<name>.+?)(?:" + EnchantTail + "| and dispel: .+|, but the dispel fails\\.)?$", Opt)),
new("you-resisted", true, SpellOutcome.Resisted, false, " resists your spell",
"WorldObject_Magic.cs: {target} resists your spell",
new Regex("^(?<name>.+) resists your spell$", Opt)),
new("you-noeffect", true, SpellOutcome.NoEffect, false, "You fail to affect ",
"Player_Magic.cs / WorldObject_Magic.cs: You fail to affect {target} with {spell}",
new Regex("^You fail to affect (?<name>.+?) with (?<spell>.+)$", Opt)),
// ── A monster's spells at you ──
new("it-damage", false, SpellOutcome.Landed, false, " you for ",
"SpellProjectile.cs: {crit}{overpower}{sneak}{caster} {verbs} you for {amount} points with {spell}.{critProt}",
new Regex("^" + Prefix + "(?<name>.+?) (?<verb>[a-z]+) you for " + Num + " points? with (?<spell>.+?)\\."
+ "(?: Your augmentation allows you to avoid a critical hit!)?$", Opt)),
new("it-drain", false, SpellOutcome.Landed, false, " and drains ",
"SpellProjectile.cs / WorldObject_Magic.cs: {caster} casts {spell} and drains {amount} points of your {vital}.",
new Regex("^(?<name>.+?) casts (?<spell>.+?) and drains " + Num + " points? of your " + Vital + "\\.$", Opt)),
new("it-transfer", false, SpellOutcome.Landed, false, " casting ",
"WorldObject_Magic.cs: You lose {n} points of {vital} due to {caster} casting {spell} on you",
new Regex("^You lose " + Num + " points? of " + Vital + " due to (?<name>.+?) casting (?<spell>.+?) on you$", Opt)),
new("it-resisted", false, SpellOutcome.Resisted, false, "You resist the spell cast by ",
"WorldObject_Magic.cs: You resist the spell cast by {caster}",
new Regex("^You resist the spell cast by (?<name>.+)$", Opt)),
new("it-enchant", false, SpellOutcome.Landed, true, " cast ",
"WorldObject_Magic.cs: {caster} cast {spell} on you{suffix} / on your {item}{suffix}",
new Regex("^(?<name>.+?) cast (?<spell>.+?) on (?:you|your (?<item>.+?))(?:" + EnchantTail + ")?$", Opt)),
new("it-dispel", false, SpellOutcome.Landed, true, " casts ",
"WorldObject_Magic.cs: {caster} casts {spell} on you and dispels: {list}. / , but the dispel fails.",
new Regex("^(?<name>.+?) casts (?<spell>.+?) on you(?: and dispels: .+|, but the dispel fails\\.)$", Opt)),
new("it-noeffect", false, SpellOutcome.NoEffect, false, " fails to affect you with ",
"WorldObject_Magic.cs: {caster} fails to affect you with {spell}",
new Regex("^(?<name>.+?) fails to affect you with (?<spell>.+)$", Opt)),
};
/// <summary>
/// Reads one chat line. True for a spell line of the table, with whose spell it was, its
/// outcome, the monster's name and the health damage; false for anything else (and for a
/// line about yourself). The caller has already left out lines in a player's chat types.
/// </summary>
public static bool TryParse(string? text, out CombatLine line)
{
line = default;
if (string.IsNullOrEmpty(text)) return false;
string t = text.Trim();
if (t.Length < 8) return false;
foreach (Row row in Rows)
{
if (t.IndexOf(row.Hint, StringComparison.Ordinal) < 0) continue;
Match m = row.Pattern.Match(t);
if (!m.Success) continue;
string name = m.Groups["name"].Value.Trim();
if (!IsMonsterName(name)) return false;
int damage = 0;
Group n = m.Groups["n"];
Group vital = m.Groups["vital"];
// Damage is health taken: a damage line's amount, a health drain's; not stamina or mana,
// and not what a transfer gave you (the line says what you gained, not what it lost).
bool health = !vital.Success || vital.Value == "health";
if (n.Success && health && row.Id is not "you-transfer") damage = ParseAmount(n.Value);
line = new CombatLine(row.Id, row.ByYou, row.Outcome, name, damage, row.MayBeItem);
return true;
}
return false;
}
/// <summary>Not you: "yourself" (and "yourself and lose ..."), "you", "your ...", or nothing.</summary>
private static bool IsMonsterName(string name)
{
if (name.Length == 0) return false;
if (name.Equals("You", StringComparison.OrdinalIgnoreCase)) return false;
if (name.StartsWith("yourself", StringComparison.OrdinalIgnoreCase)) return false;
if (name.StartsWith("your ", StringComparison.OrdinalIgnoreCase)) return false;
return true;
}
/// <summary>"1,234" as 1234; 0 for anything that isn't a number up to a million.</summary>
internal static int ParseAmount(string s)
{
long v = 0;
foreach (char c in s)
{
if (c == ',') continue;
if (c < '0' || c > '9') return 0;
v = v * 10 + (c - '0');
if (v > 1_000_000) return 0;
}
return (int)v;
}
}

View file

@ -0,0 +1,288 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterCombatStats.cs
// The combat since login (or the last reset) between you and each kind of
// monster (by name: every Drudge Skulker together), in both directions:
//
// You at it swings = hits + its evades (melee and missile), with the
// killing blow counted as a hit; your spells that reached it
// = landed + resisted + no effect; kills; damage dealt.
// It at you attacks = hits + your evades; its spells that reached you
// = landed + resisted + no effect; damage taken.
// Rates it evades (its evades / your swings), it resists (its
// resists / your spells), you evade, you resist.
//
// Fed by CombatEvents (typed melee/missile events), CombatLines (spell lines)
// and the kill notice; shown under each monster in the Damage panel (the row's
// "mstats"), else by MonsterStatsWindow; printed by /ra mstats,
// kept across a hot reload by MonsterStatsStore. Pure: every call takes the
// time, so the tests drive it. One thread (the plugin pump); the window reads
// the immutable rows of Snapshot().
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>How the killing blow was struck (the player's combat mode at the kill notice).</summary>
internal enum KillBlow
{
/// <summary>Not known (peace mode): the kill is counted, the blow isn't.</summary>
None,
/// <summary>Melee or missile: a hit.</summary>
Physical,
/// <summary>Magic: a landed spell.</summary>
Spell,
}
/// <summary>One monster's numbers, as of one moment (immutable).</summary>
internal sealed record MonsterStatsRow(
string Name,
int Hits, int Evaded, int SpellsLanded, int Resisted, int NoEffect, int Kills, long DamageDealt,
int HitsTaken, int YouEvaded, int SpellsTaken, int YouResisted, int NoEffectOnYou, long DamageTaken,
long FirstUtcTicks, long LastUtcTicks)
{
/// <summary>Your melee and missile attacks at it: hits and the ones it evaded.</summary>
public int Swings => Hits + Evaded;
/// <summary>Your spells that reached it.</summary>
public int SpellsAtIt => SpellsLanded + Resisted + NoEffect;
/// <summary>Its melee and missile attacks at you.</summary>
public int Attacks => HitsTaken + YouEvaded;
/// <summary>Its spells that reached you.</summary>
public int SpellsAtYou => SpellsTaken + YouResisted + NoEffectOnYou;
public double? ItEvadesRate => MonsterCombatStats.Rate(Evaded, Swings);
public double? ItResistsRate => MonsterCombatStats.Rate(Resisted, SpellsAtIt);
public double? YouEvadeRate => MonsterCombatStats.Rate(YouEvaded, Attacks);
public double? YouResistRate => MonsterCombatStats.Rate(YouResisted, SpellsAtYou);
/// <summary>Nothing counted (a fresh row).</summary>
public bool IsEmpty => Swings == 0 && SpellsAtIt == 0 && Kills == 0 && Attacks == 0 && SpellsAtYou == 0;
}
internal sealed class MonsterCombatStats
{
/// <summary>Kinds of monster kept at once; past it the one seen longest ago goes.</summary>
public const int MaxMonsters = 400;
private sealed class Entry
{
public string Name = "";
public int Hits, Evaded, SpellsLanded, Resisted, NoEffect, Kills;
public long DamageDealt;
public int HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou;
public long DamageTaken;
public long FirstUtcTicks, LastUtcTicks;
public MonsterStatsRow ToRow() => new(Name, Hits, Evaded, SpellsLanded, Resisted, NoEffect, Kills, DamageDealt,
HitsTaken, YouEvaded, SpellsTaken, YouResisted, NoEffectOnYou, DamageTaken, FirstUtcTicks, LastUtcTicks);
}
private readonly Dictionary<string, Entry> _byName = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Goes up on every change (the window and the save follow it).</summary>
public int Version { get; private set; }
/// <summary>Kinds of monster with numbers.</summary>
public int Count => _byName.Count;
/// <summary>A share as 0..1, or null when there is nothing to divide by.</summary>
public static double? Rate(int part, int whole) => whole > 0 ? (double)part / whole : null;
/// <summary>"23%" (whole from 10% up), "4.5%" (one decimal below), or "-" with nothing to divide by.</summary>
public static string Percent(double? rate)
{
if (rate is not double r || !double.IsFinite(r)) return "-";
double p = Math.Clamp(r, 0, 1) * 100;
p = p >= 10 ? Math.Round(p, MidpointRounding.AwayFromZero) : Math.Round(p, 1, MidpointRounding.AwayFromZero);
return p.ToString("0.#", CultureInfo.InvariantCulture) + "%";
}
/// <summary>True when <paramref name="name"/> has numbers this session.</summary>
public bool IsTracked(string? name) => !string.IsNullOrEmpty(name) && _byName.ContainsKey(name);
// ── Events ───────────────────────────────────────────────────────────
/// <summary>A melee or missile attack, either way (CombatEvents).</summary>
public void OnPhysical(PhysicalEvent kind, string name, int damage, DateTime nowUtc)
{
Entry? e = Touch(name, nowUtc);
if (e == null) return;
int dmg = Math.Max(0, damage);
switch (kind)
{
case PhysicalEvent.YouHit: e.Hits++; e.DamageDealt += dmg; break;
case PhysicalEvent.ItEvaded: e.Evaded++; break;
case PhysicalEvent.ItHit: e.HitsTaken++; e.DamageTaken += dmg; break;
case PhysicalEvent.YouEvaded: e.YouEvaded++; break;
}
Version++;
}
/// <summary>A spell line (CombatLines), either way.</summary>
public void OnSpell(CombatLine line, DateTime nowUtc)
{
Entry? e = Touch(line.Name, nowUtc);
if (e == null) return;
int dmg = Math.Max(0, line.Damage);
if (line.ByYou)
{
switch (line.Outcome)
{
case SpellOutcome.Landed: e.SpellsLanded++; e.DamageDealt += dmg; break;
case SpellOutcome.Resisted: e.Resisted++; break;
case SpellOutcome.NoEffect: e.NoEffect++; break;
}
}
else
{
switch (line.Outcome)
{
case SpellOutcome.Landed: e.SpellsTaken++; e.DamageTaken += dmg; break;
case SpellOutcome.Resisted: e.YouResisted++; break;
case SpellOutcome.NoEffect: e.NoEffectOnYou++; break;
}
}
Version++;
}
/// <summary>
/// The server's kill notice ("You killed Drudge Skulker!", "Drudge Skulker died!", ...): one kill
/// for the monster it names, and the killing blow, which sent no hit or damage line, as a hit
/// (<see cref="KillBlow.Physical"/>) or a landed spell (<see cref="KillBlow.Spell"/>). The monster
/// is the longest name with numbers that the notice contains, else <paramref name="nameInNotice"/>'s
/// answer (the plugin looks among the creatures around: a monster killed by its first blow has
/// no numbers yet). Returns the name credited, or null when the notice names none.
/// </summary>
public string? OnKill(string? notice, KillBlow blow, DateTime nowUtc, Func<string, string?>? nameInNotice = null)
{
if (string.IsNullOrWhiteSpace(notice)) return null;
string? name = LongestNameIn(notice);
if (name == null && nameInNotice != null)
{
string? n = nameInNotice(notice);
if (!string.IsNullOrWhiteSpace(n) && notice.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) name = n.Trim();
}
if (name == null) return null;
Entry? e = Touch(name, nowUtc);
if (e == null) return null;
e.Kills++;
if (blow == KillBlow.Physical) e.Hits++;
else if (blow == KillBlow.Spell) e.SpellsLanded++;
Version++;
return e.Name;
}
private string? LongestNameIn(string notice)
{
string? best = null;
foreach (string n in _byName.Keys)
if ((best == null || n.Length > best.Length) && notice.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0)
best = n;
return best;
}
/// <summary>Starts every monster over.</summary>
public void Reset()
{
_byName.Clear();
Version++;
}
// ── Reading ──────────────────────────────────────────────────────────
/// <summary>Every monster's numbers now, most recently fought first.</summary>
public MonsterStatsRow[] Snapshot()
{
var rows = new MonsterStatsRow[_byName.Count];
int i = 0;
foreach (Entry e in _byName.Values) rows[i++] = e.ToRow();
Array.Sort(rows, (a, b) =>
{
int c = b.LastUtcTicks.CompareTo(a.LastUtcTicks);
return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
});
return rows;
}
/// <summary>One monster's numbers by its exact name (any case), or null.</summary>
public MonsterStatsRow? Get(string? name)
=> !string.IsNullOrEmpty(name) && _byName.TryGetValue(name, out Entry? e) ? e.ToRow() : null;
/// <summary>
/// The monster <paramref name="query"/> means: its exact name (any case), else the one name that
/// contains it. Null with the candidates (up to <paramref name="maxCandidates"/>, recent first)
/// when several do, and with none when nothing does.
/// </summary>
public MonsterStatsRow? Find(string? query, out List<string> candidates, int maxCandidates = 8)
{
candidates = new List<string>();
if (string.IsNullOrWhiteSpace(query)) return null;
string q = query.Trim();
if (_byName.TryGetValue(q, out Entry? exact)) return exact.ToRow();
MonsterStatsRow? only = null;
int matches = 0;
foreach (MonsterStatsRow r in Snapshot())
{
if (r.Name.IndexOf(q, StringComparison.OrdinalIgnoreCase) < 0) continue;
matches++;
only = r;
if (candidates.Count < maxCandidates) candidates.Add(r.Name);
}
if (matches == 1) { candidates.Clear(); return only; }
return null;
}
// ── Saving (MonsterStatsStore) ───────────────────────────────────────
/// <summary>Puts saved rows back in place of what there is (a hot reload's carried session).</summary>
public void Load(IEnumerable<MonsterStatsRow> rows)
{
_byName.Clear();
foreach (MonsterStatsRow r in rows)
{
if (string.IsNullOrWhiteSpace(r.Name) || _byName.ContainsKey(r.Name)) continue;
_byName[r.Name] = new Entry
{
Name = r.Name,
Hits = Math.Max(0, r.Hits), Evaded = Math.Max(0, r.Evaded),
SpellsLanded = Math.Max(0, r.SpellsLanded), Resisted = Math.Max(0, r.Resisted), NoEffect = Math.Max(0, r.NoEffect),
Kills = Math.Max(0, r.Kills), DamageDealt = Math.Max(0, r.DamageDealt),
HitsTaken = Math.Max(0, r.HitsTaken), YouEvaded = Math.Max(0, r.YouEvaded),
SpellsTaken = Math.Max(0, r.SpellsTaken), YouResisted = Math.Max(0, r.YouResisted), NoEffectOnYou = Math.Max(0, r.NoEffectOnYou),
DamageTaken = Math.Max(0, r.DamageTaken),
FirstUtcTicks = r.FirstUtcTicks, LastUtcTicks = r.LastUtcTicks,
};
if (_byName.Count >= MaxMonsters) break;
}
Version++;
}
// ── Internals ────────────────────────────────────────────────────────
/// <summary>The monster's entry (made on first sight), its last-seen time now; null for no name.</summary>
private Entry? Touch(string? name, DateTime nowUtc)
{
if (string.IsNullOrWhiteSpace(name)) return null;
string n = name.Trim();
if (n.Length > 64) n = n.Substring(0, 64);
long now = nowUtc.Ticks;
if (!_byName.TryGetValue(n, out Entry? e))
{
if (_byName.Count >= MaxMonsters) DropOldest();
e = new Entry { Name = n, FirstUtcTicks = now };
_byName[n] = e;
}
e.LastUtcTicks = now;
return e;
}
private void DropOldest()
{
string? oldest = null;
long at = long.MaxValue;
foreach (Entry e in _byName.Values)
if (e.LastUtcTicks < at) { at = e.LastUtcTicks; oldest = e.Name; }
if (oldest != null) _byName.Remove(oldest);
}
}

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterStatsStore.cs
// Keeps the monster stats (since login, or their last reset) across a plugin
// reload (engine hot reload, RynthSuite update), by TrackerSessionStore's rules:
// a small file saved every ~30 s, at a reset and on Shutdown, picked up by the
// next copy only for the same client process (id and start time), the same
// character and a recent save. A real logout deletes the file, so the next
// login starts fresh. The Mini Remote session's Reset XP doesn't touch it.
//
// %LOCALAPPDATA%\RynthCore\monster-stats\monsters-<pid>-<character>.txt, plain
// "key=value" lines with one "m=" line per monster (tab-separated), and an end
// marker so a torn write never loads. No System.Text.Json (plugin types and
// STJ leak across reloads). Pure apart from the file calls.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>What a save holds. Times are UTC ticks.</summary>
internal sealed class MonsterStatsSave
{
public int ProcessId;
public long ProcessStartUtcTicks;
public uint CharacterId;
public long SavedUtcTicks;
/// <summary>When these numbers started (the login, or their last reset).</summary>
public long SinceUtcTicks;
public List<MonsterStatsRow> Rows = new();
}
internal static class MonsterStatsStore
{
public const string Header = "RynthAi monster stats v2";
/// <summary>A save older than this is from a client gone (the session store's rule).</summary>
public static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(10);
/// <summary>Files untouched for this long are left over from closed clients.</summary>
public static readonly TimeSpan PurgeAge = TimeSpan.FromDays(1);
private const string FilePrefix = "monsters-";
private const string FileSuffix = ".txt";
private const int Fields = 16; // the name and 15 numbers
private static readonly CultureInfo Ic = CultureInfo.InvariantCulture;
/// <summary>One file per client process and character.</summary>
public static string FileName(int processId, uint characterId)
=> FilePrefix + processId.ToString(Ic) + "-" + characterId.ToString("X8", Ic) + FileSuffix;
/// <summary>%LOCALAPPDATA%\RynthCore\monster-stats.</summary>
public static string DefaultDirectory() => RynthCore.Plugin.Shared.TrackerSessionStore.DirectoryFor("monster-stats");
// ── Format ───────────────────────────────────────────────────────────
public static string Serialize(MonsterStatsSave s)
{
var sb = new StringBuilder(256 + s.Rows.Count * 96);
sb.Append(Header).Append('\n');
Line(sb, "pid", s.ProcessId.ToString(Ic));
Line(sb, "pstart", s.ProcessStartUtcTicks.ToString(Ic));
Line(sb, "char", s.CharacterId.ToString(Ic));
Line(sb, "saved", s.SavedUtcTicks.ToString(Ic));
Line(sb, "since", s.SinceUtcTicks.ToString(Ic));
foreach (MonsterStatsRow r in s.Rows)
{
sb.Append("m=").Append(Clean(r.Name));
foreach (long v in new long[]
{
r.Hits, r.Evaded, r.SpellsLanded, r.Resisted, r.NoEffect, r.Kills, r.DamageDealt,
r.HitsTaken, r.YouEvaded, r.SpellsTaken, r.YouResisted, r.NoEffectOnYou, r.DamageTaken,
r.FirstUtcTicks, r.LastUtcTicks,
})
sb.Append('\t').Append(v.ToString(Ic));
sb.Append('\n');
}
Line(sb, "end", "1"); // a torn write never parses
return sb.ToString();
}
/// <summary>Strict: wrong header, a missing or malformed field, or no end marker = nothing (start fresh).
/// Unknown keys are ignored so a later version can add some.</summary>
public static bool TryParse(string? text, out MonsterStatsSave save)
{
save = new MonsterStatsSave();
if (string.IsNullOrEmpty(text)) return false;
string[] lines = text.Replace("\r", "").Split('\n');
if (lines.Length == 0 || lines[0] != Header) return false;
var map = new Dictionary<string, string>(StringComparer.Ordinal);
var rows = new List<MonsterStatsRow>();
bool end = false;
for (int i = 1; i < lines.Length; i++)
{
string line = lines[i];
if (line.Length == 0) continue;
int eq = line.IndexOf('=');
if (eq <= 0) return false;
string key = line.Substring(0, eq), value = line.Substring(eq + 1);
if (key == "m")
{
if (!TryParseRow(value, out MonsterStatsRow? row)) return false;
rows.Add(row!);
continue;
}
if (key == "end") { end = value == "1"; continue; }
map[key] = value;
}
if (!end) return false;
var s = save;
bool ok = Int(map, "pid", out s.ProcessId)
&& Long(map, "pstart", out s.ProcessStartUtcTicks)
&& UInt(map, "char", out s.CharacterId)
&& Long(map, "saved", out s.SavedUtcTicks)
&& Long(map, "since", out s.SinceUtcTicks);
if (!ok || !ValidTicks(s.SavedUtcTicks) || !ValidTicks(s.SinceUtcTicks)) return false;
s.Rows = rows;
return true;
}
private static bool TryParseRow(string value, out MonsterStatsRow? row)
{
row = null;
string[] f = value.Split('\t');
if (f.Length < Fields || f[0].Trim().Length == 0) return false;
var n = new long[Fields - 1];
for (int i = 1; i < Fields; i++)
if (!long.TryParse(f[i], NumberStyles.None, Ic, out n[i - 1])) return false;
for (int i = 0; i < 13; i++)
if (i != 6 && i != 12 && n[i] > int.MaxValue) return false; // counts are ints; damage is long
if (!ValidTicks(n[13]) || !ValidTicks(n[14])) return false;
row = new MonsterStatsRow(f[0].Trim(),
(int)n[0], (int)n[1], (int)n[2], (int)n[3], (int)n[4], (int)n[5], n[6],
(int)n[7], (int)n[8], (int)n[9], (int)n[10], (int)n[11], n[12],
n[13], n[14]);
return true;
}
/// <summary>
/// Carry the saved stats on only for the same client process (id and start time) and character,
/// and a recent save (a real logout deleted it, so a save that is there is a reload's). A save
/// "from the future" (clock moved back) is treated like a stale one; a minute of slack covers
/// small clock adjustments.
/// </summary>
public static bool ShouldRestore(MonsterStatsSave s, int processId, long processStartUtcTicks, uint characterId, DateTime nowUtc)
{
if (characterId == 0) return false;
if (s.ProcessId != processId || s.ProcessStartUtcTicks != processStartUtcTicks) return false;
if (s.CharacterId != characterId) return false;
if (s.SinceUtcTicks > s.SavedUtcTicks) return false;
TimeSpan age = nowUtc - new DateTime(s.SavedUtcTicks, DateTimeKind.Utc);
return age <= MaxAge && age >= TimeSpan.FromMinutes(-1);
}
// ── Files ────────────────────────────────────────────────────────────
/// <summary>Writes to a temp file and swaps it in, so a crash mid-write leaves the last good save.</summary>
public static void Save(string directory, MonsterStatsSave s)
{
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, FileName(s.ProcessId, s.CharacterId));
string tmp = path + ".tmp";
File.WriteAllText(tmp, Serialize(s));
File.Move(tmp, path, overwrite: true);
}
public static bool TryLoad(string directory, int processId, uint characterId, out MonsterStatsSave save)
{
save = new MonsterStatsSave();
string path = Path.Combine(directory, FileName(processId, characterId));
if (!File.Exists(path)) return false;
return TryParse(File.ReadAllText(path), out save);
}
public static void Delete(string directory, int processId, uint characterId)
{
string path = Path.Combine(directory, FileName(processId, characterId));
if (File.Exists(path)) File.Delete(path);
}
/// <summary>Deletes this process's saves for any character and files left untouched past
/// <see cref="PurgeAge"/> by clients that have closed. Returns how many went.</summary>
public static int Cleanup(string directory, int processId, DateTime nowUtc)
{
if (!Directory.Exists(directory)) return 0;
string mine = FilePrefix + processId.ToString(Ic) + "-";
int removed = 0;
foreach (string path in Directory.GetFiles(directory, FilePrefix + "*"))
{
string name = Path.GetFileName(path);
bool remove = name.StartsWith(mine, StringComparison.Ordinal) || nowUtc - File.GetLastWriteTimeUtc(path) > PurgeAge;
if (!remove) continue;
try { File.Delete(path); removed++; }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return removed;
}
// The client's start time, so a new client that gets a closed one's process id never picks up
// its save. 0 if Windows won't say (both sides then match on the id alone).
private static long? _processStartTicks;
public static long ProcessStartTicks
{
get
{
if (_processStartTicks is long t) return t;
try
{
using var p = System.Diagnostics.Process.GetCurrentProcess();
t = p.StartTime.ToUniversalTime().Ticks;
}
catch { t = 0; }
_processStartTicks = t;
return t;
}
}
// ── Helpers ──────────────────────────────────────────────────────────
private static void Line(StringBuilder sb, string key, string value) => sb.Append(key).Append('=').Append(value).Append('\n');
/// <summary>A name with no tab or line break in it (AC names have none; be safe).</summary>
private static string Clean(string name) => name.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ').Trim();
private static bool ValidTicks(long t) => t >= DateTime.MinValue.Ticks && t <= DateTime.MaxValue.Ticks;
private static bool Long(Dictionary<string, string> m, string k, out long v)
{
v = 0;
return m.TryGetValue(k, out string? s) && long.TryParse(s, NumberStyles.AllowLeadingSign, Ic, out v);
}
private static bool Int(Dictionary<string, string> m, string k, out int v)
{
v = 0;
return m.TryGetValue(k, out string? s) && int.TryParse(s, NumberStyles.AllowLeadingSign, Ic, out v);
}
private static bool UInt(Dictionary<string, string> m, string k, out uint v)
{
v = 0;
return m.TryGetValue(k, out string? s) && uint.TryParse(s, NumberStyles.None, Ic, out v);
}
}

View file

@ -0,0 +1,372 @@
// ============================================================================
// RynthAi - MonsterStats/MonsterStatsWindow.cs
// The Monster Stats window, the FALLBACK for an engine whose Damage panel
// doesn't show the numbers under each monster (no GetUiHookFlags bit 8, e.g.
// plugin API 90): one line per kind of monster fought since login (kills, how
// often it evades and resists you, how often you evade and resist it), and
// under each monster, when clicked open, its numbers both ways. RynthCore hosts
// the window (the sections manifest's "monsterstats" window, plugin API v89:
// header, pop-out, resize, remembered place) and calls Draw through
// RynthPluginRenderEmbed. On an engine with the Damage panel's line it isn't
// declared at all.
//
// AC's render thread: it reads the view the tick published and queues what it
// does (Reset) for the tick. Looks: Shared/RynthUi (the player's theme).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthAi.MonsterStats;
/// <summary>What the window shows (immutable; the tick publishes a new one when something changed).</summary>
internal sealed record MonsterStatsView(MonsterStatsRow[] Rows, string FocusName, bool PhysicalCounted, bool InWorld)
{
public static readonly MonsterStatsView Empty = new(Array.Empty<MonsterStatsRow>(), string.Empty, true, false);
}
internal sealed class MonsterStatsWindow
{
private readonly Action _reset;
private readonly HashSet<string> _open = new(StringComparer.OrdinalIgnoreCase);
private string _filterEdit = string.Empty; // the box
private string _filter = string.Empty; // what it filters by (trimmed)
private int _sort; // 0 recent, 1 name, 2 kills
private static readonly string[] SortNames = { "Recent", "Name", "Kills" };
// The shown rows, built again only when the view, the sort or the filter changes.
private MonsterStatsView? _builtFor;
private int _builtSort = -1;
private string _builtFilter = string.Empty;
private readonly List<MonsterStatsRow> _shown = new();
private float _k = 1f;
private float Px(float v) => v * _k;
private const string HelpText =
"Your fights since login, one line per kind of monster (every Drudge Skulker together).\n\n" +
"It evades: of your melee and missile attacks, the share it evaded.\n" +
"It resists: of your spells that reached it, the share it resisted.\n" +
"You evade: of its melee and missile attacks, the share you evaded.\n" +
"You resist: of its spells that reached you, the share you resisted.\n\n" +
"Click a monster for its numbers both ways: attacks and hits, spells and how many landed, " +
"spells that could do nothing to it (immune), damage and kills. The killing blow counts as a hit " +
"(melee or missile) or a landed spell (magic).\n\n" +
"Melee and missile come from the server's combat events; spells from its spell lines in chat. " +
"A ring spell counts once for each monster it reaches.\n\n" +
"The numbers start over with Reset here, /ra mstats reset, the Damage panel's Reset stats, and at " +
"logout; Reset XP leaves them, and a hot reload keeps them.\n\n" +
"/ra mstats <name> prints a monster's numbers in chat; /ra mstats show opens this window.";
public MonsterStatsWindow(Action reset) => _reset = reset;
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
public Vector2 Draw(MonsterStatsView view)
{
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
Vector2 origin = ImGui.GetCursorScreenPos();
Vector2 size = ImGui.GetContentRegionAvail();
var want = new Vector2(Px(560), Px(360));
if (size.X < 60 || size.Y < 40) return want;
ImDrawListPtr frame = ImGui.GetWindowDrawList();
frame.AddRectFilled(origin, origin + size, Background, 4);
using (PushFont(RynthUiFont.Ui11))
{
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
ImGui.Indent(6);
float w = size.X - 12;
DrawTop(view, w);
DrawFilter(w);
Build(view);
DrawHeader(w);
// 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(10));
ImGui.PushStyleColor(ImGuiCol.ChildBg, Field);
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGui.BeginChild("##ms_rows", new Vector2(w, bodyH));
DrawRows(view);
ImGui.EndChild();
ImGui.PopStyleVar();
ImGui.PopStyleColor();
ImGui.Unindent(6);
ImGui.PopStyleVar();
DrawResetPopup();
}
frame.AddRect(origin, origin + size, Border, 4);
return want;
}
// ── Top line: status, sort, reset, help ─────────────────────────────
private void DrawTop(MonsterStatsView view, float w)
{
Vector2 start = ImGui.GetCursorScreenPos();
float h = Px(20), iconW = Px(22);
string sortLabel = "Sort: " + SortNames[_sort];
float sortW = ButtonWidth(sortLabel), resetW = ButtonWidth("Reset");
float textW = Math.Max(10, w - sortW - resetW - iconW - Px(12));
ImDrawListPtr dl = ImGui.GetWindowDrawList();
string status = !view.InWorld ? "Monster stats start once you are in the world."
: view.Rows.Length == 0 ? "No fights yet since login."
: view.Rows.Length == 1 ? "1 kind of monster since login." : $"{view.Rows.Length} kinds of monster since login.";
dl.PushClipRect(start, start + new Vector2(textW, h), true);
dl.AddText(new Vector2(start.X, start.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, status);
dl.PopClipRect();
float x = start.X + w - iconW - resetW - sortW - Px(8);
if (Button("##ms_sort", sortLabel, new Vector2(x, start.Y), new Vector2(sortW, h), Text, ButtonFill))
_sort = (_sort + 1) % SortNames.Length;
ImGui.SetItemTooltip("Most recently fought first, by name, or by kills.");
x += sortW + Px(4);
if (Button("##ms_reset", "Reset", new Vector2(x, start.Y), new Vector2(resetW, h), Text, ButtonFill, enabled: view.Rows.Length > 0))
ImGui.OpenPopup("##ms_reset_confirm");
ImGui.SetItemTooltip("Start every monster's numbers over (the session's XP and kills and the learned damage stay).");
x += resetW + Px(4);
IconButton("##ms_help", RynthIcons.Info, new Vector2(x, start.Y), new Vector2(iconW, h), Mute, ButtonFill, font: RynthUiFont.Ui11);
if (ImGui.IsItemHovered())
{
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32);
ImGui.TextUnformatted(HelpText);
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
ImGui.SetCursorScreenPos(new Vector2(start.X, start.Y + h + Px(4)));
if (!view.PhysicalCounted)
{
ImGui.PushTextWrapPos(start.X + w);
Label("RynthCore's server messages are off, so melee and missile attacks aren't counted (spells are). /rc net on turns them on; then reload RynthAi.", Highlight);
ImGui.PopTextWrapPos();
}
ImGui.Dummy(Vector2.Zero);
}
private void DrawFilter(float w)
{
ImGui.SetNextItemWidth(w);
ImGui.PushStyleColor(ImGuiCol.FrameBg, Field);
if (ImGui.InputTextWithHint("##ms_filter", "Find a monster", ref _filterEdit, 64u))
_filter = _filterEdit.Trim();
ImGui.PopStyleColor();
}
// ── Columns ─────────────────────────────────────────────────────────
private static readonly (string Head, string Tip)[] Columns =
{
("Kills", "Your kills since login."),
("It evades", "Of your melee and missile attacks, the share it evaded (hover a number for the counts)."),
("It resists", "Of your spells that reached it, the share it resisted."),
("You evade", "Of its melee and missile attacks, the share you evaded."),
("You resist", "Of its spells that reached you, the share you resisted."),
};
private float ColW => Px(66);
private float CaretW => Px(16);
/// <summary>Left edge of number column <paramref name="i"/> (0 = Kills), from the row's left edge.</summary>
private float ColX(float rowW, int i) => rowW - (Columns.Length - i) * ColW;
private void DrawHeader(float w)
{
Vector2 p = ImGui.GetCursorScreenPos();
float h = Px(18);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
dl.AddText(new Vector2(p.X + CaretW, p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, "Monster");
for (int i = 0; i < Columns.Length; i++)
{
var at = new Vector2(p.X + ColX(w, i), p.Y);
ImGui.SetCursorScreenPos(at);
ImGui.InvisibleButton("##ms_col" + i.ToString(CultureInfo.InvariantCulture), new Vector2(ColW, h));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Columns[i].Tip);
float tw = ImGui.CalcTextSize(Columns[i].Head).X;
dl.AddText(new Vector2(at.X + ColW - tw - Px(6), at.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, Columns[i].Head);
}
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(2)));
ImGui.Dummy(Vector2.Zero);
}
// ── Rows ────────────────────────────────────────────────────────────
private void Build(MonsterStatsView view)
{
if (ReferenceEquals(view, _builtFor) && _sort == _builtSort && _filter == _builtFilter) return;
_builtFor = view;
_builtSort = _sort;
_builtFilter = _filter;
_shown.Clear();
foreach (MonsterStatsRow r in view.Rows)
if (_filter.Length == 0 || r.Name.IndexOf(_filter, StringComparison.OrdinalIgnoreCase) >= 0)
_shown.Add(r);
if (_sort == 1) _shown.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
else if (_sort == 2) _shown.Sort((a, b) => b.Kills != a.Kills ? b.Kills.CompareTo(a.Kills) : b.LastUtcTicks.CompareTo(a.LastUtcTicks));
// 0: the view's own order, most recently fought first.
}
private void DrawRows(MonsterStatsView view)
{
float w = ImGui.GetContentRegionAvail().X;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
if (_shown.Count == 0)
{
ImGui.SetCursorPos(new Vector2(Px(8), Px(8)));
Label(view.Rows.Length == 0
? "Fight something: each monster you fight gets a line here."
: "No monster's name has \"" + _filter + "\" in it.", Mute);
return;
}
float rowH = Px(22);
float fontH = ImGui.GetFontSize();
for (int i = 0; i < _shown.Count; i++)
{
MonsterStatsRow r = _shown[i];
ImGui.PushID(r.Name);
Vector2 p = ImGui.GetCursorScreenPos();
bool clicked = ImGui.InvisibleButton("##row", new Vector2(Math.Max(1, w), rowH));
bool hot = ImGui.IsItemHovered();
bool open = _open.Contains(r.Name);
if (clicked)
{
if (open) _open.Remove(r.Name); else _open.Add(r.Name);
open = !open;
}
uint fill = hot ? Selected : (i & 1) == 1 ? RowAlt : 0;
if (fill != 0) dl.AddRectFilled(p, p + new Vector2(w, rowH), fill);
float ty = p.Y + (rowH - fontH) * 0.5f;
DrawCentered(dl, Font(RynthUiFont.Ui11), open ? RynthIcons.CaretDown : RynthIcons.CaretRight,
new Vector2(p.X + Px(2), p.Y), new Vector2(CaretW - Px(2), rowH), Mute);
bool focus = view.FocusName.Length > 0 && r.Name.Equals(view.FocusName, StringComparison.OrdinalIgnoreCase);
dl.PushClipRect(new Vector2(p.X + CaretW, p.Y), new Vector2(p.X + ColX(w, 0) - Px(4), p.Y + rowH), true);
dl.AddText(new Vector2(p.X + CaretW, ty), focus ? Accent : Text, r.Name);
dl.PopClipRect();
string[] cells =
{
r.Kills.ToString("N0", CultureInfo.InvariantCulture),
MonsterCombatStats.Percent(r.ItEvadesRate),
MonsterCombatStats.Percent(r.ItResistsRate),
MonsterCombatStats.Percent(r.YouEvadeRate),
MonsterCombatStats.Percent(r.YouResistRate),
};
for (int c = 0; c < cells.Length; c++)
{
float tw = ImGui.CalcTextSize(cells[c]).X;
dl.AddText(new Vector2(p.X + ColX(w, c) + ColW - tw - Px(6), ty), cells[c] == "-" ? Faded(Mute) : Text, cells[c]);
}
if (hot)
{
float mx = ImGui.GetMousePos().X - p.X;
string? tip = mx >= ColX(w, 1) ? CellTip(r, (int)((mx - ColX(w, 0)) / ColW)) : null;
SafeImGui.SetTooltip(tip ?? (open ? "Click to fold " + r.Name + " away." : "Click for " + r.Name + "'s numbers both ways."));
}
if (open) DrawDetail(r, w);
ImGui.PopID();
}
}
/// <summary>The counts behind a rate cell (column 1..4).</summary>
private static string? CellTip(MonsterStatsRow r, int col) => col switch
{
1 => $"It evaded {r.Evaded:N0} of your {r.Swings:N0} melee and missile attacks.",
2 => $"It resisted {r.Resisted:N0} of your {r.SpellsAtIt:N0} spells that reached it.",
3 => $"You evaded {r.YouEvaded:N0} of its {r.Attacks:N0} melee and missile attacks.",
4 => $"You resisted {r.YouResisted:N0} of its {r.SpellsAtYou:N0} spells that reached you.",
_ => null,
};
/// <summary>One monster's numbers both ways, under its line.</summary>
private void DrawDetail(MonsterStatsRow r, float w)
{
ImGui.Indent(CaretW);
ImGui.Dummy(new Vector2(0, Px(2)));
var flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp;
ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(Px(6), Px(2)));
if (ImGui.BeginTable("##detail", 3, flags, new Vector2(Math.Max(Px(200), w - CaretW - Px(8)), 0)))
{
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 0.8f);
ImGui.TableSetupColumn("You at it", ImGuiTableColumnFlags.WidthStretch, 1.2f);
ImGui.TableSetupColumn("It at you", ImGuiTableColumnFlags.WidthStretch, 1.2f);
ImGui.TableHeadersRow();
foreach (var (label, mine, its) in MonsterStatsText.DetailRows(r))
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
Label(label, Mute);
ImGui.TableNextColumn();
ImGui.TextUnformatted(mine);
ImGui.TableNextColumn();
ImGui.TextUnformatted(its);
}
ImGui.EndTable();
}
ImGui.PopStyleVar();
ImGui.Dummy(new Vector2(0, Px(6)));
ImGui.Unindent(CaretW);
}
private void DrawResetPopup()
{
if (!ImGui.BeginPopup("##ms_reset_confirm")) return;
ImGui.TextUnformatted("Start every monster's numbers over?");
Label("The session's XP and kills stay.", Mute);
if (ImGui.Button("Reset")) { _reset(); _open.Clear(); ImGui.CloseCurrentPopup(); }
ImGui.SameLine();
if (ImGui.Button("Cancel")) ImGui.CloseCurrentPopup();
ImGui.EndPopup();
}
}
/// <summary>The words for one monster's numbers: the window's detail rows and /ra mstats's lines. Pure.</summary>
internal static class MonsterStatsText
{
private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>The detail table: a label, your side, its side.</summary>
public static List<(string Label, string Mine, string Its)> DetailRows(MonsterStatsRow r)
{
var rows = new List<(string, string, string)>
{
("Attacks", $"{N(r.Swings)} swings, {N(r.Hits)} hit", $"{N(r.Attacks)} attacks, {N(r.HitsTaken)} hit"),
("Evaded", $"it evaded {N(r.Evaded)} ({MonsterCombatStats.Percent(r.ItEvadesRate)})",
$"you evaded {N(r.YouEvaded)} ({MonsterCombatStats.Percent(r.YouEvadeRate)})"),
("Spells", $"{N(r.SpellsAtIt)} reached it, {N(r.SpellsLanded)} landed", $"{N(r.SpellsAtYou)} reached you, {N(r.SpellsTaken)} landed"),
("Resisted", $"it resisted {N(r.Resisted)} ({MonsterCombatStats.Percent(r.ItResistsRate)})",
$"you resisted {N(r.YouResisted)} ({MonsterCombatStats.Percent(r.YouResistRate)})"),
};
if (r.NoEffect > 0 || r.NoEffectOnYou > 0)
rows.Add(("No effect", $"{N(r.NoEffect)} (it is immune)", $"{N(r.NoEffectOnYou)} (you are immune)"));
rows.Add(("Damage", $"{N(r.DamageDealt)} dealt", $"{N(r.DamageTaken)} taken"));
rows.Add(("Kills", N(r.Kills), string.Empty));
return rows;
}
/// <summary>/ra mstats's answer: a title line, then your side and its side (three chat lines).</summary>
public static string[] ChatLines(MonsterStatsRow r) => new[]
{
$"[RynthAi] {r.Name} since login: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}.",
$"[RynthAi] You at it: {N(r.Swings)} swings, {N(r.Hits)} hit, it evaded {N(r.Evaded)} ({MonsterCombatStats.Percent(r.ItEvadesRate)}); "
+ $"{N(r.SpellsAtIt)} spells reached it, it resisted {N(r.Resisted)} ({MonsterCombatStats.Percent(r.ItResistsRate)})"
+ (r.NoEffect > 0 ? $", {N(r.NoEffect)} no effect" : string.Empty)
+ $"; {N(r.DamageDealt)} damage.",
$"[RynthAi] It at you: {N(r.Attacks)} attacks, {N(r.HitsTaken)} hit, you evaded {N(r.YouEvaded)} ({MonsterCombatStats.Percent(r.YouEvadeRate)}); "
+ $"{N(r.SpellsAtYou)} spells reached you, you resisted {N(r.YouResisted)} ({MonsterCombatStats.Percent(r.YouResistRate)})"
+ (r.NoEffectOnYou > 0 ? $", {N(r.NoEffectOnYou)} no effect" : string.Empty)
+ $"; {N(r.DamageTaken)} damage.",
};
/// <summary>One short line for /ra mstats list.</summary>
public static string ListLine(MonsterStatsRow r) =>
$"[RynthAi] {r.Name}: {N(r.Kills)} {(r.Kills == 1 ? "kill" : "kills")}, it evades {MonsterCombatStats.Percent(r.ItEvadesRate)}, "
+ $"resists {MonsterCombatStats.Percent(r.ItResistsRate)}; you evade {MonsterCombatStats.Percent(r.YouEvadeRate)}, "
+ $"resist {MonsterCombatStats.Percent(r.YouResistRate)}";
}

View file

@ -161,6 +161,12 @@ public static unsafe class PluginExports
int drawn = plugin.RenderDashboard(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.SequenceEqual("window:monsterstats"u8))
{
// The Monster Stats window (RynthAiPlugin.MonsterStats.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderMonsterStats(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.StartsWith("section:"u8))
{
// Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours.
@ -243,17 +249,21 @@ public static unsafe class PluginExports
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
// API v78 server messages: only what RynthAiPlugin asked for (SetServerMessageInterest in
// Initialize: the transient-text game event, for "The door is locked!"). `data` lives only
// during the call; the text is copied out by the parser.
// Initialize: the transient-text game event, for "The door is locked!", and the four combat
// events, for the Monster Stats). `data` lives only during the call; the parsers copy out what
// they keep (the text, the monster's name).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnServerMessage(uint opcode, byte* data, int length)
{
try
{
var msg = RynthCore.PluginSdk.Net.ServerMessage.FromCallback(opcode, data, length);
if (msg.IsGameEvent && msg.EventType == RynthCore.PluginSdk.Net.GameEventType.TransientString
if (!msg.IsGameEvent) return;
if (msg.EventType == RynthCore.PluginSdk.Net.GameEventType.TransientString
&& RynthCore.PluginSdk.Net.SystemText.TryParse(msg.EventBody, true, out var text))
Runtime.Plugin?.NoteDoorServerText(text.Text);
else if (MonsterStats.CombatEvents.IsCombatEvent(msg.EventType))
Runtime.Plugin?.NoteCombatEvent(msg.EventType, msg.EventBody);
}
catch { }
}

View file

@ -127,6 +127,7 @@ public sealed partial class RynthAiPlugin
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");
ChatLine("[RynthAi] /ra mstats [monster] — its evades, resists, hits, spells and kills this session (list | reset | show | hide)");
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
ChatLine("[RynthAi] /ra pause [sec] — stop the macro, auto-resume after sec (default 60)");

View file

@ -24,6 +24,22 @@ public sealed partial class RynthAiPlugin
return combat != null && (combat.HasEngageableTarget || combat.IsUnderCloseAttack);
}
/// <summary>
/// Idle for Rebuff When Idle's early top-off (BuffManager.IdleForTopOff): the macro on, no fight
/// (the target combat is locked on, a monster within Monster Range or on top of us; read with
/// Enable Combat off too, so a fight by hand counts), no corpse to loot (the arbiter's looting
/// input, last tick) and no salvage. Navigating counts as idle: buffing pauses the route as always.
/// </summary>
internal bool IdleForBuffTopOff()
{
var s = _dashboard?.Settings;
if (s == null || !s.IsMacroRunning) return false;
var combat = _combatManager;
if (combat == null || combat.HasEngageableTarget || combat.IsUnderCloseAttack) return false;
if (_lastWantLoot || _openedContainerId != 0 || _targetCorpseId != 0) return false;
return _salvageManager?.IsBusy != true;
}
/// <summary>
/// AutoCram / AutoStack, one tick: not while a corpse is open or claimed, and not in a fight (a
/// pack move went out between melee swings). The manager itself waits for the busy count.

View file

@ -133,6 +133,7 @@ public sealed partial class RynthAiPlugin
() => _combatManager?.activeTargetId ?? 0)
{
SessionStats = _sessionStats,
ToggleMonsterStats = MonsterStatsWindowWanted ? ToggleMonsterStatsWindow : null,
};
if (_translateUi != null) _huds.Translate = _translateUi;
@ -192,6 +193,8 @@ public sealed partial class RynthAiPlugin
catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); }
try { _sessionStats?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats tick"); }
try { TickMonsterStats(); } // after the session's tick: follows its start (RynthAiPlugin.MonsterStats.cs)
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats tick"); }
try { _serverHub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); }
try { _miniRemote?.Tick(); }
@ -481,7 +484,7 @@ public sealed partial class RynthAiPlugin
{
if (!_initialized || !_loginComplete) return null;
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
dashboard: DashboardWindowWanted);
dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot; // AcObjectClass
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
@ -26,6 +27,14 @@ public sealed partial class RynthAiPlugin
internal const string TaperKey = "tapers";
// The scarab kinds a spell can use (Diamond is left out of the check). Only for an item whose
// class isn't known yet: one known to be something else never counts.
private static readonly HashSet<string> ScarabKinds = new(StringComparer.OrdinalIgnoreCase)
{
"Lead Scarab", "Iron Scarab", "Copper Scarab", "Silver Scarab", "Gold Scarab",
"Pyreal Scarab", "Platinum Scarab", "Mana Scarab",
};
/// <summary>Every tick with the safety checks; does the work every LowCompsCheckMs.</summary>
private void CheckLowComponents(LegacyUiSettings s)
{
@ -50,16 +59,25 @@ public sealed partial class RynthAiPlugin
Log("[RynthAi] " + line);
}
/// <summary>Tapers (every kind together, under <see cref="TaperKey"/>) and each scarab kind but Diamond, by stack size.</summary>
/// <summary>
/// Tapers (every kind together, under <see cref="TaperKey"/>) and each scarab kind but Diamond, by stack size.
/// Spell components only: an item of another class never counts, whatever its name (the "Mechanical
/// Scarab" jewelry stopped the macro as "Mechanical Scarab 0" once it had left the pack, 2026-10-30).
/// An item whose class isn't known yet counts only under a real component's name.
/// </summary>
internal static Dictionary<string, int> CountComponents(IEnumerable<WorldObject> inventory)
{
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var wo in inventory)
{
string name = wo?.Name ?? "";
if (wo == null) continue;
bool component = wo.ObjectClass == AcObjectClass.SpellComponent;
if (!component && wo.ObjectClass != AcObjectClass.Unknown) continue;
string name = wo.Name ?? "";
string? key = name.EndsWith(" Taper", StringComparison.OrdinalIgnoreCase) ? TaperKey
: name.EndsWith(" Scarab", StringComparison.OrdinalIgnoreCase)
&& !name.StartsWith("Diamond", StringComparison.OrdinalIgnoreCase) ? name
&& !name.StartsWith("Diamond", StringComparison.OrdinalIgnoreCase)
&& (component || ScarabKinds.Contains(name)) ? name
: null;
if (key == null) continue;
int n = Math.Max(1, wo!.Values(LongValueKey.StackCount, 1));

View file

@ -0,0 +1,546 @@
// RynthAiPlugin.MonsterStats.cs — combat per kind of monster since login (MonsterStats/), shown
// under each monster in the Damage panel's Monsters tab, and /ra mstats (2026-10-30, a player's
// request: "combat statistics under individual monsters, evades/resists for both the player and
// the monster").
//
// Where it shows: the Damage panel (the dashboard's Monsters key) draws RynthAi's rows
// (BuildMonsterDamageJson); each monster row carries its numbers as "mstats", and an engine that
// draws them (RynthCore feature/monster-stats-tab: UI/Data/DamageRowStats.cs, GetUiHookFlags bit 8)
// puts a line under the monster. On an older engine (the owner's PC, plugin API 90) the field is
// ignored, so RynthAi's own Monster Stats window (a plugin window, API v89) is the fallback, with
// the Session Stats view's "Monster stats" button; on an engine with the tab neither is offered.
//
// Sources (MonsterStats/): melee and missile from the server's typed combat events (API v78
// server messages: 0x01B1..0x01B4, asked for in Initialize); spells from the server's spell lines
// in chat (CombatLines, one table); kills from the kill notice. Not a player's chat types, never a
// player's or a pet's name, and an enchantment line only for a creature (items cast the same line).
//
// Lifetime: from login to logout (per character), kept across a hot reload (MonsterStatsStore),
// started over only by /ra mstats reset, the window's Reset or the Damage panel's Reset stats; not
// by Reset XP (the owner's rule, 2026-10-30). Pump thread throughout, except the window (render
// thread, the published view) and the Damage panel's poll (the published rows).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.MonsterStats;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>The window's title (its panel key) and surface (Huds/SectionsManifest.cs).</summary>
internal const string MonsterStatsTitle = "Monster Stats", MonsterStatsSurface = "window:monsterstats";
/// <summary>The engine's Damage panel key (the dashboard's Monsters key opens it).</summary>
internal const string DamagePanelKey = "Monsters";
internal const string MonsterStatsUsage = "Usage: /ra mstats [monster] | list | reset | show | hide";
/// <summary>
/// GetUiHookFlags bit 8 (SDK RynthUiHookFlags.DamageRowStats on RynthCore feature/monster-stats-tab):
/// the engine's Damage panel draws a row's "mstats". Spelled here so RynthAi builds against an
/// SDK without the name.
/// </summary>
internal const uint DamageRowStatsFlag = 1u << 8;
private static readonly TimeSpan MonsterStatsSaveInterval = TimeSpan.FromSeconds(30);
private readonly MonsterCombatStats _monsterStats = new();
private volatile MonsterStatsView _monsterStatsView = MonsterStatsView.Empty; // tick writes, render reads
private int _monsterStatsViewVersion = -1;
private string _monsterStatsViewFocus = string.Empty;
private bool _monsterStatsViewInWorld;
private long _monsterStatsViewAtMs;
private long _monsterStatsDrawnMs = long.MinValue / 2; // render writes, tick reads
// The rows by name for the Damage panel's poll (BuildMonsterDamageJson, its own thread): swapped whole.
private volatile Dictionary<string, MonsterStatsRow> _monsterStatsByName = new(StringComparer.OrdinalIgnoreCase);
private int _monsterStatsByNameVersion = -1;
/// <summary>The counting has begun for this login (the save looked for); false before login and after logout.</summary>
private bool _monsterStatsStarted;
/// <summary>When the numbers started (login, or the last reset), UTC.</summary>
private DateTime _monsterStatsSinceUtc;
/// <summary>The Damage panel's Reset stats asked (its thread); done on the tick.</summary>
private volatile bool _monsterStatsResetWanted;
private int _monsterStatsSavedVersion = -1;
private DateTime _monsterStatsSaveAtUtc;
private bool _monsterStatsSaveFailedLogged;
/// <summary>The engine streams the combat game events (Initialize); false = melee and missile go uncounted.</summary>
private bool _combatEventsStreaming = true;
private MonsterStatsWindow? _monsterStatsWindow; // render thread
private int _monsterStatsFailures; // render thread
// Creature names around, by class (refreshed at most every 2 s): who a line's name is.
private readonly Dictionary<string, AcObjectClass> _creatureClassByName = new(StringComparer.OrdinalIgnoreCase);
private long _creatureNamesAtMs = long.MinValue / 2;
/// <summary>Where the save goes (tests point it at a temp folder).</summary>
internal string MonsterStatsDirectory { get; set; } = MonsterStatsStore.DefaultDirectory();
/// <summary>The counters (tests, and RynthAi's own readers).</summary>
internal MonsterCombatStats MonsterStatsForTests => _monsterStats;
/// <summary>The engine's Damage panel shows the numbers under each monster (GetUiHookFlags bit 8). Any thread.</summary>
internal bool EngineDrawsMonsterStats => Host.HasUiHooks && ((uint)Host.GetUiHookFlags() & DamageRowStatsFlag) != 0;
// ── Events (pump thread) ─────────────────────────────────────────────
/// <summary>One of the four combat game events (PluginExports.OnServerMessage).</summary>
internal void NoteCombatEvent(uint eventType, ReadOnlySpan<byte> body)
{
if (!_loginComplete) return;
if (!CombatEvents.TryParse(eventType, body, out PhysicalEvent kind, out string name, out int damage)) return;
if (!CountsAsMonster(name, mayBeItem: false)) return;
_monsterStats.OnPhysical(kind, name, damage, DateTime.UtcNow);
}
/// <summary>A chat line: one of the spell lines (CombatLines) about a monster, unless a player wrote it.</summary>
private void NoteMonsterStatsChat(string text, int chatType)
{
if (!_loginComplete || RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return;
if (!CombatLines.TryParse(text, out CombatLine line)) return;
if (!CountsAsMonster(line.Name, line.MayBeItem)) return;
_monsterStats.OnSpell(line, DateTime.UtcNow);
}
/// <summary>The kill notice: a kill, and the killing blow by the combat mode it was struck in.</summary>
private void NoteMonsterStatsKill(string? notice)
{
if (!_loginComplete) return;
KillBlow blow = _currentCombatMode switch
{
CombatMode.Melee or CombatMode.Missile => KillBlow.Physical,
CombatMode.Magic => KillBlow.Spell,
_ => KillBlow.None,
};
_monsterStats.OnKill(notice, blow, DateTime.UtcNow, CreatureNameIn);
}
/// <summary>
/// A name the stats count: not a player's or a pet's (PvP, a summon), nor an NPC's; and for a line
/// an item could have sent (<paramref name="mayBeItem"/>), a creature around or a monster already
/// counted. A name the client doesn't know otherwise counts (a monster out of sight).
/// </summary>
private bool CountsAsMonster(string name, bool mayBeItem)
{
AcObjectClass? cls = CreatureClassOf(name);
if (cls is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) return false;
if (mayBeItem && cls == null && !_monsterStats.IsTracked(name)) return false;
return true;
}
/// <summary>The class of the creature around with that name, or null when none is known.</summary>
private AcObjectClass? CreatureClassOf(string name)
{
RefreshCreatureNames(false);
if (_creatureClassByName.TryGetValue(name, out AcObjectClass cls)) return cls;
// A creature that just came: look once more before calling it unknown (at most every 250 ms).
if (Environment.TickCount64 - _creatureNamesAtMs > 250)
{
RefreshCreatureNames(true);
if (_creatureClassByName.TryGetValue(name, out cls)) return cls;
}
return null;
}
private void RefreshCreatureNames(bool force)
{
long now = Environment.TickCount64;
if (!force && now - _creatureNamesAtMs < 2000) return;
_creatureNamesAtMs = now;
_creatureClassByName.Clear();
var cache = _objectCache;
if (cache == null) return;
foreach (WorldObject wo in cache.GetLandscape())
{
if (wo == null || string.IsNullOrEmpty(wo.Name)) continue;
// The cache can file a player as a monster (a creature whose kind wasn't readable yet):
// a player's guid says player. A player's name wins over a monster's of the same name.
AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass;
if (_creatureClassByName.TryGetValue(wo.Name, out AcObjectClass had) && had == AcObjectClass.Player) continue;
_creatureClassByName[wo.Name] = cls;
}
// Players, NPCs and pets that aren't in the creature list (everything with a place in the
// world): never a monster. Items stay unknown (an enchantment line from one doesn't count).
foreach (WorldObject wo in cache.GetLandscapeObjects())
{
if (wo == null || string.IsNullOrEmpty(wo.Name)) continue;
AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass;
if (cls is AcObjectClass.Player or AcObjectClass.Npc or AcObjectClass.Vendor or AcObjectClass.CombatPet)
_creatureClassByName[wo.Name] = cls;
}
}
/// <summary>The kill notice names a monster with no numbers yet (killed by its first blow): the longest creature name around in it.</summary>
private string? CreatureNameIn(string notice)
{
RefreshCreatureNames(true);
string? best = null;
foreach (var kv in _creatureClassByName)
{
if (kv.Value is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) continue;
if ((best == null || kv.Key.Length > best.Length) && notice.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) >= 0)
best = kv.Key;
}
return best;
}
// ── Tick (pump thread) ───────────────────────────────────────────────
/// <summary>Starts the login's counting (or brings the save back after a reload), resets on asking, saves, publishes.</summary>
private void TickMonsterStats()
{
DateTime now = DateTime.UtcNow;
if (!_monsterStatsStarted && _loginComplete && _playerId != 0)
{
// The login's first tick with the character known: after a hot reload the save is there.
_monsterStatsStarted = true;
if (TryRestoreMonsterStats(now))
Host.Log($"[RynthAi] Monster stats carried over from before the reload ({_monsterStats.Count} kinds of monster).");
else
{
_monsterStatsSinceUtc = now;
CleanupMonsterStatsSaves(now);
}
_monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval;
}
if (_monsterStatsResetWanted)
{
_monsterStatsResetWanted = false;
ResetMonsterStats("the Damage panel's Reset stats");
}
if (_monsterStatsStarted && now >= _monsterStatsSaveAtUtc)
{
_monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval;
if (_monsterStats.Version != _monsterStatsSavedVersion) SaveMonsterStats(now);
}
PublishMonsterStatsRows();
PublishMonsterStatsView(Environment.TickCount64);
}
/// <summary>Every monster's numbers start over (/ra mstats reset, the window's Reset, the Damage panel's Reset stats). Pump thread.</summary>
private int ResetMonsterStats(string by)
{
int n = _monsterStats.Count;
_monsterStats.Reset();
DateTime now = DateTime.UtcNow;
_monsterStatsSinceUtc = now;
// Saved at once, so a reload right after a reset can't bring the old numbers back.
if (_monsterStatsStarted) SaveMonsterStats(now);
Host.Log($"[RynthAi] Monster stats started over ({by}; {n} kinds of monster cleared).");
return n;
}
/// <summary>The Damage panel's Reset stats (RynthPluginClearMonsterStats, its thread): the monster stats start over too.</summary>
internal void RequestMonsterStatsReset() => _monsterStatsResetWanted = true;
/// <summary>The rows by name for the Damage panel's poll, when something changed.</summary>
private void PublishMonsterStatsRows()
{
if (_monsterStats.Version == _monsterStatsByNameVersion) return;
_monsterStatsByNameVersion = _monsterStats.Version;
var byName = new Dictionary<string, MonsterStatsRow>(StringComparer.OrdinalIgnoreCase);
foreach (MonsterStatsRow r in _monsterStats.Snapshot()) byName[r.Name] = r;
_monsterStatsByName = byName;
}
/// <summary>
/// A Damage-panel row's "mstats" field and its comma, for the monster named <paramref name="name"/>
/// (UI/Data/DamageRowStats.cs in the engine reads it); "" for a monster without numbers. Any thread.
/// </summary>
internal string MonsterStatsJsonFor(string name)
{
if (!_monsterStatsByName.TryGetValue(name, out MonsterStatsRow? r) || r.IsEmpty) return string.Empty;
return MonsterStatsJson(r) + ",";
}
/// <summary>"mstats":{...} for one monster (the field names DamageRowStats reads).</summary>
internal static string MonsterStatsJson(MonsterStatsRow r)
{
CultureInfo ic = CultureInfo.InvariantCulture;
var sb = new StringBuilder(160);
sb.Append("\"mstats\":{")
.Append("\"sw\":").Append(r.Swings.ToString(ic)).Append(",\"ev\":").Append(r.Evaded.ToString(ic))
.Append(",\"sp\":").Append(r.SpellsAtIt.ToString(ic)).Append(",\"rs\":").Append(r.Resisted.ToString(ic))
.Append(",\"ne\":").Append(r.NoEffect.ToString(ic))
.Append(",\"at\":").Append(r.Attacks.ToString(ic)).Append(",\"yev\":").Append(r.YouEvaded.ToString(ic))
.Append(",\"ysp\":").Append(r.SpellsAtYou.ToString(ic)).Append(",\"yrs\":").Append(r.YouResisted.ToString(ic))
.Append(",\"yne\":").Append(r.NoEffectOnYou.ToString(ic))
.Append(",\"k\":").Append(r.Kills.ToString(ic))
.Append(",\"dd\":").Append(r.DamageDealt.ToString(ic)).Append(",\"dt\":").Append(r.DamageTaken.ToString(ic))
.Append('}');
return sb.ToString();
}
/// <summary>
/// A new view for the fallback window when something changed (at most 4 a second): while it is on
/// screen, and off screen only for a login or logout, so it never opens on the wrong one.
/// </summary>
private void PublishMonsterStatsView(long nowMs)
{
bool shown = nowMs - Volatile.Read(ref _monsterStatsDrawnMs) <= 2000;
if (!shown && _monsterStatsViewVersion != -1 && _monsterStatsViewInWorld == _loginComplete) return;
if (nowMs - _monsterStatsViewAtMs < 250) return;
string focus = MonsterStatsFocusName();
if (_monsterStats.Version == _monsterStatsViewVersion && focus == _monsterStatsViewFocus
&& _loginComplete == _monsterStatsViewInWorld) return;
_monsterStatsViewAtMs = nowMs;
_monsterStatsViewVersion = _monsterStats.Version;
_monsterStatsViewFocus = focus;
_monsterStatsViewInWorld = _loginComplete;
_monsterStatsView = new MonsterStatsView(_monsterStats.Snapshot(), focus, _combatEventsStreaming, _loginComplete);
}
/// <summary>The monster in focus: the one combat fights, else the selected creature; "" for none.</summary>
private string MonsterStatsFocusName()
{
int id = _combatManager?.activeTargetId ?? 0;
if (id == 0) id = unchecked((int)_currentTargetId);
if (id == 0) return string.Empty;
if (CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)id))) return string.Empty;
WorldObject? wo = _objectCache?[id];
return wo != null && wo.ObjectClass != AcObjectClass.Player ? wo.Name ?? string.Empty : string.Empty;
}
/// <summary>A real logout ends them (they are per character and login), and the save with them.</summary>
private void OnLogoutMonsterStats()
{
if (_monsterStatsStarted) DeleteMonsterStatsSave();
_monsterStats.Reset();
_monsterStatsStarted = false;
_monsterStatsSavedVersion = -1;
_creatureClassByName.Clear();
PublishMonsterStatsRows();
_monsterStatsView = MonsterStatsView.Empty;
_monsterStatsViewVersion = -1;
}
/// <summary>Plugin unload (hot reload, update, client closing): saved while counting, never deleted.</summary>
private void ShutdownMonsterStats()
{
if (_monsterStatsStarted) SaveMonsterStats(DateTime.UtcNow);
}
// ── Saving (MonsterStatsStore) ───────────────────────────────────────
private void SaveMonsterStats(DateTime now)
{
if (_playerId == 0 || !_monsterStatsStarted) return;
try
{
var save = new MonsterStatsSave
{
ProcessId = Environment.ProcessId,
ProcessStartUtcTicks = MonsterStatsStore.ProcessStartTicks,
CharacterId = _playerId,
SavedUtcTicks = now.Ticks,
SinceUtcTicks = _monsterStatsSinceUtc.Ticks,
Rows = new List<MonsterStatsRow>(_monsterStats.Snapshot()),
};
MonsterStatsStore.Save(MonsterStatsDirectory, save);
_monsterStatsSavedVersion = _monsterStats.Version;
_monsterStatsSaveFailedLogged = false;
}
catch (Exception ex)
{
if (_monsterStatsSaveFailedLogged) return; // one line until a save works again
_monsterStatsSaveFailedLogged = true;
Host.Log($"[RynthAi] Couldn't save the monster stats: {ex.GetType().Name}: {ex.Message}");
}
}
private bool TryRestoreMonsterStats(DateTime now)
{
if (_playerId == 0) return false;
try
{
int pid = Environment.ProcessId;
if (!MonsterStatsStore.TryLoad(MonsterStatsDirectory, pid, _playerId, out MonsterStatsSave save)) return false;
if (!MonsterStatsStore.ShouldRestore(save, pid, MonsterStatsStore.ProcessStartTicks, _playerId, now)) return false;
_monsterStats.Load(save.Rows);
_monsterStatsSinceUtc = new DateTime(save.SinceUtcTicks, DateTimeKind.Utc);
_monsterStatsSavedVersion = _monsterStats.Version;
return true;
}
catch (Exception ex)
{
Host.Log($"[RynthAi] Couldn't read the saved monster stats, starting fresh: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private void DeleteMonsterStatsSave()
{
if (_playerId == 0) return;
try { MonsterStatsStore.Delete(MonsterStatsDirectory, Environment.ProcessId, _playerId); }
catch (Exception ex) { Host.Log($"[RynthAi] Couldn't delete the saved monster stats: {ex.GetType().Name}: {ex.Message}"); }
}
private void CleanupMonsterStatsSaves(DateTime now)
{
try { MonsterStatsStore.Cleanup(MonsterStatsDirectory, Environment.ProcessId, now); }
catch { }
}
// ── /ra mstats ───────────────────────────────────────────────────────
/// <summary>
/// "/ra mstats [monster]" prints a monster's numbers (no name: the monster combat fights, else
/// the selected one); "list" the monsters with numbers; "reset" starts them over; "show", "hide",
/// "toggle" the Damage panel (or, on an older engine, the Monster Stats window). Pump thread.
/// </summary>
private void HandleMonsterStatsCommand(string[] parts)
{
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
switch (arg.ToLowerInvariant())
{
case "list":
ListMonsterStats();
return;
case "reset":
case "clear":
{
int n = ResetMonsterStats("/ra mstats reset");
ReplyOk($"[RynthAi] Monster stats started over ({n} {(n == 1 ? "kind" : "kinds")} of monster cleared).");
return;
}
case "show":
case "open":
case "window":
case "hide":
case "close":
case "toggle":
SetMonsterStatsWindow(arg.ToLowerInvariant());
return;
case "help":
case "?":
ChatLine("[RynthAi] /ra mstats [monster] — a monster's evades, resists, hits, spells and kills since login (no name: the one you fight or have selected)");
ChatLine("[RynthAi] /ra mstats list | reset | show | hide — every monster, start over, where they show (the Damage panel's Monsters tab)");
return;
}
MonsterStatsRow? row;
if (arg.Length == 0)
{
string focus = MonsterStatsFocusName();
row = focus.Length > 0 ? _monsterStats.Get(focus) : null;
if (row == null)
{
ReplyFail((focus.Length > 0
? $"[RynthAi] No monster stats for {focus} since login yet."
: "[RynthAi] Select a monster or name one.")
+ KnownMonsters() + " " + MonsterStatsUsage);
return;
}
}
else
{
row = _monsterStats.Find(arg, out List<string> candidates);
if (row == null)
{
ReplyFail(candidates.Count > 1
? $"[RynthAi] '{arg}' matches {candidates.Count} monsters: {string.Join(", ", candidates)}. Name one exactly. {MonsterStatsUsage}"
: $"[RynthAi] No monster stats for '{arg}' since login.{KnownMonsters()} {MonsterStatsUsage}");
return;
}
}
foreach (string line in MonsterStatsText.ChatLines(row)) ChatLine(line);
}
/// <summary>" Monsters with stats: A, B, C." (the most recent few), or " No monster has stats yet."</summary>
private string KnownMonsters()
{
MonsterStatsRow[] rows = _monsterStats.Snapshot();
if (rows.Length == 0) return " No monster has stats yet.";
var names = new List<string>();
for (int i = 0; i < rows.Length && i < 6; i++) names.Add(rows[i].Name);
return " Monsters with stats: " + string.Join(", ", names) + (rows.Length > 6 ? ", ..." : "") + ".";
}
private void ListMonsterStats()
{
MonsterStatsRow[] rows = _monsterStats.Snapshot();
if (rows.Length == 0)
{
ChatLine("[RynthAi] No monster stats yet since login: fight something.");
return;
}
ChatLine($"[RynthAi] Monster stats since login ({rows.Length} {(rows.Length == 1 ? "kind" : "kinds")}, most recent first):");
for (int i = 0; i < rows.Length && i < 10; i++) ChatLine(MonsterStatsText.ListLine(rows[i]));
if (rows.Length > 10) ChatLine($"[RynthAi] ... and {rows.Length - 10} more (/ra mstats show).");
}
/// <summary>"show" / "hide" / "toggle": the Damage panel where it shows them, else the fallback window.</summary>
private void SetMonsterStatsWindow(string verb)
{
if (!Host.HasSetPanelOpen)
{
ReplyFail("[RynthAi] Opening a panel needs RynthCore with plugin windows (plugin API 89+); /ra mstats <monster> prints the numbers.");
return;
}
RynthPanelOpen mode = verb is "hide" or "close" ? RynthPanelOpen.Close : verb == "toggle" ? RynthPanelOpen.Toggle : RynthPanelOpen.Open;
bool tab = EngineDrawsMonsterStats;
string key = tab ? DamagePanelKey : MonsterStatsTitle;
string what = tab ? "Damage panel (Monsters)" : "Monster Stats window";
int open = Host.SetPanelOpen(key, mode);
if (open < 0)
{
ReplyFail(tab
? "[RynthAi] RynthCore has no Damage panel to open."
: "[RynthAi] The Monster Stats window isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment.");
return;
}
ReplyOk(open == 1
? $"[RynthAi] {what} open{(tab ? ": each monster's evades and resists are under its line." : ".")}"
: $"[RynthAi] {what} closed.");
}
/// <summary>The window's Reset (queued from the render thread, run on the tick).</summary>
private void ResetMonsterStatsFromWindow() => ResetMonsterStats("the Monster Stats window");
/// <summary>The Session Stats view's "Monster stats" button (the fallback window only): open or closed. Any thread.</summary>
internal void ToggleMonsterStatsWindow()
{
if (Host.HasSetPanelOpen) Host.SetPanelOpen(MonsterStatsTitle, RynthPanelOpen.Toggle);
}
// ── Fallback window (render thread) ──────────────────────────────────
/// <summary>
/// RynthPluginRenderEmbed "window:monsterstats": the Monster Stats window body, docked or popped
/// out (the engine's current context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
/// </summary>
internal int RenderMonsterStats(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
Volatile.Write(ref _monsterStatsDrawnMs, Environment.TickCount64);
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_monsterStatsWindow ??= new MonsterStatsWindow(() => QueueDashAction(ResetMonsterStatsFromWindow));
want = _monsterStatsWindow.Draw(_monsterStatsView);
_monsterStatsFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderMonsterStats");
return ++_monsterStatsFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
/// <summary>
/// The fallback window goes in the sections manifest on an engine with plugin windows (v89) whose
/// Damage panel doesn't show the numbers (no GetUiHookFlags bit 8: the owner's API-90 core).
/// </summary>
private bool MonsterStatsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen && !EngineDrawsMonsterStats;
}

View file

@ -244,13 +244,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.UseAudit.WorldUseHold = SalvagePanelHold;
// "The door is locked!" comes as a transient string (ACE Door.ActOnUse): the door logic picks a
// lock only when the server says so (DoorInteractionController). The chat line is the fallback.
// The four combat events (hits and evades both ways, by name) feed the Monster Stats
// (RynthAiPlugin.MonsterStats.cs); without the stream melee and missile go uncounted there.
_combatEventsStreaming = false;
try
{
if (Host.HasServerMessages)
{
int sm = Host.SetServerMessageInterest(ReadOnlySpan<uint>.Empty,
new uint[] { RynthCore.PluginSdk.Net.GameEventType.TransientString });
if (sm != 1) Host.Log($"[RynthAi] Server messages: not streaming ({sm}); locked doors are read from chat only.");
var events = new uint[1 + MonsterStats.CombatEvents.GameEvents.Length];
events[0] = RynthCore.PluginSdk.Net.GameEventType.TransientString;
MonsterStats.CombatEvents.GameEvents.CopyTo(events, 1);
int sm = Host.SetServerMessageInterest(ReadOnlySpan<uint>.Empty, events);
_combatEventsStreaming = sm == 1;
if (sm != 1) Host.Log($"[RynthAi] Server messages: not streaming ({sm}); locked doors are read from chat only, and the Monster Stats count no melee or missile attacks.");
}
}
catch (Exception ex) { Host.Log($"[RynthAi] Server messages: {ex.Message}"); }
@ -286,6 +292,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
long t0 = Environment.TickCount64;
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.Shutdown(); } catch { }
try { ShutdownMonsterStats(); } catch { } // kept for the next copy, with the session
try { GameInput.Shutdown(); } catch { } // keys still held for /mt movement | jump | strafe
// Release the Monster Editor process handle (if the toggle button
// launched one) rather than leaking it on plugin unload/hot-reload.
@ -341,6 +348,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Log("RynthAi: logout — tearing down session.");
try { _dashboard?.SaveSettings(); } catch { }
try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); }
try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); }
Loot.T11ItemSupport.Reset();
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
ClearInGameMarker();
@ -757,7 +765,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.JumpBusy = () => _jumper?.IsBusy == true;
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
{
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
_buffManager.IdleForTopOff = IdleForBuffTopOff; // Rebuff When Idle's early top-off (RynthAiPlugin.Chores.cs)
}
_combatManager.SetCharacterSkills(_charSkills);
_combatManager.SetPlayerId(_playerId);
_combatManager.SetDamageStores(_creatureStore, _damageStore);
@ -1104,7 +1115,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["DunPatrolSightYd"] = (DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax),
["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000),
["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20),
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600),
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600), ["RebuffIdleMarginMinutes"] = (0, 60),
["AutoVendorTries"] = (1, 20), ["AutoVendorTriesTime"] = (500, 30000),
["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500),
["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500),
@ -2409,6 +2420,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { NoteServerPolicyChat(text); } catch { } // DreamWeave's Thread lines (ServerPolicy)
try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic)
try { _sessionStats?.OnChatWindowText(text); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats chat"); }
try { NoteMonsterStatsChat(text, chatType); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats chat"); }
// The Meta Manager eats the reply to its own /myquests poll (only that).
bool mmEat = false;
try { mmEat = MetaScheduleChat(text); } catch { }
@ -2441,6 +2453,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Mini Remote stats count every notice, as RynthTracker does (an empty message is still a kill).
try { _sessionStats?.OnKillNotification(deathMessage); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats kill"); }
try { NoteMonsterStatsKill(deathMessage); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats kill"); }
if (string.IsNullOrEmpty(deathMessage)) return;
_killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone
NoteBoostLootKill(); // before combat sees the kill: its next target waits for the corpse
@ -2494,7 +2508,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f;
_sessionStats?.OnUpdateHealth(targetId, currentHealth, maxHealth);
_objectCache?.OnUpdateHealth(targetId, healthRatio);
_combatManager?.NoteServerHealth(unchecked((int)targetId), healthRatio); // kill-shot evidence (fight target only)
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
@ -2786,6 +2799,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(pet))).Append(',')
.Append(WeakJson(wcid, name, wcids));
if (wcids.Length > 1) sb.Append("\"wcids\":[").Append(string.Join(",", wcids)).Append("],");
// Its evades and resists both ways since login (RynthAiPlugin.MonsterStats.cs): the line under
// the monster on an engine that draws it; an older one ignores the field.
sb.Append(MonsterStatsJsonFor(name));
sb.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[");
@ -3222,9 +3238,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return sb.ToString();
}
/// <summary>Master reset from the Damage panel: zero all learned stats, keep names + manual overrides. Persists.</summary>
/// <summary>Master reset from the Damage panel: zero all learned stats, keep names + manual overrides. Persists.
/// The evades and resists under each monster (RynthAiPlugin.MonsterStats.cs) start over too.</summary>
public void ClearMonsterStats()
{
RequestMonsterStatsReset();
if (_damageStore == null) return;
_damageStore.ClearAllStats();
_damageStore.SaveIfDirty();
@ -4009,6 +4027,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "fellowinfo": HandleFellowshipInfoCommand(); break;
case "dumpinv": HandleDumpInventoryCommand(); break;
case "combat": HandleCombatStateCommand(); break;
case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs
case "why": HandleWhyCommand(); break;
case "ghost":
case "ghosts": HandleGhostsCommand(cmd, parts); break;

View file

@ -2,16 +2,27 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses,
Quantity, Split, Give, Buy }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
/// <summary>
/// A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).
/// The quantity box's verbs (qty, split, give, buy): <see cref="Amount"/> (null = the box's number) and
/// <see cref="Text"/> (split: the pack; buy: the item's name).
/// </summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "", QtyAmount? Amount = null);
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear]]";
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear] | "
+ "qty [number|max|half] | split [number] [into <pack>] | give [number] | buy [number] [item name]]";
public const string QtyUsage = "Usage: /rdef qty <number|max|half>, e.g. /rdef qty 25 (the Selection window's number)";
public const string SplitUsage = "Usage: /rdef split [number|max|half] [into <pack>], e.g. /rdef split 25 or /rdef split 25 into Sack";
public const string GiveUsage = "Usage: /rdef give [number|max|half], e.g. /rdef give 10 (to the last player or NPC you selected)";
public const string BuyUsage = "Usage: /rdef buy [number|max|half] [item name], e.g. /rdef buy 25 or /rdef buy 25 Mana Scarab (a vendor open)";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
@ -68,6 +79,31 @@ internal static class DefCommandParser
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotCountMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotCountMax}, e.g. /rdef slots 10");
// The quantity box (2026-10-30, Quantity/QuantityController.cs).
case "qty": case "quantity": case "amount":
{
if (rest.Length == 0) return new DefCommand(DefVerb.Quantity);
return QuantityRules.TryParse(rest, out QtyAmount q, out string why)
? new DefCommand(DefVerb.Quantity, Amount: q)
: Fail(why + " " + QtyUsage);
}
case "split":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + SplitUsage);
string into = StripWord(tail, "into", "in", "to");
return new DefCommand(DefVerb.Split, Text: into, Amount: q);
}
case "give":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + GiveUsage);
if (tail.Length > 0) return Fail($"'{tail}' isn't a quantity. {GiveUsage}");
return new DefCommand(DefVerb.Give, Amount: q);
}
case "buy":
{
if (!QuantityRules.TryParseLeading(rest, out QtyAmount? q, out string tail, out string why)) return Fail(why + " " + BuyUsage);
return new DefCommand(DefVerb.Buy, Text: StripWord(tail, "of"), Amount: q);
}
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
@ -91,4 +127,14 @@ internal static class DefCommandParser
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
/// <summary>The text without a leading word ("into Sack" -> "Sack").</summary>
private static string StripWord(string text, params string[] words)
{
string t = text.Trim();
foreach (string w in words)
if (t.Length > w.Length && t.StartsWith(w, StringComparison.OrdinalIgnoreCase) && char.IsWhiteSpace(t[w.Length]))
return t[(w.Length + 1)..].Trim();
return t;
}
}

View file

@ -111,6 +111,12 @@ internal sealed class DefSettings
/// the picker opens from the settings window, the bar's right-click menu and /rdef weapons.
/// </summary>
public bool WeaponsButtonOnBar;
/// <summary>
/// The quantity box under a stack or a vendor's item in the Selection window (2026-10-30): how many,
/// and Split / Give / Buy that many. On (the default, and what a file from before reads as).
/// /rdef qty, split, give and buy work either way.
/// </summary>
public bool QuantityBox = true;
public bool BarOpen;
public bool PickerOpen;

View file

@ -68,6 +68,7 @@ internal sealed class DefStore
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.WeaponsButtonOnBar = Bool(s, "weaponsButtonOnBar", st.WeaponsButtonOnBar); // missing (a file from before 2026-10-29): off
st.IndependentBar = Bool(s, "independentBar", st.IndependentBar); // missing (a file from before 2026-10-27): off
st.QuantityBox = Bool(s, "quantityBox", st.QuantityBox); // missing (a file from before 2026-10-30): on
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
@ -166,6 +167,7 @@ internal sealed class DefStore
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("weaponsButtonOnBar", s.WeaponsButtonOnBar);
w.WriteBoolean("independentBar", s.IndependentBar);
w.WriteBoolean("quantityBox", s.QuantityBox);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();

View file

@ -0,0 +1,406 @@
// ============================================================================
// RynthDefective - Model/Quantity.cs
// The quantity box's rules (2026-10-30): how many of a stack a split or a
// give takes, how many of a vendor's item a buy asks for, what that costs and
// why it can't go. Pure (no host), so RynthDefective.Tests checks every rule.
//
// Retail AC keeps this number in its toolbar: the stack slider and the number
// beside the selected item's name (the client's split_amount global, which a
// drag and the vendor's buy list read). RynthCore's "Hide retail toolbar"
// hides it with the rest of the toolbar, and the plugin API can't read or set
// it (API 92), so the box keeps a number of its own and acts through the
// engine's calls: SplitStackInternal, GiveObjectTo and VendorBuy.
//
// The counts:
// split takes 1 .. stack-1 (one always stays: the whole stack is a move);
// "max" is stack-1, "half" is half the stack.
// give hands over 1 .. the whole stack; "max" is the whole stack.
// buy asks for exactly the number; "max" is the most the vendor has, you
// 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.
// ============================================================================
using System;
using System.Globalization;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum QtyWord { Number, Max, Half }
/// <summary>A quantity as typed: a number, "max" or "half".</summary>
internal readonly record struct QtyAmount(QtyWord Word, int Number = 0)
{
public static QtyAmount Of(int n) => new(QtyWord.Number, n);
public static readonly QtyAmount Max = new(QtyWord.Max);
public static readonly QtyAmount Half = new(QtyWord.Half);
public override string ToString() => Word switch
{
QtyWord.Max => "max",
QtyWord.Half => "half",
_ => Number.ToString(CultureInfo.InvariantCulture),
};
}
internal static class QuantityRules
{
/// <summary>The most one request carries: the engine's vendor limit (an ItemProfile packs 24 bits).</summary>
public const int MaxAmount = 0x7FFFFF;
public const string Usage = "a number (25, 1,000), max or half";
/// <summary>"25", "1,000", "max" / "all", "half" / "1/2". False with the reason and the usage.</summary>
public static bool TryParse(string? text, out QtyAmount amount, out string why)
{
amount = default;
why = string.Empty;
string t = (text ?? string.Empty).Trim();
switch (t.ToLowerInvariant())
{
case "max": case "all": case "most":
amount = QtyAmount.Max;
return true;
case "half": case "1/2":
amount = QtyAmount.Half;
return true;
}
string digits = t.Replace(",", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal);
if (digits.Length > 0 && (char.IsDigit(digits[0]) || digits[0] == '-' || digits[0] == '+')
&& long.TryParse(digits, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long n))
{
if (n < 1) { why = $"The quantity is at least 1 (not {t})."; return false; }
if (n > MaxAmount) { why = $"{t} is more than one request can carry (at most {MaxAmount.ToString("N0", CultureInfo.InvariantCulture)})."; return false; }
amount = QtyAmount.Of((int)n);
return true;
}
why = t.Length == 0 ? $"How many? {Usage}." : $"'{t}' isn't a quantity: {Usage}.";
return false;
}
/// <summary>Whether a word reads as a quantity (a number of any size, or max / half), so "25 into Sack" splits off the 25.</summary>
public static bool LooksLikeAmount(string word)
{
string w = word.Trim().ToLowerInvariant();
if (w is "max" or "all" or "most" or "half" or "1/2") return true;
return w.Length > 0 && (char.IsDigit(w[0]) || ((w[0] == '-' || w[0] == '+') && w.Length > 1 && char.IsDigit(w[1])));
}
/// <summary>
/// The arguments of split / give / buy: an optional quantity first, then the rest ("into Sack", an
/// item name). False only when the first word reads as a quantity and is a wrong one ("0", "-3").
/// </summary>
public static bool TryParseLeading(string? args, out QtyAmount? amount, out string rest, out string why)
{
amount = null;
why = string.Empty;
string a = (args ?? string.Empty).Trim();
int sp = a.IndexOf(' ');
string first = sp < 0 ? a : a[..sp];
rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
if (first.Length == 0 || !LooksLikeAmount(first))
{
rest = a;
return true;
}
if (!TryParse(first, out QtyAmount q, out why)) return false;
amount = q;
return true;
}
/// <summary><paramref name="n"/> within 1 .. <paramref name="max"/> (1 when max is below 1).</summary>
public static int Clamp(int n, int max) => max < 1 ? 1 : Math.Clamp(n, 1, max);
/// <summary>Half of <paramref name="of"/>, at least 1.</summary>
public static int HalfOf(int of) => Math.Max(1, of / 2);
/// <summary>How many a split takes from a stack of <paramref name="stack"/>: at least one stays; 0 = not a stack.</summary>
public static int SplitCount(int n, int stack) => stack < 2 ? 0 : Clamp(n, stack - 1);
/// <summary>How many a give hands over: up to the whole stack; 0 = nothing there.</summary>
public static int GiveCount(int n, int stack) => stack < 1 ? 0 : Clamp(n, stack);
/// <summary>A split's count from what was typed (or the box's number): "max" stack-1, "half" half the stack.</summary>
public static int ForSplit(QtyAmount a, int stack) => stack < 2 ? 0 : a.Word switch
{
QtyWord.Max => stack - 1,
QtyWord.Half => SplitCount(HalfOf(stack), stack),
_ => SplitCount(a.Number, stack),
};
/// <summary>A give's count: "max" the whole stack, "half" half of it.</summary>
public static int ForGive(QtyAmount a, int stack) => stack < 1 ? 0 : a.Word switch
{
QtyWord.Max => stack,
QtyWord.Half => HalfOf(stack),
_ => GiveCount(a.Number, stack),
};
/// <summary>
/// The box's number after /rdef qty or a button: a typed number as typed (1 .. MaxAmount); "max"
/// and "half" of <paramref name="max"/> (the whole stack, or the most you can buy). 0 when max or
/// half has nothing to be of.
/// </summary>
public static int ForBox(QtyAmount a, int max) => a.Word switch
{
QtyWord.Max => max >= 1 ? Math.Min(max, MaxAmount) : 0,
QtyWord.Half => max >= 1 ? HalfOf(Math.Min(max, MaxAmount)) : 0,
_ => Math.Clamp(a.Number, 1, MaxAmount),
};
/// <summary>A buy's count: exactly the number typed (VendorQuote.Refusal says when it can't go); "max" the most you can buy.</summary>
public static int ForBuy(QtyAmount a, int maxBuy) => a.Word switch
{
QtyWord.Max => Math.Max(0, maxBuy),
QtyWord.Half => maxBuy >= 1 ? HalfOf(maxBuy) : 0,
_ => a.Number,
};
public static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}
/// <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.
/// </summary>
internal sealed record VendorQuote
{
public const uint ItemTypePromissoryNote = 0x00040000;
public string Name { get; init; } = string.Empty;
public uint ItemType { get; init; }
public int UnitValue { get; init; }
/// <summary>What one costs at this vendor (the engine's server-rounded figure; shown, not summed).</summary>
public int UnitPrice { get; init; }
public int ListingValue { get; init; }
public int UnitBurden { get; init; }
public int ListingBurden { get; init; }
/// <summary>The largest stack (above 0 = stackable, ACE's rule).</summary>
public int MaxStack { get; init; }
public bool Unlimited { get; init; }
/// <summary>How many the vendor has (a limited listing).</summary>
public int Stock { get; init; }
public float SellRate { get; init; } = 1f;
public bool NeedsContainerSlot { get; init; }
public string Currency { get; init; } = "pyreals";
/// <summary>Pyreals (or the vendor's own currency) you have; -1 = unknown.</summary>
public long Funds { get; init; } = -1;
public int FreeItemSlots { get; init; } = -1;
public int FreeContainerSlots { get; init; } = -1;
public long FreeBurden { 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)
{
int stack = Math.Max(1, item.StackSize);
bool alt = info.UsesAltCurrency;
return new VendorQuote
{
Name = item.Name,
ItemType = item.ItemType,
UnitValue = item.UnitValue,
UnitPrice = item.UnitPrice,
ListingValue = item.Value,
UnitBurden = stack > 1 ? item.Burden / stack : item.Burden,
ListingBurden = item.Burden,
MaxStack = item.MaxStackSize,
Unlimited = item.Unlimited || item.Amount < 0,
Stock = Math.Max(0, item.Amount),
SellRate = info.SellRate,
NeedsContainerSlot = item.NeedsContainerSlot,
Currency = alt ? (info.AltCurrencyName.Length > 0 ? info.AltCurrencyName : "the vendor's currency") : "pyreals",
Funds = alt ? info.AltCurrencyHave : info.PlayerCoins,
FreeItemSlots = freeItemSlots,
FreeContainerSlots = freeContainerSlots,
FreeBurden = freeBurden,
};
}
/// <summary>What the player pays for one created stack worth <paramref name="stackValue"/> (ACE Vendor.GetSellCost).</summary>
public long PaysForStack(long stackValue)
{
float rate = ItemType == ItemTypePromissoryNote ? 1.15f : SellRate;
float product = rate * stackValue;
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
}
/// <summary>Cost, pack slots and burden of buying <paramref name="n"/>.</summary>
public void Estimate(int n, out long cost, out long slots, out long burden)
{
long unitValue = Math.Max(0, UnitValue), unitBurden = Math.Max(0, UnitBurden);
if (n < 1) { cost = slots = burden = 0; return; }
if (Stackable)
{
long max = MaxStack, full = n / max, rem = n % max;
cost = full * PaysForStack(unitValue * max) + (rem > 0 ? PaysForStack(unitValue * rem) : 0);
slots = full + (rem > 0 ? 1 : 0);
}
else
{
cost = n * PaysForStack(unitValue);
slots = n;
}
burden = n * unitBurden;
if (!Unlimited)
{
cost = Math.Max(cost, PaysForStack(Math.Max(0, ListingValue)));
slots = Math.Max(slots, 1);
burden = Math.Max(burden, Math.Max(0, ListingBurden));
}
}
public long Cost(int n)
{
Estimate(n, out long cost, out _, out _);
return cost;
}
private int FreeSlots => NeedsContainerSlot ? FreeContainerSlots : FreeItemSlots;
/// <summary>Money, room and burden allow <paramref name="n"/> (the vendor's stock aside).</summary>
private bool Fits(int n)
{
Estimate(n, out long cost, out long slots, out long burden);
if (Funds >= 0 && cost > Funds) return false;
if (FreeSlots >= 0 && slots > FreeSlots) return false;
if (FreeBurden >= 0 && burden > FreeBurden) return false;
return true;
}
/// <summary>
/// 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.
/// </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 (cap < 1 || !Fits(1)) return 0;
int lo = 1, hi = cap;
while (lo < hi)
{
int mid = lo + (hi - lo + 1) / 2;
if (Fits(mid)) lo = mid; else hi = mid - 1;
}
return lo;
}
/// <summary>Why buying <paramref name="n"/> can't go, or null when it can (as far as the plugin can tell).</summary>
public string? Refusal(int n)
{
if (n < 1) return "The quantity is at least 1.";
if (n > QuantityRules.MaxAmount) return $"{QuantityRules.N(n)} is more than one buy can carry (at most {QuantityRules.N(QuantityRules.MaxAmount)}).";
if (!Unlimited && n > Stock)
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()}.";
int free = FreeSlots;
if (free >= 0 && slots > free)
{
if (NeedsContainerSlot)
return free == 0 ? $"No room for another pack: {what} need a container slot of their own."
: $"Not enough container slots: {what} need {QuantityRules.N(slots)}, you have {free}{CanBuy()}.";
return free == 0 ? "The pack is full: no free slot for " + what + "."
: $"Not enough room in your packs: {what} need {QuantityRules.N(slots)} free slots, you have {free}{CanBuy()}.";
}
if (FreeBurden >= 0 && burden > FreeBurden)
return $"Too heavy: {what} weigh {QuantityRules.N(burden)} burden, you can carry {QuantityRules.N(FreeBurden)} more{CanBuy()}.";
return null;
}
private string CanBuy()
{
int max = MaxBuy();
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>
public string PriceLine(int n)
{
string cost = n >= 1 ? QuantityRules.N(Cost(n)) + " " + Currency : "-";
return Funds >= 0 ? $"{cost} · you have {QuantityRules.N(Funds)}" : cost;
}
}
/// <summary>What the quantity box's actions say (chat and the Selection window). Pure.</summary>
internal static class QtyReplies
{
public const string NothingSelected = "Nothing is selected. Select a stack in your pack (or an item in a vendor's list) first.";
public const string Busy = "Wait a moment: the last split, give or buy is still waiting for the server.";
public const string NoSplitApi = "This RynthCore can't split stacks for a plugin.";
public const string NoGiveApi = "This RynthCore can't give items for a plugin (it needs plugin API v62).";
public const string NoTradeApi = "This RynthCore can't trade with vendors for a plugin (it needs plugin API v67).";
public const string NoVendor = "No vendor is open: talk to a vendor first.";
public const string NoVendorItem = "Select the item in the vendor's list first (or type its name: /rdef buy 25 Mana Scarab).";
public const string VendorUnreadable = "RynthCore can't trade with this vendor (its list couldn't be read): use the game's own Buy.";
public const string VendorBusy = "A trade with the vendor is still going: wait a moment.";
public const string NoGiveTarget = "Who to? Select the player or NPC first, then the stack: Give goes to the last one you selected.";
public const string MaxNeedsSelection = "max and half are of what is selected: select a stack or a vendor's item first. Usage: /rdef qty <number|max|half>";
public static string NotAStack(string name) => $"That's not a stack: {name} is a single item.";
public static string Wielded(string name) => $"{name} is wielded: take it off first.";
public static string NotReachable(string name) => $"{name} isn't in your packs or in the container you have open.";
public static string NotCarried(string name) => $"{name} isn't in your packs: pick it up first.";
public static string VendorsItem(string name) => $"{name} is the vendor's: Buy takes it (/rdef buy N).";
public static string PackFull(string where) =>
$"{Cap(where)} is full. Pick another pack for the split (the 'into' button, or /rdef split 25 into <pack>).";
public static string NoSuchPack(string typed, string packs) => $"No pack called '{typed}'. Your packs: {packs}.";
public static string NotSent(string what) => $"The {what} couldn't be sent (the game isn't ready for it): nothing changed.";
public static string Splitting(int n, string name, string into) => $"Split {QuantityRules.N(n)} {name} into {into}.";
public static string Gave(int n, string name, string to) => $"Gave {QuantityRules.N(n)} {name} to {to}.";
public static string Bought(int n, string name, long cost, string currency) =>
cost > 0 ? $"Bought {QuantityRules.N(n)} {name} for {QuantityRules.N(cost)} {currency}." : $"Bought {QuantityRules.N(n)} {name}.";
public static string Refused(string what, uint error) =>
error != 0 ? $"The server refused the {what} (error 0x{error:X4}): nothing changed." : $"The server refused the {what}: nothing changed.";
public static string NoAnswer(string what) => $"No answer from the server for the {what}: check your pack before trying again.";
/// <summary>
/// The engine's refusal of a buy (VendorTradeStatus.Message, Compatibility/VendorTrade.cs) in the
/// player's words. Unknown messages are passed on as they are.
/// </summary>
public static string VendorRefusal(string? message)
{
string m = (message ?? string.Empty).Trim();
if (m.Length == 0) return "The vendor didn't sell it.";
if (m.StartsWith("costs ", StringComparison.Ordinal))
{
// "costs 300 pyreals, you have 200" / "costs 3 Ancient Mattekar Claws, you have 1"
int comma = m.IndexOf(", you have ", StringComparison.Ordinal);
string head = comma > 0 ? m[6..comma] : m[6..];
int sp = head.IndexOf(' ');
string currency = sp > 0 ? head[(sp + 1)..] : "pyreals";
return $"Not enough {currency}: it {m}.";
}
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("free pack slots", StringComparison.Ordinal))
return m.EndsWith("you have 0", StringComparison.Ordinal) ? $"The pack is full: it {m}." : $"Not enough room in your packs: it {m}.";
if (m.StartsWith("needs ", StringComparison.Ordinal) && m.Contains("container slots", StringComparison.Ordinal))
return $"No room for another pack: it {m}.";
if (m.StartsWith("adds ", StringComparison.Ordinal) && m.Contains("burden", StringComparison.Ordinal))
return $"Too heavy: it {m}.";
if (m.Contains("vendor only has", StringComparison.Ordinal) || m.StartsWith("bad amount", StringComparison.Ordinal))
return "The vendor doesn't have that many.";
if (m.Contains("no vendor open", StringComparison.Ordinal) || m.Contains("vendor window is closed", StringComparison.Ordinal)
|| m.Contains("vendor closed", StringComparison.Ordinal) || m.Contains("is not the open vendor", StringComparison.Ordinal))
return "The vendor is closed: talk to it again.";
if (m.Contains("not on this vendor's list", StringComparison.Ordinal) || m.Contains("no longer on the vendor's list", StringComparison.Ordinal))
return "The vendor doesn't sell that any more.";
if (m.Contains("requests already waiting", StringComparison.Ordinal))
return VendorBusy;
if (m.Contains("could not read your", StringComparison.Ordinal) || m.Contains("could not count your", StringComparison.Ordinal))
return $"RynthCore couldn't count your money ({m}): try again in a moment.";
return $"The vendor didn't sell it: {m}.";
}
private static string Cap(string s) => s.Length == 0 ? s : char.ToUpperInvariant(s[0]) + s[1..];
}

View file

@ -0,0 +1,252 @@
// ============================================================================
// RynthDefective - Quantity/QtyWorld.cs
// What the quantity box (QuantityController) needs from the game, as an
// interface so the tests drive it offline (RynthDefective.Tests), and the
// engine host's side of it. Plugin pump thread only.
//
// 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.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyPackKind { Main, Side, Open }
/// <summary>A place a split can go: the main pack, a side pack, or the container you have open.</summary>
internal readonly record struct QtyPack(uint Id, string Name, int Capacity, int Count, QtyPackKind Kind)
{
/// <summary>Free item slots; -1 = unknown (the server decides).</summary>
public int Free => Capacity > 0 && Count >= 0 ? Math.Max(0, Capacity - Count) : -1;
/// <summary>In a sentence: "the main pack", "Sack", "Chest".</summary>
public string Where => Kind == QtyPackKind.Main ? "the main pack" : Name;
/// <summary>On a button: "Main pack", "Sack", "Chest (open)".</summary>
public string Label => Kind switch
{
QtyPackKind.Main => "Main pack",
QtyPackKind.Open => Name + " (open)",
_ => Name,
};
}
internal interface IQtyWorld
{
long NowMs { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>AC's selection before this one (0 = none or unknown).</summary>
uint PreviousSelectedId { get; }
/// <summary>The chest or corpse you have open (0 = none).</summary>
uint OpenContainerId { get; }
bool TryGetName(uint id, out string name);
/// <summary>The client knows the object.</summary>
bool Exists(uint id);
/// <summary>Someone to give to: a player or an NPC (a creature that isn't a monster).</summary>
bool CanReceive(uint id);
/// <summary>Where it is: its container and its wielder (0 = none). False = the client doesn't know it.</summary>
bool TryGetOwner(uint id, out uint container, out uint wielder);
/// <summary>Its stack size; 0 = unknown.</summary>
int StackOf(uint id);
/// <summary>The main pack first, then the side packs (the pack column's order), then the open container.</summary>
IReadOnlyList<QtyPack> Packs();
bool CanSplit { get; }
/// <summary>Splits <paramref name="n"/> off the stack into <paramref name="into"/> (a new stack there).</summary>
bool Split(uint id, uint into, int n);
bool CanGive { get; }
/// <summary>Gives <paramref name="n"/> of it (0 = the whole of it) to a player or NPC.</summary>
bool Give(uint id, uint to, int n);
/// <summary>Counts the server's refusals (0 when the engine can't say): note it before a send, compare after.</summary>
int RefusalSeq { get; }
bool LastRefusal(out uint error, out uint eventType, out uint objectId);
bool CanTrade { get; }
/// <summary>The vendor open now (false = none).</summary>
bool TryGetVendor(out VendorInfo info);
IReadOnlyList<VendorItem> VendorItems();
/// <summary>Asks the engine to buy; the request id, or 0 when it refused at once (the trade status says why).</summary>
uint Buy(uint vendorId, uint itemId, int n);
bool TryGetTradeStatus(out VendorTradeStatus status);
/// <summary>Free container slots (for packs and foci bought); -1 = unknown.</summary>
int FreeContainerSlots();
/// <summary>Burden you can still carry (three times your capacity, as ACE); -1 = unknown.</summary>
long FreeBurden();
}
/// <summary>The engine host's side (RynthCoreHost). Plugin pump thread only.</summary>
internal sealed class HostQtyWorld : IQtyWorld
{
// STypeInt
private const uint EncumbranceVal = 5, ItemsCapacity = 6, ContainersCapacity = 7, StackSize = 12, EncumbranceCapacity = 96;
private const uint ItemTypeCreature = 0x10, ItemTypeContainer = 0x200;
// PublicWeenieDesc bitfield (ObjectDescriptionFlag).
private const uint BitPlayer = 0x8, BitAttackable = 0x10;
private const int MainPackDefault = 102, ContainerSlotsDefault = 7;
private readonly RynthCoreHost _h;
private uint[] _contents = new uint[256];
private uint[] _order = new uint[16];
private uint _vendorId, _vendorGeneration;
private VendorItem[] _vendorItems = Array.Empty<VendorItem>();
public HostQtyWorld(RynthCoreHost host) => _h = host;
public long NowMs => Environment.TickCount64;
public uint PlayerId => _h.HasGetPlayerId ? _h.GetPlayerId() : 0;
public uint SelectedId => _h.HasGetSelectedItemId ? _h.GetSelectedItemId() : 0;
public uint PreviousSelectedId => _h.HasGetPreviousSelectedItemId ? _h.GetPreviousSelectedItemId() : 0;
public uint OpenContainerId => _h.HasGetGroundContainerId ? _h.GetGroundContainerId() : 0;
public bool TryGetName(uint id, out string name)
{
name = string.Empty;
if (id == 0 || !_h.TryGetObjectName(id, out string n) || string.IsNullOrWhiteSpace(n)) return false;
name = n.Trim();
return true;
}
public bool Exists(uint id) => id != 0 && _h.TryGetItemType(id, out _);
/// <summary>
/// A creature that is a player (description bit Player 0x8) or isn't attackable (Attackable 0x10: a
/// monster): a monster selected in a fight never becomes the give target. Without the description
/// bits (an older engine) any creature; the server refuses a give it doesn't take.
/// </summary>
public bool CanReceive(uint id)
{
if (id == 0 || !_h.TryGetItemType(id, out uint t) || (t & ItemTypeCreature) == 0) return false;
if (!_h.HasGetObjectBitfield || !_h.TryGetObjectBitfield(id, out uint bits)) return true;
return (bits & BitPlayer) != 0 || (bits & BitAttackable) == 0;
}
public bool TryGetOwner(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (id == 0) return false;
if (_h.HasGetObjectOwnershipInfo && _h.TryGetObjectOwnershipInfo(id, out container, out wielder, out _)) return true;
return false;
}
public int StackOf(uint id) => id != 0 && _h.TryGetObjectIntProperty(id, StackSize, out int s) && s > 0 ? s : 0;
private int Int(uint id, uint stype) => _h.TryGetObjectIntProperty(id, stype, out int v) ? v : -1;
public IReadOnlyList<QtyPack> Packs()
{
var packs = new List<QtyPack>(8);
uint player = PlayerId;
if (player == 0) return packs;
int mainCap = Int(player, ItemsCapacity);
packs.Add(new QtyPack(player, "Main pack", mainCap > 0 ? mainCap : MainPackDefault, Count(player), QtyPackKind.Main));
// The side packs, in the pack column's order when the engine knows it (v80), else as the client lists them.
var ids = new List<uint>(8);
if (_h.HasContainerOrder && _h.TryGetContainerOrder(player, true, ref _order, out int ordered) && ordered > 0)
for (int i = 0; i < ordered && i < _order.Length; i++) ids.Add(_order[i]);
else if (_h.HasGetContainerContents)
{
int n = _h.GetContainerContents(player, _contents);
if (n > _contents.Length && n <= 4096) { _contents = new uint[n]; n = _h.GetContainerContents(player, _contents); }
for (int i = 0; i < n && i < _contents.Length; i++) ids.Add(_contents[i]);
}
var names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (uint id in ids)
{
if (id == 0 || !_h.TryGetItemType(id, out uint type) || (type & ItemTypeContainer) == 0) continue;
int cap = Int(id, ItemsCapacity);
if (cap <= 0) continue; // a focus holds no items
if (TryGetOwner(id, out uint c, out uint w) && (c != player || w != 0)) continue;
string name = TryGetName(id, out string nm) ? nm : "Pack";
names[name] = names.TryGetValue(name, out int seen) ? seen + 1 : 1;
if (names[name] > 1) name += " " + names[name];
packs.Add(new QtyPack(id, name, cap, Count(id), QtyPackKind.Side));
}
uint open = OpenContainerId;
if (open != 0 && open != player && !packs.Exists(p => p.Id == open))
{
string name = TryGetName(open, out string nm) ? nm : "The open container";
packs.Add(new QtyPack(open, name, Int(open, ItemsCapacity), Count(open), QtyPackKind.Open));
}
return packs;
}
private int Count(uint container) => _h.HasGetNumContainedItems ? _h.GetNumContainedItems(container) : -1;
public bool CanSplit => _h.HasSplitStackInternal;
// Slot 0 with a count below the stack: the client's StackableSplitToContainer, as the engine's own
// Inventory panel splits (InventoryModel). The new stack takes a free slot of the target.
public bool Split(uint id, uint into, int n) => CanSplit && n >= 1 && _h.SplitStackInternal(id, into, 0, n);
public bool CanGive => _h.HasGiveObjectTo;
public bool Give(uint id, uint to, int n) => CanGive && _h.GiveObjectTo(id, to, Math.Max(0, n));
public int RefusalSeq => _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool LastRefusal(out uint error, out uint eventType, out uint objectId)
{
error = eventType = objectId = 0;
return _h.HasGetLastWeenieError && _h.TryGetLastWeenieError(out _, out error, out eventType, out objectId);
}
public bool CanTrade => _h.HasVendorTrade;
public bool TryGetVendor(out VendorInfo info)
{
info = null!;
return CanTrade && _h.TryGetVendorInfo(out info) && info.VendorId != 0;
}
/// <summary>The open vendor's list, read again only when the vendor or its list (Generation) changed.</summary>
public IReadOnlyList<VendorItem> VendorItems()
{
if (!TryGetVendor(out VendorInfo info))
{
_vendorId = 0;
_vendorItems = Array.Empty<VendorItem>();
return _vendorItems;
}
if (info.VendorId != _vendorId || info.Generation != _vendorGeneration || _vendorItems.Length == 0)
{
_vendorItems = _h.GetVendorItems();
_vendorId = info.VendorId;
_vendorGeneration = info.Generation;
}
return _vendorItems;
}
public uint Buy(uint vendorId, uint itemId, int n) => CanTrade ? _h.VendorBuy(itemId, n, vendorId) : 0;
public bool TryGetTradeStatus(out VendorTradeStatus status)
{
status = null!;
return CanTrade && _h.TryGetVendorTradeStatus(out status);
}
public int FreeContainerSlots()
{
uint player = PlayerId;
if (player == 0 || !_h.HasGetNumContainedContainers) return -1;
int n = _h.GetNumContainedContainers(player);
if (n < 0) return -1;
int cap = Int(player, ContainersCapacity);
return Math.Max(0, (cap > 0 ? cap : ContainerSlotsDefault) - n);
}
public long FreeBurden()
{
uint player = PlayerId;
if (player == 0) return -1;
int carried = Int(player, EncumbranceVal), cap = Int(player, EncumbranceCapacity);
if (carried < 0 || cap <= 0) return -1; // unknown: the engine checks with its own reading
return Math.Max(0, 3L * cap - carried);
}
}

View file

@ -0,0 +1,552 @@
// ============================================================================
// RynthDefective - Quantity/QuantityController.cs
// The quantity box (2026-10-30): one number, and what it does to what is
// selected. Asked for by a player: "to select a portion of a stack, or buy
// multiple of an item from a vendor, I need a place to type in the number".
//
// a stack you carry Split N into the main pack, a side pack or the
// (or in the chest you have container you have open; Give N to the player
// 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
//
// 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.
// Nothing here needs the engine's Inventory panel or RynthInventory.
//
// One action at a time. Each one answers once: at once when it can't go
// (why, in the player's words), or when the game answers (the stack got
// smaller, the item left your packs, the vendor's trade finished) or doesn't
// (a refusal from the server, or no answer in time).
//
// Threads: everything on the plugin pump, except Value and Into, which the
// Selection window sets from the render thread (single ints).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Quantity;
internal enum QtyMode { None, Single, Stack, Vendor }
/// <summary>Where the selected item is, for a split or a give.</summary>
internal enum QtyWhere { Unknown, Carried, Wielded, Open, Elsewhere }
/// <summary>What is selected, as the box sees it.</summary>
internal sealed record QtySubject(QtyMode Mode, uint Id, string Name, int Stack, QtyWhere Where)
{
public static readonly QtySubject Nothing = new(QtyMode.None, 0, string.Empty, 0, QtyWhere.Unknown);
/// <summary>A vendor's item: its price and what you have.</summary>
public VendorQuote? Quote { get; init; }
public uint VendorId { get; init; }
/// <summary>The most you can buy now (vendor items).</summary>
public int MaxBuy { get; init; }
/// <summary>What the box's "max" is of: the whole stack, or the most you can buy; 0 = nothing.</summary>
public int BoxMax => Mode switch
{
QtyMode.Stack => Stack,
QtyMode.Vendor => MaxBuy,
_ => 0,
};
}
/// <summary>The box as the Selection window draws it (built on the tick).</summary>
internal sealed record QuantityView(QtySubject Subject, QtyPack[] Targets, int TargetIndex, uint GiveTo, string GiveName,
bool Busy, bool CanSplit, bool CanGive)
{
public QtyPack? Target => TargetIndex >= 0 && TargetIndex < Targets.Length ? Targets[TargetIndex] : null;
}
/// <summary>The last thing the box did, for the Selection window's line.</summary>
internal sealed record QtyStatus(string Text, bool Ok, long AtMs);
internal sealed class QuantityController
{
/// <summary>How long a split, a give (the server may walk you to the NPC first) and a buy wait for the game.</summary>
public const long SplitAnswerMs = 6000, GiveAnswerMs = 20_000, BuyAnswerMs = 15_000;
/// <summary>A refusal that doesn't name the item is ours if nothing changed this long after it.</summary>
public const long RefusalGraceMs = 1500;
/// <summary>The last player or NPC selected stays the give target this long.</summary>
public const long GiveTargetMs = 10 * 60 * 1000;
public const long StatusShownMs = 8000;
/// <summary>InventoryServerSaveFailed: the server refused a move, split or give of this item.</summary>
private const uint InventorySaveFailed = 0x00A0;
private int _value = 1;
private uint _into;
private volatile QtyStatus? _status;
private uint _lastSelection, _giveId;
private string _giveName = string.Empty;
private long _giveAtMs;
private Pending? _pending;
/// <summary>Every answer (ok, text): the plugin writes it in chat.</summary>
public Action<bool, string> Report = (_, _) => { };
/// <summary>The box's number (1 .. MaxAmount). Any thread.</summary>
public int Value
{
get => Volatile.Read(ref _value);
set => Volatile.Write(ref _value, Math.Clamp(value, 1, QuantityRules.MaxAmount));
}
/// <summary>The pack a split goes into (its id); 0 or a pack that's gone = the main pack. Any thread.</summary>
public uint Into
{
get => Volatile.Read(ref _into);
set => Volatile.Write(ref _into, value);
}
public bool Busy => _pending != null;
/// <summary>The last answer while it is fresh. Any thread.</summary>
public QtyStatus? StatusAt(long nowMs)
{
QtyStatus? s = _status;
return s != null && nowMs - s.AtMs < StatusShownMs ? s : null;
}
public void Reset()
{
_pending = null;
_status = null;
_giveId = _lastSelection = 0;
_giveName = string.Empty;
Into = 0;
}
private void Say(IQtyWorld w, bool ok, string text)
{
_status = new QtyStatus(text, ok, w.NowMs);
Report(ok, text);
}
// ── What is selected ────────────────────────────────────────────────────
public QtySubject Analyze(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == 0) return QtySubject.Nothing;
string name = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
if (w.CanTrade && w.TryGetVendor(out VendorInfo info))
{
foreach (VendorItem it in w.VendorItems())
{
if (it.ObjectId != sel) continue;
VendorQuote q = Quote(w, info, it);
return new QtySubject(QtyMode.Vendor, sel, it.Name.Length > 0 ? it.Name : name, Math.Max(1, it.StackSize), QtyWhere.Elsewhere)
{
Quote = q,
VendorId = info.VendorId,
MaxBuy = q.MaxBuy(),
};
}
}
int stack = w.StackOf(sel);
return new QtySubject(stack >= 2 ? QtyMode.Stack : QtyMode.Single, sel, name, Math.Max(1, stack), WhereIs(w, sel));
}
private static QtyWhere WhereIs(IQtyWorld w, uint id)
{
uint player = w.PlayerId;
if (player == 0 || !w.TryGetOwner(id, out uint c, out uint wielder)) return QtyWhere.Unknown;
if (wielder != 0 && wielder == player) return QtyWhere.Wielded;
if (c == player) return QtyWhere.Carried;
if (c != 0 && w.TryGetOwner(c, out uint outer, out uint outerWielder) && outer == player && outerWielder == 0) return QtyWhere.Carried;
if (c != 0 && c == w.OpenContainerId) return QtyWhere.Open;
return QtyWhere.Elsewhere;
}
private static bool Owned(IQtyWorld w, uint id)
{
QtyWhere where = WhereIs(w, id);
return where is QtyWhere.Carried or QtyWhere.Wielded;
}
private static VendorQuote Quote(IQtyWorld w, VendorInfo info, VendorItem item)
{
int free = 0;
foreach (QtyPack p in w.Packs())
{
if (p.Kind == QtyPackKind.Open) continue;
if (p.Free < 0) { free = -1; break; }
free += p.Free;
}
return VendorQuote.From(info, item, free, w.FreeContainerSlots(), w.FreeBurden());
}
/// <summary>
/// The Selection window's box: for a vendor's item, or a stack you carry, wield (it says to take it
/// off) or have in the open container. Not for a stack on the ground or in someone else's hands. Plugin tick.
/// </summary>
public QuantityView? View(IQtyWorld w)
{
QtySubject s = Analyze(w);
if (s.Mode is not (QtyMode.Stack or QtyMode.Vendor)) return null;
if (s.Mode == QtyMode.Stack && s.Where is not (QtyWhere.Carried or QtyWhere.Wielded or QtyWhere.Open)) return null;
QtyPack[] targets = s.Mode == QtyMode.Stack ? new List<QtyPack>(w.Packs()).ToArray() : Array.Empty<QtyPack>();
int index = 0;
uint into = Into;
for (int i = 0; i < targets.Length; i++) if (targets[i].Id == into) { index = i; break; }
TryGiveTarget(w, s.Id, out uint to, out string toName);
return new QuantityView(s, targets, targets.Length == 0 ? -1 : index, to, toName, Busy, w.CanSplit, w.CanGive);
}
// ── The give target: the last player or NPC selected ─────────────────────
/// <summary>Notes a newly selected player or NPC (not you, not a monster) as the give target. Plugin tick, a few times a second.</summary>
public void NoteSelection(IQtyWorld w)
{
uint sel = w.SelectedId;
if (sel == _lastSelection) return;
_lastSelection = sel;
if (sel == 0 || sel == w.PlayerId || !w.CanReceive(sel)) return;
_giveId = sel;
_giveName = w.TryGetName(sel, out string n) ? n : $"0x{sel:X8}";
_giveAtMs = w.NowMs;
}
/// <summary>Who a give goes to: the last player or NPC selected (within GiveTargetMs and still there), else AC's previous selection.</summary>
public bool TryGiveTarget(IQtyWorld w, uint item, out uint to, out string name)
{
uint player = w.PlayerId;
if (_giveId != 0 && _giveId != item && w.NowMs - _giveAtMs < GiveTargetMs && w.Exists(_giveId))
{
to = _giveId;
name = _giveName;
return true;
}
uint prev = w.PreviousSelectedId;
if (prev != 0 && prev != item && prev != player && w.CanReceive(prev))
{
to = prev;
name = w.TryGetName(prev, out string n) ? n : $"0x{prev:X8}";
return true;
}
to = 0;
name = string.Empty;
return false;
}
// ── /rdef qty ───────────────────────────────────────────────────────────
/// <summary>Sets the box (null: says what it is). "max" and "half" are of what is selected.</summary>
public void SetBox(IQtyWorld w, QtyAmount? amount)
{
QtySubject s = Analyze(w);
if (amount is { } a)
{
if (a.Word != QtyWord.Number && s.BoxMax < 1)
{
Say(w, false, s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? QtyReplies.MaxNeedsSelection : QtyReplies.MaxNeedsSelection);
return;
}
Value = QuantityRules.ForBox(a, s.BoxMax);
}
Say(w, true, $"Quantity {QuantityRules.N(Value)}{About(s)}.");
}
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)})",
_ => string.Empty,
};
// ── Split ───────────────────────────────────────────────────────────────
/// <summary>
/// Splits the box's number (or <paramref name="amount"/>) off the selected stack into
/// <paramref name="into"/> (a pack's name; empty = the pack chosen in the window, else the main pack).
/// </summary>
public void Split(IQtyWorld w, QtyAmount? amount, string into)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanSplit) { Say(w, false, QtyReplies.NoSplitApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
QtyMode.Single => QtyReplies.NotAStack(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried or QtyWhere.Open => null,
_ => QtyReplies.NotReachable(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
IReadOnlyList<QtyPack> packs = w.Packs();
if (!TryPickTarget(packs, into, out QtyPack target, out why)) { Say(w, false, why); return; }
if (target.Free == 0) { Say(w, false, QtyReplies.PackFull(target.Where)); return; }
int n = QuantityRules.ForSplit(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Split, Id = s.Id, Name = s.Name, N = n, Where = target.Where,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
if (!w.Split(s.Id, target.Id, n)) { Say(w, false, QtyReplies.NotSent("split")); return; }
_pending = p;
}
/// <summary>The split's pack: the one named, else the one chosen in the window (if it's still there), else the main pack.</summary>
internal bool TryPickTarget(IReadOnlyList<QtyPack> packs, string typed, out QtyPack target, out string why)
{
target = default;
why = string.Empty;
if (packs.Count == 0) { why = "Your packs can't be read yet: try again in a moment."; return false; }
string t = (typed ?? string.Empty).Trim();
if (t.Length == 0)
{
uint into = Into;
target = packs[0];
foreach (QtyPack p in packs) if (p.Id == into) { target = p; break; }
return true;
}
string low = t.ToLowerInvariant();
if (low is "main" or "main pack" or "mainpack" or "pack" or "me" or "inventory")
{
target = packs[0];
return true;
}
if (low is "open" or "chest" or "container" or "the chest" or "the open container")
{
foreach (QtyPack p in packs) if (p.Kind == QtyPackKind.Open) { target = p; return true; }
why = "No chest or other container is open: open it first, or split into one of your packs.";
return false;
}
// The pack's own name: the whole of it, then its start, then any part of it.
foreach (QtyPack p in packs) if (p.Name.Equals(t, StringComparison.OrdinalIgnoreCase) || p.Label.Equals(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.StartsWith(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
foreach (QtyPack p in packs) if (p.Name.Contains(t, StringComparison.OrdinalIgnoreCase)) { target = p; return true; }
var names = new List<string>(packs.Count);
foreach (QtyPack p in packs) names.Add(p.Label);
why = QtyReplies.NoSuchPack(t, string.Join(", ", names));
return false;
}
// ── Give ────────────────────────────────────────────────────────────────
/// <summary>Gives the box's number (or <paramref name="amount"/>) of the selected stack to the last player or NPC selected.</summary>
public void Give(IQtyWorld w, QtyAmount? amount)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanGive) { Say(w, false, QtyReplies.NoGiveApi); return; }
QtySubject s = Analyze(w);
string? why = s.Mode switch
{
QtyMode.None => QtyReplies.NothingSelected,
QtyMode.Vendor => QtyReplies.VendorsItem(s.Name),
_ => s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Carried => null,
_ => QtyReplies.NotCarried(s.Name),
},
};
if (why != null) { Say(w, false, why); return; }
if (!TryGiveTarget(w, s.Id, out uint to, out string toName)) { Say(w, false, QtyReplies.NoGiveTarget); return; }
int n = QuantityRules.ForGive(amount ?? QtyAmount.Of(Value), s.Stack);
var p = new Pending
{
Kind = PendingKind.Give, Id = s.Id, Name = s.Name, N = n, Where = toName,
StackBefore = s.Stack, RefusalSeq = w.RefusalSeq, AtMs = w.NowMs,
};
// 0 = the whole of it (the give the client sends for a drag of the whole stack).
if (!w.Give(s.Id, to, n >= s.Stack ? 0 : n)) { Say(w, false, QtyReplies.NotSent("give")); return; }
_pending = p;
}
// ── Buy ─────────────────────────────────────────────────────────────────
/// <summary>Buys the box's number (or <paramref name="amount"/>) of the selected vendor item, or the one named.</summary>
public void Buy(IQtyWorld w, QtyAmount? amount, string itemName)
{
if (_pending != null) { Say(w, false, QtyReplies.Busy); return; }
if (!w.CanTrade) { Say(w, false, QtyReplies.NoTradeApi); return; }
if (!w.TryGetVendor(out VendorInfo info)) { Say(w, false, QtyReplies.NoVendor); return; }
if (!info.TradingAvailable) { Say(w, false, QtyReplies.VendorUnreadable); return; }
if (info.TradeInFlight) { Say(w, false, QtyReplies.VendorBusy); return; }
IReadOnlyList<VendorItem> items = w.VendorItems();
VendorItem? item;
string name = (itemName ?? string.Empty).Trim();
if (name.Length > 0)
{
item = FindVendorItem(items, name, out string? why);
if (item == null) { Say(w, false, why!); return; }
}
else
{
item = null;
uint sel = w.SelectedId;
foreach (VendorItem it in items) if (it.ObjectId == sel && sel != 0) { item = it; break; }
if (item == null) { Say(w, false, QtyReplies.NoVendorItem); return; }
}
VendorQuote q = Quote(w, info, item);
int n = amount is { } a ? QuantityRules.ForBuy(a, q.MaxBuy()) : Value;
if (n < 1) { Say(w, false, q.Refusal(1) ?? $"You can't buy any {item.Name} now."); return; }
string? refusal = q.Refusal(n);
if (refusal != null) { Say(w, false, refusal); return; }
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));
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,
};
}
/// <summary>A vendor's item by name: the whole name, else the one whose name starts so, else the one that holds it. Several = ask for more.</summary>
internal static VendorItem? FindVendorItem(IReadOnlyList<VendorItem> items, string name, out string? why)
{
why = null;
foreach (VendorItem it in items) if (it.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return it;
foreach (bool starts in new[] { true, false })
{
VendorItem? found = null;
var names = new List<string>();
foreach (VendorItem it in items)
{
bool match = starts ? it.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase) : it.Name.Contains(name, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
if (!names.Exists(x => x.Equals(it.Name, StringComparison.OrdinalIgnoreCase))) names.Add(it.Name);
found ??= it;
}
if (names.Count == 1) return found;
if (names.Count > 1)
{
why = $"'{name}' could be {string.Join(", ", names.GetRange(0, Math.Min(5, names.Count)))}{(names.Count > 5 ? ", ..." : "")}: type more of the name.";
return null;
}
}
why = $"The vendor doesn't sell '{name}'.";
return null;
}
// ── Waiting for the game ────────────────────────────────────────────────
private enum PendingKind { Split, Give, Buy }
private sealed class Pending
{
public PendingKind Kind;
public uint Id;
public string Name = string.Empty;
public int N;
/// <summary>Split: the pack ("the main pack"); give: who to.</summary>
public string Where = string.Empty;
public int StackBefore;
public int RefusalSeq;
public long AtMs;
public long RefusedAtMs;
public uint Error;
public bool RefusalNamesItem;
public uint RequestId;
public long Cost;
public string Currency = string.Empty;
}
/// <summary>Plugin tick: the give target, and the answer to the action in flight.</summary>
public void Tick(IQtyWorld w)
{
NoteSelection(w);
Pending? p = _pending;
if (p == null) return;
long now = w.NowMs;
switch (p.Kind)
{
case PendingKind.Split:
{
int stack = w.StackOf(p.Id);
if (stack > 0 && stack < p.StackBefore) Finish(w, true, QtyReplies.Splitting(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("split", p.Error));
else if (now - p.AtMs >= SplitAnswerMs) Finish(w, false, QtyReplies.NoAnswer("split"));
break;
}
case PendingKind.Give:
{
int stack = w.StackOf(p.Id);
bool left = !w.Exists(p.Id) || !Owned(w, p.Id);
if (left || (stack > 0 && stack < p.StackBefore)) Finish(w, true, QtyReplies.Gave(p.N, p.Name, p.Where));
else if (RefusedNow(w, p, now)) Finish(w, false, QtyReplies.Refused("give", p.Error));
else if (now - p.AtMs >= GiveAnswerMs) Finish(w, false, QtyReplies.NoAnswer("give"));
break;
}
case PendingKind.Buy:
WatchBuy(w, p, now);
break;
}
}
private void WatchBuy(IQtyWorld w, Pending p, long now)
{
if (w.TryGetTradeStatus(out VendorTradeStatus s))
{
if (s.RequestId == p.RequestId)
{
if (s.State == VendorTradeState.Refused) { Finish(w, false, QtyReplies.VendorRefusal(s.Message)); return; }
if (s.State == VendorTradeState.Done)
{
if (s.Result == VendorTradeResult.Accepted)
Finish(w, true, QtyReplies.Bought(p.N, p.Name, s.Estimate > 0 ? s.Estimate : p.Cost, p.Currency));
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).");
return;
}
}
else if (s.RequestId > p.RequestId)
{
// Another plugin's trade came after ours: the engine keeps only the newest one's status.
Finish(w, true, $"Asked the vendor for {QuantityRules.N(p.N)} {p.Name}; another trade followed it, so check your pack.");
return;
}
}
if (now - p.AtMs >= BuyAnswerMs)
Finish(w, false, $"No answer about {QuantityRules.N(p.N)} {p.Name}: check your pack and {p.Currency} before trying again.");
}
/// <summary>
/// The server refused it: a refusal naming the item (InventoryServerSaveFailed) at once, any other
/// new refusal once nothing changed for RefusalGraceMs after it (a fight's own errors pass by).
/// </summary>
private static bool RefusedNow(IQtyWorld w, Pending p, long now)
{
int seq = w.RefusalSeq;
if (p.RefusedAtMs == 0 && seq != 0 && seq != p.RefusalSeq && w.LastRefusal(out uint error, out uint eventType, out uint obj))
{
p.RefusalSeq = seq;
bool names = eventType == InventorySaveFailed && obj != 0;
if (names && obj != p.Id) return false; // another item's
p.RefusedAtMs = now;
p.Error = error;
p.RefusalNamesItem = names;
}
return p.RefusedAtMs != 0 && (p.RefusalNamesItem || now - p.RefusedAtMs >= RefusalGraceMs);
}
private void Finish(IQtyWorld w, bool ok, string text)
{
_pending = null;
Say(w, ok, text);
}
}

View file

@ -89,6 +89,25 @@ buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave presse
hand is highlighted. **One click wields.** `+` in front of a row adds a favourite; favourites and the last
weapons you wielded are listed first (they are also in their kind's group).
## The quantity box
Under a selected stack, or an item in an open vendor's list, the Selection window shows how many: type the
number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100, half or max.
* **A stack you carry** (or one in the chest you have open): **Split N** puts N into a new stack in the main
pack, a side pack or the open container (*into ...* picks; the number is its free slots). One always stays in
the stack, so more than the stack splits all but one. **Give N** hands N (up to the whole stack) to the last
player or NPC you selected: select them, then the stack.
* **An item in a vendor's list**: **Buy N**, with its price and your pyreals (or the vendor's own currency).
*max* is the most you can buy: what the vendor has, what you can pay for, what your packs and burden take.
A buy that can't go says why before anything is sent ("Not enough pyreals: 100 Mana Scarab cost 1,200, you
have 1,000 (you can buy 83)", "The pack is full ..."); the engine checks again before it sends.
* Every action answers once, in chat and on the box's last line: done, the server's refusal, or no answer.
One action at a time.
* The same from chat, hotkeys and metas, with the window hidden: `/rdef qty`, `/rdef split`, `/rdef give`,
`/rdef buy` (below). It doesn't need the Inventory panel or RynthInventory.
* Retail AC kept this number in its toolbar; RynthCore's *Hide retail toolbar* hides it with the toolbar.
## Busy, combat and RynthAi
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
@ -123,6 +142,11 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef weapons [search] show the weapon picker
/rdef fav make the selected weapon a favourite (or take it out)
/rdef slots <n> how many slots the script-window bar shows (1-24)
/rdef qty [n | max | half] the quantity box's number (alone: what it is and what it's of)
/rdef split [n] [into <pack>] split n (or the box's number) off the selected stack; pack: main, a side
pack's name, or open (the chest you have open)
/rdef give [n] give n of the selected stack to the last player or NPC you selected
/rdef buy [n] [item name] buy n of the selected vendor item (or the one named) from the open vendor
/rdef list | status | help
```
@ -131,8 +155,8 @@ slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's
## Settings
Shortcuts bar: the windows shown, independent of the game's toolbar, slot picture size, allow weapon swaps
under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row
Shortcuts bar: the windows shown, the quantity box under the selection (on by default), independent of the
game's toolbar, slot picture size, allow weapon swaps under RynthAi, picker row icon size. Script-window bar: slots (1-24), slots per row, button size, picker row
icon size, item icons on/off, counts and keys on/off, allow weapon swaps under RynthAi. Kept per character
with the slots, favourites and recent weapons in
`<RynthSuite>\RynthDefective\characters\<server>_<character>.json`.
@ -146,3 +170,4 @@ Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-ma
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it);
API 90 for the Shortcuts bar, Game Panels and Selection. `/rdef use` works on any engine with UseObject.
The quantity commands: splitting on any engine, giving with a count API 62, buying API 67.

View file

@ -31,7 +31,7 @@
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
<RynthPluginDescription>Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window (with a quantity box: split, give or buy that many): one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>

View file

@ -0,0 +1,76 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Quantity.cs
// The quantity box (2026-10-30, Quantity/QuantityController.cs): its commands
// (/rdef qty, split, give, buy), the Selection window's buttons, and the tick
// that notes the give target and watches the action in flight.
//
// It lives here, with the Selection window, because the number is about what
// is selected (as retail's toolbar had it): it needs no inventory panel, and
// every command works with the window hidden or on an engine without it.
// ============================================================================
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
private readonly QuantityController _qty = new();
private HostQtyWorld? _qtyWorld;
private long _nextQtyTickMs;
private HostQtyWorld QtyWorld => _qtyWorld ??= new HostQtyWorld(Host);
/// <summary>Every answer of the box goes to chat (and to the window's line).</summary>
private void InitQuantity()
{
_qty.Report = (ok, text) => Reply.Say(ok, text);
}
private void RunQuantityCommand(DefCommand c)
{
switch (c.Verb)
{
case DefVerb.Quantity: _qty.SetBox(QtyWorld, c.Amount); break;
case DefVerb.Split: _qty.Split(QtyWorld, c.Amount, c.Text); break;
case DefVerb.Give: _qty.Give(QtyWorld, c.Amount); break;
case DefVerb.Buy: _qty.Buy(QtyWorld, c.Amount, c.Text); break;
}
}
/// <summary>A button in the Selection window's box, with the count it showed (queued from the render thread).</summary>
private void RunQuantityClick(QtyClick click, int n)
{
if (!_identityKnown) return;
QtyAmount amount = QtyAmount.Of(n);
switch (click)
{
case QtyClick.Split: _qty.Split(QtyWorld, amount, string.Empty); break;
case QtyClick.Give: _qty.Give(QtyWorld, amount); break;
case QtyClick.Buy: _qty.Buy(QtyWorld, amount, string.Empty); break;
}
}
/// <summary>Plugin tick, ten times a second: the give target and the answer to the action in flight.</summary>
private void TickQuantity(long now)
{
if (!_inWorld || !_identityKnown || now < _nextQtyTickMs) return;
_nextQtyTickMs = now + 100;
try { _qty.Tick(QtyWorld); }
catch (System.Exception ex) { Host.Log($"[RynthDefective] quantity tick failed: {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>The Selection window's box for what is selected (null: none, or the setting is off).</summary>
private QuantityView? QuantityViewNow()
{
if (!_session.Settings.QuantityBox) return null;
try { return _qty.View(QtyWorld); }
catch (System.Exception ex)
{
Host.Log($"[RynthDefective] quantity view failed: {ex.GetType().Name}: {ex.Message}");
return null;
}
}
}

View file

@ -48,7 +48,11 @@ public sealed partial class RynthDefectivePlugin
System.Threading.Volatile.Write(ref _selectionDrawnMs, Environment.TickCount64);
try
{
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }));
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }))
{
Quantity = _qty,
QuantityAction = (click, n) => QueueBar(() => RunQuantityClick(click, n)),
};
wantHeight = _selectionWindow.Draw(_selectionView);
_selectionFailures = 0;
return 1;
@ -86,11 +90,16 @@ public sealed partial class RynthDefectivePlugin
Host.QueryHealth(sel);
}
// The quantity box (a stack, or an item in the open vendor's list).
Quantity.QuantityView? qty = QuantityViewNow();
string where = string.Empty;
float relative = float.NaN;
Items.CarriedItem? carried = null;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = it; break; }
if (carried != null) where = CarriedText(carried);
if (qty?.Subject.Mode == Quantity.QtyMode.Vendor && qty.Subject.Quote is { } quote)
where = "the vendor's" + (quote.UnitPrice > 0 ? $" · {quote.UnitPrice.ToString("N0", CultureInfo.InvariantCulture)} {quote.Currency} each" : "");
else if (carried != null) where = CarriedText(carried);
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
{
@ -106,12 +115,13 @@ public sealed partial class RynthDefectivePlugin
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
// Not carried (on the ground, in a corpse or chest): AC's own stack size.
if (carried == null && Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
if (carried == null && qty?.Subject.Mode != Quantity.QtyMode.Vendor
&& Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
where = "stack of " + stack.ToString("N0", CultureInfo.InvariantCulture) + (where.Length > 0 ? " · " + where : "");
HealthSeen? h = _health;
float health = h != null && h.Id == sel ? h.Ratio : -1f;
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0) { Qty = qty };
}
private const uint StackSizeProperty = 12; // PropertyInt.StackSize

View file

@ -63,6 +63,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
InitQuantity();
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
@ -115,6 +116,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.ResetSession();
_world?.Reset();
_qty.Reset();
}
public override void OnLogout()
@ -126,6 +128,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.LoggedIn = false;
_session.Use.ResetSession();
_world?.Reset();
_qty.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; }
@ -276,6 +279,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
case DefVerb.Status:
PrintStatus();
break;
case DefVerb.Quantity:
case DefVerb.Split:
case DefVerb.Give:
case DefVerb.Buy:
// The quantity box: each answers once, at once when it can't go, else when the game answers.
RunQuantityCommand(c);
break;
}
MarkAllForPass();
}
@ -287,6 +297,8 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
Print("RynthDefective draws the Shortcuts bar, the Game Panels buttons and the Selection window. Its settings: /rdef settings, "
+ "or the gear on the bar; right-click the bar's title to show or hide Game Panels and Selection.");
Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit.");
Print("How many of a stack or a vendor's item: the box under it in the Selection window, or /rdef qty 25, then /rdef split, /rdef give "
+ "(to the last player or NPC you selected) or /rdef buy (the selected vendor item, or /rdef buy 25 <item name>).");
}
private void PrintSlots()
@ -440,6 +452,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
TickQuantity(now);
TickCorpses(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and

View file

@ -0,0 +1,290 @@
// ============================================================================
// RynthDefective - ShortcutBar/SelectionWindow.Quantity.cs
// The quantity box under the selection (2026-10-30, Quantity/QuantityController):
// for a stack, a number with 1 / 10 / 100 / half / max, Split N into a pack
// and Give N to the last player or NPC selected; for an item in a vendor's
// list, Buy N with its price and what you have. Retail AC had this number in
// its toolbar (gone with "Hide retail toolbar"); this one is RynthDefective's.
//
// line 1 the number (typed: the game gets no keys while it has the
// keyboard) and the quick numbers
// line 2 Split N | into <pack> | Give N or Buy N | the price
// line 3 what the last action did, or what the buttons will do
//
// Render thread: draws the view the tick built. The number and the pack are
// set at once (QuantityController.Value / Into); the actions go to the tick.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>A click on one of the box's buttons.</summary>
internal enum QtyClick { Split, Give, Buy }
internal sealed partial class SelectionWindow
{
/// <summary>The box's number and pack (set from here) and its last answer; null = no box.</summary>
public QuantityController? Quantity { get; set; }
/// <summary>A Split / Give / Buy click, with the count on the button (queued to the tick).</summary>
public Action<QtyClick, int>? QuantityAction { get; set; }
private const float QRow = 18, QGap = 4, QField = 54, QChipGap = 3;
private const string IntoPopupId = "##qty_into";
private static readonly uint OkColor = Argb(0xFF73D885), BadColor = Argb(0xFFE0564E), WarnColor = Argb(0xFFE8B04A);
/// <summary>The box's height under the selection (pixels); 0 = none.</summary>
private float QuantityHeight(QuantityView? q) =>
q == null || Quantity == null ? 0f
: MathF.Ceiling(Px(QGap) + Px(QRow) + Px(QGap) + Px(QRow) + Px(QGap) + Fs(Font(RynthUiFont.Narrow9)) + Px(Pad));
private void DrawQuantity(ImDrawListPtr dl, QuantityView q, Vector2 top, float width)
{
QuantityController ctl = Quantity!;
float pad = Px(Pad), rowH = Px(QRow), gap = Px(QGap);
float left = top.X + pad, right = top.X + width - pad;
dl.AddLine(new Vector2(left, top.Y), new Vector2(right, top.Y), A(_line, 0.8f));
QtySubject s = q.Subject;
int value = ctl.Value;
float y = top.Y + gap;
// Line 1: the number and the quick numbers.
float fieldW = Math.Min(Px(QField), Math.Max(Px(30), right - left));
NumberField(ctl, new Vector2(left, y), fieldW, rowH, s);
float x = left + fieldW + Px(QChipGap + 2);
int max = s.BoxMax;
string none = s.Mode == QtyMode.Vendor ? s.Quote?.Refusal(1) ?? "You can't buy any now." : "Nothing to count.";
if (Chip(dl, "##qty_1", "1", ref x, y, rowH, right, true, "One.")) ctl.Value = 1;
if (Chip(dl, "##qty_10", "10", ref x, y, rowH, right, true, "Ten.")) ctl.Value = 10;
if (Chip(dl, "##qty_100", "100", ref x, y, rowH, right, true, "A hundred.")) ctl.Value = 100;
string halfTip = max < 1 ? none
: s.Mode == QtyMode.Vendor ? $"Half of the most you can buy now ({QuantityRules.N(QuantityRules.HalfOf(max))})."
: $"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 ? $"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);
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string of = s.Mode == QtyMode.Stack ? "of " + QuantityRules.N(s.Stack) : max >= 1 ? "up to " + QuantityRules.N(max) : string.Empty;
float ofW = of.Length > 0 ? sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, of).X : 0f;
if (of.Length > 0 && x + ofW <= right + 0.5f)
dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - ofW), MathF.Round(y + (rowH - Fs(sf)) * 0.5f)), _faint, of);
// Line 2: what the number does.
y += rowH + gap;
x = left;
if (s.Mode == QtyMode.Stack) StackButtons(dl, q, ctl, value, ref x, y, rowH, right);
else VendorButtons(dl, q, value, ref x, y, rowH, right);
// Line 3: the last answer, or what the buttons do.
y += rowH + gap;
QtyStatus? st = ctl.StatusAt(Environment.TickCount64);
string line;
uint color;
if (st != null) { line = st.Text; color = st.Ok ? OkColor : BadColor; }
else if (q.Busy) { line = "Waiting for the server..."; color = _dim; }
else Hint(q, value, out line, out color);
if (line.Length > 0)
{
ImGui.SetCursorScreenPos(new Vector2(left, y));
ImGui.InvisibleButton("##qty_line", new Vector2(Math.Max(1, right - left), Math.Max(1, Fs(sf))));
SafeImGui.SetItemTooltip(line);
Clip(dl, sf, Fs(sf), new Vector2(left, y), color, line, right - left);
}
}
private void StackButtons(ImDrawListPtr dl, QuantityView q, QuantityController ctl, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
bool reach = s.Where is QtyWhere.Carried or QtyWhere.Open;
int split = QuantityRules.SplitCount(value, s.Stack);
QtyPack? into = q.Target;
string splitTip = !q.CanSplit ? QtyReplies.NoSplitApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: !reach ? QtyReplies.NotReachable(s.Name)
: into is { Free: 0 } full ? QtyReplies.PackFull(full.Where)
: $"Split {QuantityRules.N(split)} off the stack of {QuantityRules.N(s.Stack)} into {into?.Where ?? "the main pack"}: a new stack there."
+ (value >= s.Stack ? " One always stays in the stack." : string.Empty);
bool canSplit = q.CanSplit && !q.Busy && reach;
if (Chip(dl, "##qty_split", "Split " + QuantityRules.N(split), ref x, y, h, right, canSplit, splitTip, primary: true))
QuantityAction?.Invoke(QtyClick.Split, split);
// Where the split goes.
if (into is { } t)
{
string free = t.Free >= 0 ? " · " + t.Free.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty;
string label = "into " + t.Label + free;
float before = x;
if (Chip(dl, "##qty_into_btn", label, ref x, y, h, right, q.Targets.Length > 1 && !q.Busy,
q.Targets.Length > 1 ? "Where the split goes: the main pack, a side pack or the container you have open (the number is its free slots)."
: "Where the split goes (your only pack).", textColor: t.Free == 0 ? BadColor : null, caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
if (x == before && right - x > Px(40))
{
// No room for the whole label: the pack's name cut short.
if (Chip(dl, "##qty_into_btn2", "into...", ref x, y, h, right, q.Targets.Length > 1 && !q.Busy, "Into " + t.Label + free + ".", caret: q.Targets.Length > 1))
ImGui.OpenPopup(IntoPopupId);
}
IntoMenu(q, ctl);
}
// Give to the last player or NPC selected.
int give = QuantityRules.GiveCount(value, s.Stack);
bool canGive = q.CanGive && !q.Busy && s.Where == QtyWhere.Carried && q.GiveTo != 0;
string giveTip = !q.CanGive ? QtyReplies.NoGiveApi
: q.Busy ? QtyReplies.Busy
: s.Where == QtyWhere.Wielded ? QtyReplies.Wielded(s.Name)
: s.Where != QtyWhere.Carried ? QtyReplies.NotCarried(s.Name)
: q.GiveTo == 0 ? QtyReplies.NoGiveTarget
: $"Give {QuantityRules.N(give)} {s.Name} to {q.GiveName} (the last player or NPC you selected).";
if (Chip(dl, "##qty_give", "Give " + QuantityRules.N(give), ref x, y, h, right, canGive, giveTip))
QuantityAction?.Invoke(QtyClick.Give, give);
}
private void IntoMenu(QuantityView q, QuantityController ctl)
{
if (!ImGui.IsPopupOpen(IntoPopupId)) return;
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5)));
bool open = ImGui.BeginPopup(IntoPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGui.TextDisabled("Split into");
ImGui.Separator();
for (int i = 0; i < q.Targets.Length; i++)
{
QtyPack p = q.Targets[i];
string free = p.Free < 0 ? "" : p.Free == 0 ? " (full)" : $" ({p.Free} free)";
// A menu item's label is drawn as it is (not a printf format); "##" keeps two packs of one name apart.
if (ImGui.MenuItem(p.Label + free + "##qty_into_" + i, null, i == q.TargetIndex, p.Free != 0))
ctl.Into = p.Kind == QtyPackKind.Main ? 0 : p.Id;
}
}
finally { ImGui.EndPopup(); }
}
private void VendorButtons(ImDrawListPtr dl, QuantityView q, int value, ref float x, float y, float h, float right)
{
QtySubject s = q.Subject;
VendorQuote? quote = s.Quote;
string? why = quote?.Refusal(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.");
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;
ImFontPtr sf = Font(RynthUiFont.Narrow9);
string price = quote.PriceLine(value);
Clip(dl, sf, Fs(sf), new Vector2(x + Px(2), MathF.Round(y + (h - Fs(sf)) * 0.5f)), why != null ? WarnColor : _dim, price, right - x - Px(2));
}
private void Hint(QuantityView q, int value, out string line, out uint color)
{
QtySubject s = q.Subject;
color = _faint;
if (s.Mode == QtyMode.Vendor)
{
string? why = s.Quote?.Refusal(value);
if (why != null) { line = why; color = WarnColor; 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;
}
line = s.Where switch
{
QtyWhere.Wielded => QtyReplies.Wielded(s.Name),
QtyWhere.Open => "In the open container: Split takes them into your pack.",
QtyWhere.Carried when q.GiveTo != 0 => $"Give goes to {q.GiveName}.",
QtyWhere.Carried => "Split makes a new stack. To give: select the NPC, then this.",
_ => QtyReplies.NotReachable(s.Name),
};
if (s.Where is QtyWhere.Wielded or QtyWhere.Elsewhere or QtyWhere.Unknown) color = WarnColor;
}
/// <summary>The number: typed (keys stay out of the game while it has the keyboard), 1 or more.</summary>
private void NumberField(QuantityController ctl, Vector2 p, float w, float h, QtySubject s)
{
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 size = new(w, h);
dl.AddRectFilled(p, p + size, _inset, Px(3));
ImFontPtr f = Font(RynthUiFont.Dash10);
ImGui.PushFont(f);
ImGui.SetWindowFontScale(_r);
float fs = ImGui.GetFontSize();
ImGui.PushStyleColor(ImGuiCol.FrameBg, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, 0u);
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, 0u);
ImGui.PushStyleColor(ImGuiCol.Border, 0u);
ImGui.PushStyleColor(ImGuiCol.Text, _text);
ImGui.PushStyleColor(ImGuiCol.TextSelectedBg, A(_accent, 0.45f));
ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(0f, (h - fs) * 0.5f)));
bool active, hovered;
try
{
ImGui.SetCursorScreenPos(p);
ImGui.SetNextItemWidth(w);
int v = ctl.Value;
if (ImGui.InputInt("##qty_n", ref v, 0, 0, ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal) && v >= 1)
ctl.Value = v;
active = ImGui.IsItemActive();
hovered = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(s.Mode == QtyMode.Vendor
? "How many to buy. Type it, or pick one beside it."
: "How many: Split and Give use this number. Type it, or pick one beside it.");
}
finally
{
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(6);
ImGui.SetWindowFontScale(1f);
ImGui.PopFont();
}
dl.AddRect(p, p + size, active ? _accent : hovered ? A(_accent, 0.6f) : _line, Px(3));
}
/// <summary>A small flat button at x (moved past it); left out (false) when it doesn't fit before <paramref name="right"/>.</summary>
private bool Chip(ImDrawListPtr dl, string id, string label, ref float x, float y, float h, float right, bool enabled, string tip,
bool primary = false, uint? textColor = null, bool caret = false)
{
ImFontPtr f = Font(RynthUiFont.Narrow10);
float tw = f.CalcTextSizeA(Fs(f), float.MaxValue, 0f, label).X;
float caretW = caret ? Px(9) : 0f;
float w = MathF.Ceiling(tw + caretW + Px(10));
if (x + w > right + 0.5f) return false;
Vector2 p = new(MathF.Round(x), y), size = new(w, h);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = enabled && ImGui.IsItemHovered();
if (tip.Length > 0) SafeImGui.SetItemTooltip(tip);
uint fill = primary ? A(_accent, hot ? 0.45f : 0.28f) : hot ? _key : A(_key, 0.6f);
dl.AddRectFilled(p, p + size, enabled ? fill : A(_key, 0.25f), Px(3));
dl.AddRect(p, p + size, hot ? _accent : A(_line, enabled ? 1f : 0.5f), Px(3));
uint tc = !enabled ? _faint : textColor ?? (hot || primary ? _text : _dim);
float tx = MathF.Round(p.X + (w - tw - caretW) * 0.5f);
dl.AddText(f, Fs(f), new Vector2(tx, MathF.Round(p.Y + (h - Fs(f)) * 0.5f)), tc, label);
if (caret)
{
// A small down arrow after the label.
float cx = tx + tw + Px(5), cy = p.Y + h * 0.5f, r = Px(2.5f);
dl.AddTriangleFilled(new Vector2(cx - r, cy - r * 0.5f), new Vector2(cx + r, cy - r * 0.5f), new Vector2(cx, cy + r * 0.7f), tc);
}
x += w + Px(QChipGap);
return clicked && enabled;
}
}

View file

@ -9,6 +9,8 @@
//
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
// the quantity under a stack or a vendor's item (2026-10-30): how many, and
// Split / Give / Buy that many (SelectionWindow.Quantity.cs).
//
// AC's render thread; reads the view the tick built (SelectionView).
// ============================================================================
@ -17,6 +19,7 @@ using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
@ -36,9 +39,12 @@ internal sealed record SelectionView(
uint Max)
{
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
/// <summary>The quantity box for a stack or a vendor's item; null = none.</summary>
public QuantityView? Qty { get; init; }
}
internal sealed class SelectionWindow
internal sealed partial class SelectionWindow
{
public const string Title = "Selection";
@ -90,7 +96,10 @@ internal sealed class SelectionWindow
float pad = Px(Pad), icon = Px(Icon);
float height = MathF.Ceiling(2 * pad + icon);
Vector2 max = origin + new Vector2(width, height);
// The quantity box under it (a stack, or a vendor's item): one background for both.
QuantityView? qty = v.Ready && v.Id != 0 ? v.Qty : null;
float qtyH = QuantityHeight(qty);
Vector2 max = origin + new Vector2(width, height + qtyH);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
@ -165,9 +174,11 @@ internal sealed class SelectionWindow
dl.AddText(uf, Fs(uf), new Vector2(MathF.Round(up.X + (useW - uw) * 0.5f), MathF.Round(up.Y + (Px(UseH) - Fs(uf)) * 0.5f)), hot ? _text : _dim, "USE");
if (use) _use(v.Id);
if (qty != null && qtyH > 0) DrawQuantity(dl, qty, new Vector2(origin.X, origin.Y + height), width);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
ImGui.Dummy(new Vector2(width, height + qtyH));
return height + qtyH;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>

View file

@ -51,6 +51,13 @@ internal sealed class BarSettingsView
WindowBox(w, BarTitle, "Shortcuts bar", "set.win.bar", "The item bar (/rdef). Its RynthCore bar button is the lightning bolt.");
WindowBox(w, PanelsTitle, "Game panel buttons", "set.win.panels", "Buttons for the game's own panels: pack, spellbook, map ... (/rdef panels).");
WindowBox(w, SelectionTitle, "Selection", "set.win.sel", "What is selected, how far and which way, and a creature's health (/rdef selection).");
if (WindowShown(SelectionTitle) != null)
{
w.Checkbox("Quantity box under a stack or a vendor's item", "set.qty", st.QuantityBox, v => { st.QuantityBox = v; Changed(); });
w.Tooltip("In the Selection window: how many, with 1 / 10 / 100 / half / max, then Split that many into a pack, "
+ "Give that many to the last player or NPC you selected, or Buy that many from the open vendor.\n"
+ "/rdef qty, /rdef split, /rdef give and /rdef buy do the same with it off. Kept for this character.");
}
w.SeparatorText("Shortcuts bar");
w.Checkbox("Independent of the game's toolbar", "set.indep", st.IndependentBar, v => Tell(_s.SetIndependent(v)));
@ -86,7 +93,8 @@ internal sealed class BarSettingsView
w.SeparatorText("About");
w.TextWrapped(SettingsPanel.Credit);
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, /rdef help.");
w.TextDisabled("Commands: /rdef (show or hide the bar), /rdef settings, /rdef panels, /rdef selection, /rdef weapons, /rdef use <slot or name>, "
+ "/rdef qty, /rdef split, /rdef give, /rdef buy, /rdef help.");
}
private void WindowBox(UiWindow w, string title, string label, string id, string tip)

View file

@ -48,9 +48,7 @@ public static unsafe class PluginExports
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
// No RynthPluginOnUpdateHealth (0.4.2): deaths come from the vitals the session reads each tick.
// Corpses (0.3.0): a kill a ring, wall or chain spell made without a kill notice is found by its corpse.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -16,10 +16,14 @@ namespace RynthCore.Plugin.RynthTracker;
// RynthOracle and RynthILT count the same session from the same start, and Reset starts that one
// over. Without RynthAi (or before its login) the Tracker's own session, kept running all along,
// is shown instead.
//
// Deaths (0.4.2, 2026-10-30): counted from the player's vitals and the server's death counter,
// read each tick (SessionStatsTracker). They used to wait for the player's health in
// OnUpdateHealth, which the engine never sends for the player, so the count stayed 0.
public sealed class RynthTrackerPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.1"); // previous release: 0.4.0
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.2"); // previous release: 0.4.1
private SessionStatsTracker? _session;
private readonly RynthAiSessionClient _ai = new();
@ -63,9 +67,6 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
public override void OnDeleteObject(uint objectId) => _session?.OnDeleteObject(objectId);
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> _session?.OnUpdateHealth(targetId, currentHealth, maxHealth);
public override void OnTick()
{
var session = _session;

View file

@ -27,6 +27,18 @@
// Fallback "You've banked N Luminance." counts on its own only until a
// bank property (9005 or 9102) is read; after that the property
// covers every source and the chat line would double-count.
//
// Deaths (2026-10-30), from two readings of the player each tick:
// health the engine's own vitals: 0 (with a max) after a reading above
// 0. The player's health never comes through OnUpdateHealth (that
// is a target's health), which is why the count used to stay 0.
// 0/0 (a login, before the vitals) is no reading.
// NumDeaths the server's death counter (PropertyInt 43): a rise counts,
// so a death while the plugin was unloaded (a reload) is not lost.
// A character that never died has no counter until its first death.
// ACE sends both in one packet (Player.Die: health 0, then NumDeaths), so one
// death shows on both: the first to show it counts it, the other is matched to
// it until the player reads alive again. Kill notices never count a death.
// ============================================================================
using System;
using System.Collections.Generic;
@ -146,6 +158,13 @@ internal sealed class SessionStats
private readonly List<(DateTime At, long Amount)> _recentLum = new();
private long _recentLumSum;
// Deaths (see the header): the last health reading, the NumDeaths baseline, and the death
// each reading has counted that the other one hasn't shown yet.
private bool? _alive; // null = no reading yet this session (or since a reload)
private TrackerRise _deathCountRise;
private bool _deathOpenByHealth; // counted from health 0; its NumDeaths rise hasn't come
private int _deathsOpenByCount; // counted from NumDeaths; their health 0 hasn't been read
public SessionStats() => Reset(DateTime.UtcNow);
public DateTime SessionStartUtc => _sessionStart;
@ -184,6 +203,10 @@ internal sealed class SessionStats
_movedIntoBankUntil = DateTime.MinValue;
_recentLum.Clear();
_recentLumSum = 0;
_alive = null;
_deathCountRise.Clear();
_deathOpenByHealth = false;
_deathsOpenByCount = 0;
}
// ── Events ───────────────────────────────────────────────────────────────
@ -228,8 +251,41 @@ internal sealed class SessionStats
return result;
}
/// <summary>The player's health reached 0.</summary>
public void OnPlayerDied() => _deaths++;
/// <summary>
/// The player's health from the engine's vitals. 0 after a reading above 0 is a death, unless
/// NumDeaths already counted it; max 0 (the 0/0 before a login's vitals) is no reading. Read
/// before <see cref="OnDeathCount"/> in the same tick: the server sends the health first.
/// </summary>
public void OnPlayerHealth(uint current, uint max)
{
if (max == 0) return;
bool alive = current > 0;
if (alive)
{
// Alive again (or still): whatever comes from now on is a new death.
_deathOpenByHealth = false;
_deathsOpenByCount = 0;
}
else if (_alive == true)
{
if (_deathsOpenByCount > 0) _deathsOpenByCount--;
else { _deaths++; _deathOpenByHealth = true; }
}
_alive = alive;
}
/// <summary>
/// The server's death counter (NumDeaths). Its first read is the baseline; a rise is that many
/// deaths, less the one health 0 has already counted.
/// </summary>
public void OnDeathCount(int numDeaths)
{
long up = _deathCountRise.Take(numDeaths);
if (up <= 0) return;
if (_deathOpenByHealth) { _deathOpenByHealth = false; up--; }
_deaths += (int)up;
_deathsOpenByCount += (int)up;
}
private void CountCorpseKill(DateTime now)
{
@ -378,6 +434,8 @@ internal sealed class SessionStats
s.LumOwn = _lumOwn;
s.BankIncome = _bankIncome;
s.OwnSinceBank = _ownSinceBank;
s.DeathCountBase = _deathCountRise.Baseline;
s.DeathOpen = _deathOpenByHealth;
s.RecentLum.Clear();
foreach (var (at, amount) in _recentLum) s.RecentLum.Add((at.Ticks, amount));
}
@ -405,6 +463,11 @@ internal sealed class SessionStats
_lumOwn = s.LumOwn;
_bankIncome = s.BankIncome;
_ownSinceBank = s.OwnSinceBank;
// The last health reading is not carried over: after an engine reload the vitals can read
// 0 with a max for a moment before the health is seeded, and that is no death. A death the
// reload hid comes in through NumDeaths' saved baseline instead.
_deathCountRise.Restore(s.DeathCountBase);
_deathOpenByHealth = s.DeathOpen;
foreach (var (at, amount) in s.RecentLum)
{
_recentLum.Add((new DateTime(at, DateTimeKind.Utc), amount));

View file

@ -1,9 +1,10 @@
// ============================================================================
// RynthSuite - Plugins/Shared/SessionStatsTracker.cs
// Feeds a SessionStats from the game: the player's properties every 0.5 s,
// kill notices, chat, corpses and the player's health, and keeps the session
// across plugin reloads (TrackerSessionStore). RynthTracker and RynthAi's
// Mini Remote each own one, so both show the same numbers (2026-10-11).
// kill notices, chat, corpses, and the player's health and death counter
// every tick, and keeps the session across plugin reloads
// (TrackerSessionStore). RynthTracker and RynthAi's Mini Remote each own one,
// so both show the same numbers (2026-10-11).
//
// Threading: every call except RequestReset and View runs on the pump
// thread. RequestReset only sets a flag (any thread); View is an immutable
@ -24,6 +25,8 @@ internal sealed class SessionStatsTracker
private const uint Int64RadianceEarned = 9101; // Aelrynth Bank mod session totals
private const uint Int64LuminanceBanked = 9102;
private const uint Int64LuminanceDrawn = 9103;
// The server's death counter (PropertyInt). The engine serves the player's own record to any thread.
private const uint IntNumDeaths = 43;
private const long PollIntervalMs = 500;
private static readonly TimeSpan SaveInterval = TimeSpan.FromSeconds(30);
@ -149,12 +152,9 @@ internal sealed class SessionStatsTracker
if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i);
}
/// <summary>The player's health reaching 0 is a death (maxHealth &gt; 0 skips spurious 0/0 packets at login).</summary>
public void OnUpdateHealth(uint targetId, uint currentHealth, uint maxHealth)
{
if (_active && targetId == _playerId && currentHealth == 0 && maxHealth > 0)
_stats.OnPlayerDied();
}
// Deaths are read every tick (CheckDeaths), not from OnUpdateHealth: the engine never sends the
// player's own health through it (that is a target's health: 0x01C0 and creature vitals), so the
// death count stayed 0 (2026-10-30).
// ── Tick (pump thread) ───────────────────────────────────────────────────
@ -180,6 +180,7 @@ internal sealed class SessionStatsTracker
}
if (!_active) return;
CheckDeaths();
CheckPendingCorpses(now);
long nowMs = Environment.TickCount64;
@ -211,6 +212,27 @@ internal sealed class SessionStatsTracker
private long? Read(uint stype)
=> _host.TryGetObjectQuadProperty(_playerId, stype, out long value) ? value : null;
/// <summary>
/// The player's health from the engine's vitals (the same reading RynthAi's death hold uses),
/// then the server's death counter, in the order the server sends them (SessionStats counts
/// each death once). Every tick: the health reads 0 for a few seconds only.
/// </summary>
private void CheckDeaths()
{
int before = _stats.Deaths;
if (_host.HasGetPlayerVitals
&& _host.TryGetPlayerVitals(out uint health, out uint maxHealth, out _, out _, out _, out _))
_stats.OnPlayerHealth(health, maxHealth);
if (_host.HasGetObjectIntProperty
&& _host.TryGetObjectIntProperty(_playerId, IntNumDeaths, out int numDeaths))
_stats.OnDeathCount(numDeaths);
if (_stats.Deaths != before)
{
_view = _stats.View(DateTime.UtcNow); // shown at once, not at the next poll
_host.Log($"{_tag} Death counted ({_stats.Deaths} this session).");
}
}
/// <summary>Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.</summary>
private void CheckPendingCorpses(DateTime now)
{

View file

@ -90,6 +90,12 @@ internal sealed class TrackerSessionState
public long OwnSinceBank;
/// <summary>Luminance of the last five minutes, oldest first: (UTC ticks, amount).</summary>
public List<(long AtTicks, long Amount)> RecentLum = new();
// Added 2026-10-30 (deaths from the vitals and NumDeaths). Optional in the file, like the above.
/// <summary>The server's death counter (PropertyInt 43, NumDeaths) baseline.</summary>
public long? DeathCountBase;
/// <summary>A death counted from health 0 whose NumDeaths rise hadn't been read yet.</summary>
public bool DeathOpen;
}
internal static class TrackerSessionStore
@ -152,6 +158,8 @@ internal static class TrackerSessionStore
Line(sb, "bankincome", s.BankIncome.ToString(Ic));
Line(sb, "ownsincebank", s.OwnSinceBank.ToString(Ic));
Line(sb, "recentlum", Recent(s.RecentLum));
Line(sb, "deathsbase", Opt(s.DeathCountBase));
Line(sb, "deathopen", s.DeathOpen ? "1" : "0");
Line(sb, "end", "1"); // a torn write never parses
return sb.ToString();
}
@ -204,7 +212,10 @@ internal static class TrackerSessionStore
(!map.ContainsKey("lumown") || Long(map, "lumown", out s.LumOwn)) &&
(!map.ContainsKey("bankincome") || Long(map, "bankincome", out s.BankIncome)) &&
(!map.ContainsKey("ownsincebank") || Long(map, "ownsincebank", out s.OwnSinceBank)) &&
(!map.ContainsKey("recentlum") || ParseRecent(map["recentlum"], s.RecentLum));
(!map.ContainsKey("recentlum") || ParseRecent(map["recentlum"], s.RecentLum)) &&
// The 2026-10-30 keys may be absent too.
(!map.ContainsKey("deathsbase") || OptLong(map, "deathsbase", out s.DeathCountBase)) &&
(!map.ContainsKey("deathopen") || Bool(map, "deathopen", out s.DeathOpen));
if (!ok) return false;
// Ticks outside DateTime's range would throw when the plugin builds a DateTime.

View file

@ -135,6 +135,7 @@ internal static class Program
MeleeStallTests.Register(runner);
ServerMenuTests.Register(runner);
MiniRemoteMoveTests.Register(runner);
SessionDeathTests.Register(runner);
SectionsTests.Register(runner);
ItemsCleanTests.Register(runner);
DeathRecallTests.Register(runner);
@ -146,6 +147,7 @@ internal static class Program
PluginFixTests.Register(runner);
BuffChainTests.Register(runner);
ShieldBuffTests.Register(runner);
RebuffWhenIdleTests.Register(runner);
LootPacingTests.Register(runner);
CorpseCloseTests.Register(runner);
VTankHotkeyTests.Register(runner);
@ -167,6 +169,7 @@ internal static class Program
TickIsolationTests.Register(runner);
ChoresInFightTests.Register(runner);
CommandReplyTests.Register(runner);
MonsterStatsTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -151,6 +151,8 @@ internal static class CommandReplyTests
new(null, "/ra corpseopen", K.Act),
new(null, "/ra fellow", K.Act),
new(null, "/ra fellowship leader", K.Act),
new("/ra mstats reset", "/ra mstats", K.Act), // no monster selected with stats: why, and the usage
new(null, "/ra mstats show", K.Act), // this rig's engine has no plugin windows: says so
new(null, "/ra nosuchverb", K.Act),
// ── /ra: output asked for ──
new("/ra help", null, K.Query),
@ -180,6 +182,8 @@ internal static class CommandReplyTests
new("/ra fellowinfo", null, K.Query),
new("/ra dumpinv", null, K.Query),
new("/ra combat", null, K.Query),
new("/ra mstats list", "/ra mstats Nobody Here At All", K.Query),
new("/ra mstats help", null, K.Query),
new("/ra why", null, K.Query),
new("/ra ghosts", null, K.Query),
new("/ra ghost", null, K.Query),

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot; // AcObjectClass
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
@ -71,6 +72,31 @@ internal static class HpFailsafeTests
Check.False(c.ContainsKey("Diamond Scarab"), "Diamond Scarabs never count");
Check.Eq(c.GetValueOrDefault("Mana Scarab"), 1, "a Mana Scarab counts");
Check.Eq(c.Count, 2, "only tapers and scarabs (not 'Scarab Shell Armor')");
// 2026-10-30: the "Mechanical Scarab" jewelry counted as a scarab kind, and once it had left the
// pack the macro stopped as "Mechanical Scarab 0". Only spell components count now.
var mixed = new[]
{
new WorldObject(11, "Mechanical Scarab", AcObjectClass.Jewelry),
new WorldObject(12, "Mechanical Scarab"),
new WorldObject(13, "Ornate Taper", AcObjectClass.Jewelry),
new WorldObject(14, "Lead Scarab", AcObjectClass.SpellComponent),
new WorldObject(15, "Obsidian Scarab", AcObjectClass.SpellComponent),
new WorldObject(16, "Gold Scarab"),
new WorldObject(17, "Diamond Scarab", AcObjectClass.SpellComponent),
new WorldObject(18, "Prismatic Taper", AcObjectClass.SpellComponent),
};
var m = RynthAiPlugin.CountComponents(mixed);
Check.False(m.ContainsKey("Mechanical Scarab"), "jewelry named '... Scarab' is no component, class known or not");
Check.Eq(m.GetValueOrDefault(RynthAiPlugin.TaperKey), 1, "a taper counts only as a spell component (not jewelry)");
Check.Eq(m.GetValueOrDefault("Lead Scarab"), 1, "a scarab spell component counts");
Check.Eq(m.GetValueOrDefault("Obsidian Scarab"), 1, "a spell component scarab counts whatever its kind (a server's own)");
Check.Eq(m.GetValueOrDefault("Gold Scarab"), 1, "a real scarab name counts before its class is known");
Check.False(m.ContainsKey("Diamond Scarab"), "Diamond Scarabs still never count");
Check.Eq(m.Count, 4, "tapers, Lead, Obsidian and Gold only");
var seenMixed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
RynthAiPlugin.LowComponents(m, seenMixed, 0, 1);
Check.False(seenMixed.Contains("Mechanical Scarab"), "the jewelry never becomes a kind that can run low");
}
// Drakkon, 2026-10-14: 15% health in melee among Depraved Shadows, the kit at 3% (under Kit Min

View file

@ -0,0 +1,907 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using RynthCore.Engine.UI.Sections;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Huds;
using RynthCore.Plugin.RynthAi.MonsterStats;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Monster stats (2026-10-30, a player's request: "combat statistics under individual monsters,
// evades/resists for both the player and the monster"). RynthAi counts, per kind of monster since
// login: your swings, hits and its evades (the typed combat events), your spells that reached it
// and its resists (the spell lines), kills; and the same the other way. They show under each monster
// in the Damage panel (the row's "mstats"; RynthCore's DamageRowStatsTests reads the same fields),
// and in RynthAi's own window only on an engine without that. Checked here: every line of the one
// table and the near-misses that must not count, the typed events, the counters and rates, reset,
// two monsters kept apart, the save across a hot reload, the plugin's wiring (no player's chat, no
// item's spell), their lifetime (Reset XP leaves them), the Damage rows' "mstats", the engine flag
// (tab or fallback window), /ra mstats and the window in the manifest.
internal static class MonsterStatsTests
{
public static void Register(Runner r)
{
r.Add("monster stats: every spell line of the table reads - whose spell, what became of it, the monster, the damage", SpellLinesRead);
r.Add("monster stats: near-misses don't read (own buffs, DoT ticks, heals, infusions, cloaks, the client's melee lines, a fizzle)", NearMissesDontRead);
r.Add("monster stats: the four typed combat events read their monster and damage; short bodies and other events don't", TypedEventsRead);
r.Add("monster stats: counters and rates (swings, spells, the killing blow, damage, percentages)", CountersAndRates);
r.Add("monster stats: reset starts every monster over", ResetClears);
r.Add("monster stats: two monsters are kept apart; one name in any case is one monster; found by part of a name", TwoMonstersApart);
r.Add("monster stats: the save round-trips and is restored only for the same process, character and a recent save", SaveRestoreRules);
r.Add("monster stats: the plugin counts typed events and spell lines, not a player's chat or an item's spell", PluginWiring);
r.Add("monster stats: login to logout - Reset XP leaves them, a hot reload carries them on, the resets and logout clear them", Lifetime);
r.Add("monster stats: each Damage panel row carries its monster's numbers as \"mstats\" (the engine's field names)", DamageRowsCarryStats);
r.Add("monster stats: an engine that draws them in the Damage panel gets no window or button; an older one gets both", EngineFlag);
r.Add("monster stats: /ra mstats prints a monster's numbers, lists, resets, and says why not with the usage", Command);
r.Add("monster stats: the Monster Stats window is in RynthAi's manifest and passes the engine's parser", ManifestWindow);
r.Add("monster stats: the window's view is published at login and while the window is on screen", WindowView);
}
private static readonly DateTime T0 = new(2026, 10, 30, 12, 0, 0, DateTimeKind.Utc);
// ── The table ────────────────────────────────────────────────────────
private static readonly (string Text, string Rule, bool ByYou, SpellOutcome Outcome, string Name, int Damage)[] Samples =
{
// Your spells at a monster (the log's own lines, and ACE's other forms).
("You smash Olthoi Slayer for 952 points with Incantation of Shock Wave.", "you-damage", true, SpellOutcome.Landed, "Olthoi Slayer", 952),
("Critical hit! You bash Olthoi Slasher for 1,234 points with Incantation of Shock Wave.", "you-damage", true, SpellOutcome.Landed, "Olthoi Slasher", 1234),
("Sneak Attack! You gore Olthoi Slayer for 88 points with Force Arc VII.", "you-damage", true, SpellOutcome.Landed, "Olthoi Slayer", 88),
("Critical hit! Overpower! Sneak Attack! You crush Drudge Skulker for 12 points with Force Arc VII. Your critical hit was avoided with their augmentation!",
"you-damage", true, SpellOutcome.Landed, "Drudge Skulker", 12),
("You blast The Anchor-Gorged for 153 points with Whirling Blade VII.", "you-damage", true, SpellOutcome.Landed, "The Anchor-Gorged", 153),
("With Incantation of Mana Bolt you drain 40 points of mana from Drudge Skulker.", "you-drain", true, SpellOutcome.Landed, "Drudge Skulker", 0),
("With Harm Other VI you drain 55 points of health from Drudge Skulker.", "you-drain", true, SpellOutcome.Landed, "Drudge Skulker", 55),
("You gain 52 points of health due to casting Drain Health Other I on Olthoi Warrior", "you-transfer", true, SpellOutcome.Landed, "Olthoi Warrior", 0),
("You cast Gossamer Flesh on Iron-Gorged Grievver", "you-enchant", true, SpellOutcome.Landed, "Iron-Gorged Grievver", 0),
("You cast Gossamer Flesh on Iron-Gorged Grievver, refreshing Gossamer Flesh", "you-enchant", true, SpellOutcome.Landed, "Iron-Gorged Grievver", 0),
("You cast Imperil Other VI on Drudge Skulker, surpassing Imperil Other V", "you-enchant", true, SpellOutcome.Landed, "Drudge Skulker", 0),
("You cast Imperil Other V on Drudge Skulker, but it is surpassed by Imperil Other VI", "you-enchant", true, SpellOutcome.Landed, "Drudge Skulker", 0),
("You cast Nullify All Magic Other on Drudge Skulker and dispel: Strength Self I, Armor Self I.", "you-enchant", true, SpellOutcome.Landed, "Drudge Skulker", 0),
("You cast Nullify All Magic Other on Drudge Skulker, but the dispel fails.", "you-enchant", true, SpellOutcome.Landed, "Drudge Skulker", 0),
("Frost Golem resists your spell", "you-resisted", true, SpellOutcome.Resisted, "Frost Golem", 0),
("Frost Golem resists your spell\n", "you-resisted", true, SpellOutcome.Resisted, "Frost Golem", 0),
("You fail to affect Olthoi Slayer with Surge of Affliction", "you-noeffect", true, SpellOutcome.NoEffect, "Olthoi Slayer", 0),
// A monster's spells at you.
("Iron-Gorged Grievver sparks you for 9 points with Lightning Bolt VI.", "it-damage", false, SpellOutcome.Landed, "Iron-Gorged Grievver", 9),
("Elite Threadbound Mirebound Rotlord cuts you for 20 points with Incantation of Whirling Blade.", "it-damage", false, SpellOutcome.Landed, "Elite Threadbound Mirebound Rotlord", 20),
("Critical hit! Bloodstone sears you for 1,002 points with Acidic Blood. Your augmentation allows you to avoid a critical hit!",
"it-damage", false, SpellOutcome.Landed, "Bloodstone", 1002),
("Bloodstone casts Incantation of Drain Stamina Other and drains 30 points of your stamina.", "it-drain", false, SpellOutcome.Landed, "Bloodstone", 0),
("Drudge Shaman casts Harm Other VI and drains 40 points of your health.", "it-drain", false, SpellOutcome.Landed, "Drudge Shaman", 40),
("You lose 33 points of health due to Elite Pike Grievver casting Vitality Siphon on you", "it-transfer", false, SpellOutcome.Landed, "Elite Pike Grievver", 33),
("You lose 18 points of mana due to Bloodstone casting Incantation of Drain Mana Other on you", "it-transfer", false, SpellOutcome.Landed, "Bloodstone", 0),
("Panumbris Shadow cast Weakening Curse VII on you", "it-enchant", false, SpellOutcome.Landed, "Panumbris Shadow", 0),
("Panumbris Shadow cast Festering Curse VII on you, refreshing Festering Curse VII", "it-enchant", false, SpellOutcome.Landed, "Panumbris Shadow", 0),
("Gilded Wraith cast Lure Blade on your Sharp Sword", "it-enchant", false, SpellOutcome.Landed, "Gilded Wraith", 0),
("Gilded Wraith casts Nullify All Magic Self on you and dispels: Strength Self I.", "it-dispel", false, SpellOutcome.Landed, "Gilded Wraith", 0),
("Gilded Wraith casts Nullify All Magic Self on you, but the dispel fails.", "it-dispel", false, SpellOutcome.Landed, "Gilded Wraith", 0),
("You resist the spell cast by Gilded Shade", "it-resisted", false, SpellOutcome.Resisted, "Gilded Shade", 0),
("You resist the spell cast by The Anchor-Gorged", "it-resisted", false, SpellOutcome.Resisted, "The Anchor-Gorged", 0),
("Gilded Husk fails to affect you with Lure Blade", "it-noeffect", false, SpellOutcome.NoEffect, "Gilded Husk", 0),
};
private static void SpellLinesRead()
{
var seen = new HashSet<string>();
foreach (var s in Samples)
{
bool ok = CombatLines.TryParse(s.Text, out CombatLine line);
Check.True(ok, "reads: " + s.Text);
if (!ok) continue;
seen.Add(line.Rule);
Check.Eq(line.Rule, s.Rule, "row: " + s.Text);
Check.Eq(line.ByYou, s.ByYou, "whose spell: " + s.Text);
Check.Eq(line.Outcome, s.Outcome, "outcome: " + s.Text);
Check.Eq(line.Name, s.Name, "monster: " + s.Text);
Check.Eq(line.Damage, s.Damage, "damage: " + s.Text);
Check.Eq(line.MayBeItem, s.Rule is "you-enchant" or "it-enchant" or "it-dispel", "an item may send it: " + s.Text);
}
foreach (CombatLines.Row row in CombatLines.Rows)
Check.True(seen.Contains(row.Id), "every row of the table has a sample: " + row.Id);
Check.Eq(CombatLines.Rows.Select(r => r.Id).Distinct().Count(), CombatLines.Rows.Length, "row ids are unique");
Check.Eq(CombatLines.ParseAmount("1,234"), 1234, "thousands");
Check.Eq(CombatLines.ParseAmount("2000000"), 0, "past a million: not a hit");
}
private static readonly string?[] NearMisses =
{
null, "", " ",
"You cast Executor's Blessing on yourself, refreshing Executor's Blessing", // your own buff
"You cast Meditative Trance on yourself and lose 10 points of stamina and also gain 12 points of mana",
"Some Guy tried and failed to cast a spell at you!", // a fizzle: it never reached you
"You smash Drudge Skulker for 15 points of periodic nether damage!", // a DoT tick, not a cast
"You receive 18 points of periodic nether damage.",
"With Heal Other VI you restore 80 points of health to Drudge Skulker.", // heals
"Drudge Shaman casts Heal Other VI and restores 40 points of your health.",
"You lose 22 points of mana due to casting Incantation of Infuse Mana Other on High-Voltage VI", // an infusion you cast
"You gain 22 points of health due to Drudge Shaman casting Drain Health Other on you", // a gift to you
"Your cloak reduced the damage from 300 down to 150!", // cloaks (player gear)
"The cloak of Drudge Skulker reduced the damage from 300 down to 150!",
"Drudge Skulker evaded your attack.", // the client's lines for the typed events
"You evaded Drudge Skulker!",
"You slash Drudge Skulker for 12 points of slashing damage!",
"Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!",
"Drudge Skulker bites you for 12 points of piercing damage!",
"Drudge Skulker resists your spell!", // not the server's exact line
"Frost Golem resists your spell and more",
"Bob says, \"Drudge Skulker resists your spell\"", // a player's copy
"Tester tells you, \"Gilded Shade cast Weakening Curse VII on you\"",
"resists your spell", // no monster
"You resist the spell cast by ",
"Aetheria surges on Drudge Skulker with the power of Surge of Affliction!",
"You killed Drudge Skulker!",
"You fail to heal yourself. Your Greater Stamina Kit has 10 uses left.",
"You cast Strength Self VI on you",
"You fail to affect yourself with Lure Blade",
"You smash Drudge Skulker for 12 points with Force Arc VII", // no full stop: not the server's line
};
private static void NearMissesDontRead()
{
foreach (string? text in NearMisses)
{
bool read = CombatLines.TryParse(text, out CombatLine line);
Check.False(read, $"not counted: '{text ?? "null"}'" + (read ? $" (read as {line.Rule} '{line.Name}')" : ""));
}
// An item casts the same line a monster does: it reads, marked as one an item may send (the plugin checks).
Check.True(CombatLines.TryParse("Frost Hand Wraps cast Aura of Infected Caress on you, refreshing Aura of Infected Caress", out CombatLine item)
&& item.MayBeItem && item.Name == "Frost Hand Wraps", "an item's line reads, marked MayBeItem");
Check.True(CombatLines.TryParse("You cast Tusker's Bane on Yoroi Greaves, refreshing Tusker's Bane", out CombatLine own)
&& own.MayBeItem && own.ByYou, "a spell on your own armour reads, marked MayBeItem");
}
// ── Typed events ─────────────────────────────────────────────────────
/// <summary>AC's 16-bit-length string: u16 length, the bytes, zero padding to a multiple of 4 (with the length).</summary>
private static byte[] Str16(string s)
{
byte[] b = Encoding.Latin1.GetBytes(s);
var o = new List<byte> { (byte)(b.Length & 0xFF), (byte)(b.Length >> 8) };
o.AddRange(b);
while (o.Count % 4 != 0) o.Add(0);
return o.ToArray();
}
private static byte[] Cat(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
private static byte[] U32(uint v) => BitConverter.GetBytes(v);
private static byte[] F64(double v) => BitConverter.GetBytes(v);
private static byte[] U64(ulong v) => BitConverter.GetBytes(v);
internal static byte[] AttackerBody(string name, uint damage) =>
Cat(Str16(name), U32(4), F64(0.25), U32(damage), U32(1), U64(0));
internal static byte[] DefenderBody(string name, uint damage) =>
Cat(Str16(name), U32(1), F64(0.1), U32(damage), U32(3), U32(0), U64(0));
internal static byte[] NameBody(string name) => Str16(name);
private static void TypedEventsRead()
{
Check.True(CombatEvents.TryParse(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 37), out var k, out string n, out int d)
&& k == PhysicalEvent.YouHit && n == "Drudge Skulker" && d == 37, "0x01B1: you hit it, for 37");
Check.True(CombatEvents.TryParse(CombatEvents.DefenderNotification, DefenderBody("Gilded Shade", 12), out k, out n, out d)
&& k == PhysicalEvent.ItHit && n == "Gilded Shade" && d == 12, "0x01B2: it hit you (a padded name), for 12");
Check.True(CombatEvents.TryParse(CombatEvents.EvasionAttackerNotification, NameBody("Olthoi Slayer"), out k, out n, out d)
&& k == PhysicalEvent.ItEvaded && n == "Olthoi Slayer" && d == 0, "0x01B3: it evaded your attack");
Check.True(CombatEvents.TryParse(CombatEvents.EvasionDefenderNotification, NameBody("Olthoi Slayer"), out k, out n, out d)
&& k == PhysicalEvent.YouEvaded && n == "Olthoi Slayer", "0x01B4: you evaded its attack");
byte[] full = AttackerBody("Drudge Skulker", 37);
Check.False(CombatEvents.TryParse(CombatEvents.AttackerNotification, full.AsSpan(0, full.Length - 16), out _, out _, out _),
"a hit without its damage doesn't read");
Check.False(CombatEvents.TryParse(CombatEvents.EvasionAttackerNotification, new byte[] { 40, 0, 65, 66 }, out _, out _, out _),
"a name longer than the body doesn't read");
Check.False(CombatEvents.TryParse(CombatEvents.EvasionAttackerNotification, NameBody(""), out _, out _, out _), "no name");
Check.False(CombatEvents.TryParse(0x01AD, NameBody("You killed Drudge Skulker!"), out _, out _, out _), "a kill notice isn't a combat event");
Check.True(CombatEvents.GameEvents.All(CombatEvents.IsCombatEvent) && CombatEvents.GameEvents.Length == 4, "the four asked for");
Check.False(CombatEvents.IsCombatEvent(0x02EB), "transient text isn't one");
}
// ── Counters ─────────────────────────────────────────────────────────
private static CombatLine Line(string text)
{
if (!CombatLines.TryParse(text, out CombatLine l)) throw new InvalidOperationException("sample didn't read: " + text);
return l;
}
private static void CountersAndRates()
{
var s = new MonsterCombatStats();
const string D = "Drudge Skulker";
for (int i = 0; i < 3; i++) s.OnPhysical(PhysicalEvent.YouHit, D, 30, T0);
s.OnPhysical(PhysicalEvent.ItEvaded, D, 0, T0);
s.OnSpell(Line("You blast Drudge Skulker for 100 points with Force Bolt VI."), T0);
s.OnSpell(Line("You cast Imperil Other VI on Drudge Skulker"), T0);
s.OnSpell(Line("Drudge Skulker resists your spell"), T0);
s.OnSpell(Line("You fail to affect Drudge Skulker with Surge of Affliction"), T0);
s.OnPhysical(PhysicalEvent.ItHit, D, 12, T0);
for (int i = 0; i < 3; i++) s.OnPhysical(PhysicalEvent.YouEvaded, D, 0, T0);
s.OnSpell(Line("Drudge Skulker zaps you for 9 points with Shock Wave II."), T0);
s.OnSpell(Line("You resist the spell cast by Drudge Skulker"), T0);
MonsterStatsRow r = s.Get(D)!;
Check.Eq((r.Hits, r.Evaded, r.Swings), (3, 1, 4), "your attacks: 3 hit, 1 evaded, 4 swings");
Check.Eq(MonsterCombatStats.Percent(r.ItEvadesRate), "25%", "it evades 25%");
Check.Eq((r.SpellsLanded, r.Resisted, r.NoEffect, r.SpellsAtIt), (2, 1, 1, 4), "your spells: 2 landed, 1 resisted, 1 no effect");
Check.Eq(MonsterCombatStats.Percent(r.ItResistsRate), "25%", "it resists 25% (of the 4 that reached it)");
Check.Eq((r.HitsTaken, r.YouEvaded, r.Attacks), (1, 3, 4), "its attacks: 1 hit, 3 evaded");
Check.Eq(MonsterCombatStats.Percent(r.YouEvadeRate), "75%", "you evade 75%");
Check.Eq((r.SpellsTaken, r.YouResisted, r.SpellsAtYou), (1, 1, 2), "its spells: 1 landed, 1 resisted");
Check.Eq(MonsterCombatStats.Percent(r.YouResistRate), "50%", "you resist 50%");
Check.Eq((r.DamageDealt, r.DamageTaken), (190L, 21L), "damage: 3 x 30 + 100 dealt, 12 + 9 taken");
Check.Eq(r.Kills, 0, "no kill yet");
// The killing blow sends no hit: the kill notice counts it, by the combat mode it was struck in.
Check.Eq(s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0), D, "a melee kill names the monster");
r = s.Get(D)!;
Check.Eq((r.Kills, r.Hits, r.Swings), (1, 4, 5), "a melee kill: a kill and a hit");
Check.Eq(MonsterCombatStats.Percent(r.ItEvadesRate), "20%", "it evades 1 of 5 now");
s.OnKill("Drudge Skulker died!", KillBlow.Spell, T0);
r = s.Get(D)!;
Check.Eq((r.Kills, r.SpellsLanded), (2, 3), "a magic kill: a kill and a landed spell");
s.OnKill("The thunder of crushing Drudge Skulker is followed by the deafening silence of death!", KillBlow.None, T0);
r = s.Get(D)!;
Check.Eq((r.Kills, r.Hits, r.SpellsLanded), (3, 4, 3), "in peace mode: a kill, no blow");
// The notice names a monster with no numbers yet: the plugin's look around, only when the notice has the name.
Check.Null(s.OnKill("You killed Banderling Scout!", KillBlow.Physical, T0), "no numbers and no look around: not credited");
Check.Eq(s.OnKill("You killed Banderling Scout!", KillBlow.Physical, T0, _ => "Banderling Scout"), "Banderling Scout", "found around");
Check.Eq(s.Get("Banderling Scout")!.Kills, 1, "a kill for it");
Check.Null(s.OnKill("You killed Mosswart!", KillBlow.Physical, T0, _ => "Drudge Shaman"), "a name the notice doesn't have isn't credited");
Check.Null(s.OnKill("", KillBlow.Physical, T0), "an empty notice");
// The longest name the notice has: Drudge Skulker, not Drudge.
s.OnPhysical(PhysicalEvent.YouHit, "Drudge", 5, T0);
Check.Eq(s.OnKill("You flatten Drudge Skulker's body with the force of your assault!", KillBlow.Physical, T0), D, "the longest name wins");
// Percentages.
Check.Eq(MonsterCombatStats.Percent(null), "-", "nothing to divide by");
Check.Eq(MonsterCombatStats.Percent(0), "0%", "0%");
Check.Eq(MonsterCombatStats.Percent(1), "100%", "100%");
Check.Eq(MonsterCombatStats.Percent(0.125), "13%", "whole numbers from 10%");
Check.Eq(MonsterCombatStats.Percent(1 / 3.0), "33%", "a third");
Check.Eq(MonsterCombatStats.Percent(2 / 3.0), "67%", "two thirds");
Check.Eq(MonsterCombatStats.Percent(0.045), "4.5%", "one decimal below 10%");
Check.Eq(MonsterCombatStats.Percent(0.0049), "0.5%", "rounded");
Check.Eq(MonsterCombatStats.Percent(0.0999), "10%", "9.99 rounds to 10");
Check.Eq(MonsterCombatStats.Percent(double.NaN), "-", "not a number");
Check.Eq(MonsterCombatStats.Percent(1.7), "100%", "clamped");
Check.Null(MonsterCombatStats.Rate(1, 0), "a share of nothing");
// The words.
string[] chat = MonsterStatsText.ChatLines(s.Get(D)!);
Check.Eq(chat.Length, 3, "three chat lines");
Check.True(chat[0].Contains("Drudge Skulker since login") && chat[0].Contains("4 kills"), "title: " + chat[0]);
Check.True(chat[1].Contains("6 swings, 5 hit, it evaded 1 (17%)") && chat[1].Contains("it resisted 1 (20%)") && chat[1].Contains("1 no effect"),
"your side: " + chat[1]);
Check.True(chat[2].Contains("4 attacks, 1 hit, you evaded 3 (75%)") && chat[2].Contains("you resisted 1 (50%)") && chat[2].Contains("21 damage"),
"its side: " + chat[2]);
var detail = MonsterStatsText.DetailRows(s.Get(D)!);
Check.True(detail.Any(d => d.Label == "No effect"), "the detail shows no effect when there is some");
Check.False(MonsterStatsText.DetailRows(s.Get("Banderling Scout")!).Any(d => d.Label == "No effect"), "and leaves it out when there is none");
int v = s.Version;
s.OnPhysical(PhysicalEvent.YouHit, D, 1, T0);
Check.True(s.Version > v, "a change moves the version");
}
private static void ResetClears()
{
var s = new MonsterCombatStats();
s.OnPhysical(PhysicalEvent.YouHit, "Drudge Skulker", 30, T0);
s.OnSpell(Line("Mosswart Worshipper resists your spell"), T0);
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0);
Check.Eq(s.Count, 2, "two monsters before");
int v = s.Version;
s.Reset();
Check.Eq(s.Count, 0, "none after");
Check.Eq(s.Snapshot().Length, 0, "an empty list");
Check.Null(s.Get("Drudge Skulker"), "its numbers are gone");
Check.False(s.IsTracked("Mosswart Worshipper"), "not tracked");
Check.True(s.Version > v, "the window sees the change");
s.OnPhysical(PhysicalEvent.ItEvaded, "Drudge Skulker", 0, T0.AddSeconds(5));
MonsterStatsRow r = s.Get("Drudge Skulker")!;
Check.Eq((r.Hits, r.Evaded, r.Kills), (0, 1, 0), "counting starts from zero");
Check.Eq(r.FirstUtcTicks, T0.AddSeconds(5).Ticks, "first seen anew");
}
private static void TwoMonstersApart()
{
var s = new MonsterCombatStats();
const string A = "Drudge Skulker", B = "Mosswart Worshipper";
s.OnPhysical(PhysicalEvent.YouHit, A, 10, T0);
s.OnPhysical(PhysicalEvent.ItEvaded, B, 0, T0.AddSeconds(1));
s.OnSpell(Line("Drudge Skulker resists your spell"), T0.AddSeconds(2));
s.OnSpell(Line("Mosswart Worshipper blasts you for 20 points with Flame Bolt II."), T0.AddSeconds(3));
s.OnPhysical(PhysicalEvent.YouEvaded, "drudge skulker", 0, T0.AddSeconds(4)); // one monster in any case
s.OnKill("You killed Mosswart Worshipper!", KillBlow.Spell, T0.AddSeconds(5));
Check.Eq(s.Count, 2, "two monsters, not three");
MonsterStatsRow a = s.Get(A)!, b = s.Get(B)!;
Check.Eq((a.Hits, a.Evaded, a.Resisted, a.YouEvaded, a.SpellsTaken, a.Kills, a.DamageDealt), (1, 0, 1, 1, 0, 0, 10L), "Drudge's numbers are its own");
Check.Eq((b.Hits, b.Evaded, b.Resisted, b.YouEvaded, b.SpellsTaken, b.Kills, b.SpellsLanded, b.DamageTaken), (0, 1, 0, 0, 1, 1, 1, 20L),
"Mosswart's numbers are its own");
Check.Eq(a.Name, A, "the name as first seen");
Check.Eq(s.Snapshot()[0].Name, B, "the most recently fought first");
Check.Eq(s.Find("drudge skulker", out _)!.Name, A, "found by its name in any case");
Check.Eq(s.Find("moss", out _)!.Name, B, "found by part of its name");
s.OnPhysical(PhysicalEvent.YouHit, "Drudge Ravener", 1, T0.AddSeconds(6));
Check.Null(s.Find("Drudge", out List<string> many), "two Drudges: not one");
Check.True(many.Count == 2 && many.Contains(A) && many.Contains("Drudge Ravener"), "both named: " + string.Join(", ", many));
s.OnPhysical(PhysicalEvent.YouHit, "Drudge", 1, T0.AddSeconds(7));
Check.Eq(s.Find("Drudge", out _)!.Name, "Drudge", "an exact name wins over the names it is part of");
Check.Null(s.Find("Banderling", out List<string> none), "nothing");
Check.Eq(none.Count, 0, "and no candidates");
// Past the cap the one fought longest ago goes.
var cap = new MonsterCombatStats();
for (int i = 0; i <= MonsterCombatStats.MaxMonsters; i++)
cap.OnPhysical(PhysicalEvent.YouHit, "Monster " + i, 1, T0.AddSeconds(i));
Check.Eq(cap.Count, MonsterCombatStats.MaxMonsters, "kept to the cap");
Check.False(cap.IsTracked("Monster 0"), "the oldest went");
Check.True(cap.IsTracked("Monster " + MonsterCombatStats.MaxMonsters), "the newest is there");
}
// ── Saving ───────────────────────────────────────────────────────────
private static MonsterStatsSave SampleSave(DateTime saved, DateTime start)
{
var s = new MonsterCombatStats();
s.OnPhysical(PhysicalEvent.YouHit, "Drudge Skulker", 30, start.AddMinutes(1));
s.OnPhysical(PhysicalEvent.ItEvaded, "Drudge Skulker", 0, start.AddMinutes(1));
s.OnSpell(Line("You fail to affect Gilded Husk with Lure Blade"), start.AddMinutes(2));
s.OnPhysical(PhysicalEvent.ItHit, "Bad\tName", 5, start.AddMinutes(3));
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, start.AddMinutes(4));
return new MonsterStatsSave
{
ProcessId = 1234, ProcessStartUtcTicks = 5555, CharacterId = 0x50000001,
SavedUtcTicks = saved.Ticks, SinceUtcTicks = start.Ticks,
Rows = s.Snapshot().ToList(),
};
}
private static void SaveRestoreRules()
{
DateTime start = T0, saved = T0.AddMinutes(30);
MonsterStatsSave save = SampleSave(saved, start);
string text = MonsterStatsStore.Serialize(save);
Check.True(MonsterStatsStore.TryParse(text, out MonsterStatsSave back), "parses");
Check.Eq((back.ProcessId, back.ProcessStartUtcTicks, back.CharacterId, back.SavedUtcTicks, back.SinceUtcTicks),
(1234, 5555L, 0x50000001u, saved.Ticks, start.Ticks), "the header fields");
Check.Eq(back.Rows.Count, 3, "three monsters");
foreach (MonsterStatsRow r in save.Rows)
{
string name = r.Name.Replace('\t', ' ');
Check.Eq(back.Rows.Single(x => x.Name == name), r with { Name = name }, "round-trips: " + name);
}
Check.True(MonsterStatsStore.TryParse(text.Replace("\n", "\r\n"), out _), "Windows line breaks too");
DateTime soon = saved.AddMinutes(1);
Check.True(MonsterStatsStore.ShouldRestore(back, 1234, 5555, 0x50000001, soon), "same process, character, recent: restored");
Check.False(MonsterStatsStore.ShouldRestore(back, 4321, 5555, 0x50000001, soon), "another process");
Check.False(MonsterStatsStore.ShouldRestore(back, 1234, 6666, 0x50000001, soon), "a new client with a reused process id");
Check.False(MonsterStatsStore.ShouldRestore(back, 1234, 5555, 0x50000002, soon), "another character");
Check.False(MonsterStatsStore.ShouldRestore(back, 1234, 5555, 0, soon), "no character");
Check.False(MonsterStatsStore.ShouldRestore(back, 1234, 5555, 0x50000001, saved.AddMinutes(11)), "too old");
Check.False(MonsterStatsStore.ShouldRestore(back, 1234, 5555, 0x50000001, saved.AddMinutes(-2)), "from the future");
var odd = SampleSave(saved, saved.AddMinutes(1));
Check.False(MonsterStatsStore.ShouldRestore(odd, 1234, 5555, 0x50000001, soon), "started after it was saved: not a real save");
string noEnd = text.Replace("end=1\n", "");
Check.False(MonsterStatsStore.TryParse(noEnd, out _), "a torn write (no end marker)");
Check.False(MonsterStatsStore.TryParse(text.Replace(MonsterStatsStore.Header, "RynthAi monster stats v0"), out _), "another header");
Check.False(MonsterStatsStore.TryParse(text.Replace("m=Drudge Skulker\t", "m=Drudge Skulker\tx"), out _), "a number that isn't one");
Check.False(MonsterStatsStore.TryParse(text.Replace("pid=1234\n", "pid=1234\nm=Short\t1\t2\n"), out _), "a row too short");
Check.False(MonsterStatsStore.TryParse(text.Replace("pid=1234\n", "pid=1234\nnoequals\n"), out _), "a line without '='");
Check.False(MonsterStatsStore.TryParse(null, out _), "nothing");
// The files: save, load, delete, cleanup (a temp folder, never %LOCALAPPDATA%).
string dir = Path.Combine(Program.TempRoot, "monster-stats-" + Guid.NewGuid().ToString("N"));
try
{
MonsterStatsStore.Save(dir, save);
Check.True(File.Exists(Path.Combine(dir, MonsterStatsStore.FileName(1234, 0x50000001))), "saved as " + MonsterStatsStore.FileName(1234, 0x50000001));
Check.True(MonsterStatsStore.TryLoad(dir, 1234, 0x50000001, out MonsterStatsSave loaded) && loaded.Rows.Count == 3, "loads");
Check.False(MonsterStatsStore.TryLoad(dir, 1234, 0x50000002, out _), "another character's file isn't there");
var other = SampleSave(saved, start);
other.ProcessId = 999;
MonsterStatsStore.Save(dir, other);
var old = SampleSave(saved, start);
old.ProcessId = 777;
MonsterStatsStore.Save(dir, old);
File.SetLastWriteTimeUtc(Path.Combine(dir, MonsterStatsStore.FileName(777, 0x50000001)), DateTime.UtcNow.AddDays(-2));
File.WriteAllText(Path.Combine(dir, "session-1234-50000001.txt"), "not ours");
int removed = MonsterStatsStore.Cleanup(dir, 1234, DateTime.UtcNow);
Check.Eq(removed, 2, "this process's save and a closed client's old one");
Check.True(File.Exists(Path.Combine(dir, MonsterStatsStore.FileName(999, 0x50000001))), "another running client's stays");
Check.True(File.Exists(Path.Combine(dir, "session-1234-50000001.txt")), "files that aren't monster stats stay");
MonsterStatsStore.Delete(dir, 999, 0x50000001);
Check.False(File.Exists(Path.Combine(dir, MonsterStatsStore.FileName(999, 0x50000001))), "deleted");
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch { }
}
}
// ── The plugin ───────────────────────────────────────────────────────
private const uint Player = 0x50000E31, Drudge = 0x80000E01, Mosswart = 0x80000E02;
private const uint Fellow = 0x50000E99; // another player nearby (the cache files it as a creature)
private const uint Lb = 0xA9B40000;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
// ── A fake engine's plugin windows (v89) and UI flags (v77), for the tab / fallback choice ──
private static uint _uiFlags;
private static readonly List<(string Key, int Mode)> PanelCalls = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint FakeUiFlags() => _uiFlags;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe int FakeScreenMode(int* previous) { if (previous != null) *previous = 0; return 0x10000008; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint FakeUiColor(int token) => 0xFFFFFFFF;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr FakeUiFont(int font) => IntPtr.Zero;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe int FakeSetPanelOpen(byte* key, int mode)
{
PanelCalls.Add((Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode));
return mode == 0 ? 0 : 1;
}
/// <summary>An engine with plugin windows and UI flags <paramref name="flags"/> (bit 8: its Damage panel draws "mstats").</summary>
private static unsafe void PluginWindowsEngine(ref RynthCoreApiNative api, uint flags)
{
_uiFlags = flags;
api.GetUiHookFlagsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&FakeUiFlags;
api.GetScreenModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, int>)&FakeScreenMode;
api.GetUiColorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint>)&FakeUiColor;
api.GetUiFontFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, IntPtr>)&FakeUiFont;
api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&FakeSetPanelOpen;
}
/// <summary>A logged-in RynthAi on the fakes with two monsters around, its save in a temp folder.
/// <paramref name="uiFlags"/> set: an engine with plugin windows and those UI flags.</summary>
private sealed class Rig
{
public readonly RynthAiPlugin P = new();
public readonly RynthCoreHost Host;
public Rig(string saveDir, uint? uiFlags = null)
{
FakeHost.Reset();
PanelCalls.Clear();
if (uiFlags is uint flags) FakeHost.ConfigureApi = (ref RynthCoreApiNative api) => PluginWindowsEngine(ref api, flags);
FakeHost.Names[Player] = "Tester";
FakeHost.PlayerIdValue = Player;
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
foreach (var (id, name, y, wcid) in new[] { (Drudge, "Drudge Skulker", 99f, 0x1F01u), (Mosswart, "Mosswart Worshipper", 101f, 0x1F02u), (Fellow, "Some Fellow", 97f, 1u) })
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, 96f, y, 0f);
FakeHost.ItemTypes[id] = 0x10; // a creature
FakeHost.Wcids[id] = wcid;
}
Host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var cache = new WorldObjectCache(Host);
cache.SetPlayerId(Player);
foreach (uint id in new[] { Drudge, Mosswart, Fellow }) _ = cache[unchecked((int)id)];
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_initialized", true);
Set("_loginComplete", true);
P.MonsterStatsDirectory = saveDir;
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
public object? Call(string method, params object?[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args);
public MonsterCombatStats Stats => P.MonsterStatsForTests;
public void Chat(string text, int chatType = 7) { int eat = 0; P.OnChatWindowText(text, chatType, ref eat); }
/// <summary>A line typed in the chat bar; the chat lines it wrote.</summary>
public List<(string Text, int Type)> Typed(string line)
{
int before = FakeHost.Chat.Count;
int eat = 0;
P.OnChatBarEnter(line, ref eat);
var lines = new List<(string, int)>();
for (int i = before; i < FakeHost.Chat.Count; i++)
lines.Add((FakeHost.Chat[i], i < FakeHost.ChatTypes.Count ? FakeHost.ChatTypes[i] : -1));
return lines;
}
/// <summary>The Mini Remote's session, started (as at login), saved in <paramref name="dir"/>.</summary>
public SessionStatsTracker StartSession(string dir)
{
var t = new SessionStatsTracker(Host, "[test]", dir);
t.OnLoginComplete();
Set("_sessionStats", t);
return t;
}
/// <summary>The Damage panel's rows (RynthPluginGetMonsterDamageJson), by name, the Default line left out.</summary>
public Dictionary<string, JsonElement> DamageRows(string storeDir)
{
if (Get("_damageStore") == null)
{
var store = new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore();
Directory.CreateDirectory(storeDir);
store.SetCharacter(storeDir);
Set("_damageStore", store);
Set("_creatureStore", new RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore());
}
using var doc = JsonDocument.Parse(P.BuildMonsterDamageJson());
var rows = new Dictionary<string, JsonElement>();
foreach (JsonElement e in doc.RootElement.EnumerateArray())
if (!(e.TryGetProperty("isDefault", out var d) && d.GetBoolean())) rows[e.GetProperty("name").GetString()!] = e.Clone();
return rows;
}
}
private static string TempDir(string what) => Path.Combine(Program.TempRoot, what + "-" + Guid.NewGuid().ToString("N"));
private static void PluginWiring()
{
string dir = TempDir("ms-wiring");
var rig = new Rig(dir);
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30));
rig.P.NoteCombatEvent(CombatEvents.EvasionAttackerNotification, NameBody("Drudge Skulker"));
rig.P.NoteCombatEvent(CombatEvents.DefenderNotification, DefenderBody("Drudge Skulker", 8));
rig.P.NoteCombatEvent(CombatEvents.EvasionDefenderNotification, NameBody("Drudge Skulker"));
MonsterStatsRow d = rig.Stats.Get("Drudge Skulker")!;
Check.Eq((d.Hits, d.Evaded, d.HitsTaken, d.YouEvaded, d.DamageDealt, d.DamageTaken), (1, 1, 1, 1, 30L, 8L), "the four typed events, through the plugin");
rig.Chat("Drudge Skulker resists your spell");
rig.Chat("You resist the spell cast by Drudge Skulker");
d = rig.Stats.Get("Drudge Skulker")!;
Check.Eq((d.Resisted, d.YouResisted), (1, 1), "the spell lines, through OnChatWindowText");
rig.Chat("Drudge Skulker resists your spell", ChatSource.Speech);
rig.Chat("You resist the spell cast by Drudge Skulker", ChatSource.Tell);
d = rig.Stats.Get("Drudge Skulker")!;
Check.Eq((d.Resisted, d.YouResisted), (1, 1), "a player's chat types don't count");
rig.Chat("Frost Hand Wraps cast Aura of Infected Caress on you, refreshing Aura of Infected Caress");
rig.Chat("You cast Tusker's Bane on Yoroi Greaves, refreshing Tusker's Bane");
Check.False(rig.Stats.IsTracked("Frost Hand Wraps") || rig.Stats.IsTracked("Yoroi Greaves"), "an item's spell, or one on an item, isn't a monster's");
rig.Chat("Mosswart Worshipper cast Weakening Curse VII on you");
Check.Eq(rig.Stats.Get("Mosswart Worshipper")?.SpellsTaken, 1, "a creature around casting on you counts");
rig.Chat("Gilded Wraith cast Weakening Curse VII on you");
Check.False(rig.Stats.IsTracked("Gilded Wraith"), "a name neither around nor fought isn't counted for an enchantment line");
rig.P.NoteCombatEvent(CombatEvents.DefenderNotification, DefenderBody("Gilded Wraith", 4));
rig.Chat("Gilded Wraith cast Weakening Curse VII on you");
Check.Eq(rig.Stats.Get("Gilded Wraith")?.SpellsTaken, 1, "once fought (out of sight), its enchantment counts");
// Another player: buffing each other, a spar. Never a monster, even filed as a creature.
rig.Chat("You cast Strength Other VI on Some Fellow");
rig.Chat("Some Fellow cast Strength Other VI on you, refreshing Strength Other VI");
rig.Chat("Some Fellow resists your spell");
rig.Chat("You resist the spell cast by Some Fellow");
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Some Fellow", 9));
rig.P.NoteCombatEvent(CombatEvents.EvasionDefenderNotification, NameBody("Some Fellow"));
Check.False(rig.Stats.IsTracked("Some Fellow"), "a player's lines and events don't count");
rig.Set("_currentTargetId", Fellow);
Check.Eq((string)rig.Call("MonsterStatsFocusName")!, "", "a selected player isn't the monster in focus");
rig.Set("_currentTargetId", 0u);
rig.Set("_currentCombatMode", CombatMode.Melee);
rig.Call("NoteMonsterStatsKill", "You killed Drudge Skulker!");
d = rig.Stats.Get("Drudge Skulker")!;
Check.Eq((d.Kills, d.Hits), (1, 2), "a melee kill: the killing blow is a hit");
rig.Set("_currentCombatMode", CombatMode.Magic);
rig.Call("NoteMonsterStatsKill", "Mosswart Worshipper died!");
MonsterStatsRow m = rig.Stats.Get("Mosswart Worshipper")!;
Check.Eq((m.Kills, m.SpellsLanded), (1, 1), "a magic kill: a landed spell");
rig.Set("_loginComplete", false);
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30));
rig.Chat("Drudge Skulker resists your spell");
d = rig.Stats.Get("Drudge Skulker")!;
Check.Eq((d.Hits, d.Resisted), (2, 1), "nothing counts out of the world");
try { Directory.Delete(dir, true); } catch { }
}
private static void Lifetime()
{
string saveDir = TempDir("ms-save"), sessionDir = TempDir("ms-session");
try
{
// Login: the first tick with the character known starts the counting.
var rig = new Rig(saveDir);
SessionStatsTracker session = rig.StartSession(sessionDir);
Check.False((bool)rig.Get("_monsterStatsStarted")!, "not started before the first tick");
rig.Call("TickMonsterStats");
Check.True((bool)rig.Get("_monsterStatsStarted")!, "started on the login's first tick");
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30));
rig.P.NoteCombatEvent(CombatEvents.EvasionAttackerNotification, NameBody("Drudge Skulker"));
// Reset XP (the Mini Remote session's reset, which RynthTracker's reset also runs) leaves them.
Thread.Sleep(20);
long before = session.View.SessionStartUtc.Ticks;
session.RequestReset();
session.Tick();
Check.True(session.View.SessionStartUtc.Ticks != before, "the session started over");
rig.Call("TickMonsterStats");
MonsterStatsRow? d = rig.Stats.Get("Drudge Skulker");
Check.True(d != null && d.Hits == 1 && d.Evaded == 1, "Reset XP leaves the monster stats");
// A hot reload: the copy going saves, the next brings them back.
rig.Call("ShutdownMonsterStats");
Check.True(File.Exists(Path.Combine(saveDir, MonsterStatsStore.FileName(Environment.ProcessId, Player))), "saved at unload");
var next = new Rig(saveDir);
Check.Eq(next.Stats.Count, 0, "the new copy starts empty");
next.Call("TickMonsterStats");
d = next.Stats.Get("Drudge Skulker");
Check.True(d != null && d.Hits == 1 && d.Evaded == 1, "the stats carried over");
Check.True(FakeHost.Logs.Any(l => l.Contains("Monster stats carried over")), "and the log says so");
Check.True(next.Stats.Count == 1, "only what was saved");
// The resets that do clear them: /ra mstats reset (CommandTest), the window's, the Damage panel's Reset stats.
next.P.ClearMonsterStats(); // the Damage panel's Reset stats (RynthPluginClearMonsterStats)
Check.Eq(next.Stats.Count, 1, "the panel's reset is done on the tick");
next.Call("TickMonsterStats");
Check.Eq(next.Stats.Count, 0, "the Damage panel's Reset stats clears them");
Check.True(MonsterStatsStore.TryLoad(saveDir, Environment.ProcessId, Player, out MonsterStatsSave afterReset) && afterReset.Rows.Count == 0,
"a reset is saved at once (a reload right after it can't bring the old numbers back)");
next.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Mosswart Worshipper", 5));
next.Call("ResetMonsterStatsFromWindow");
Check.Eq(next.Stats.Count, 0, "the window's Reset clears them");
// A real logout ends them, and the save with them; the next login starts fresh.
next.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Mosswart Worshipper", 5));
next.Call("ShutdownMonsterStats");
next.Call("OnLogoutMonsterStats");
Check.Eq(next.Stats.Count, 0, "logout: no stats");
Check.False(File.Exists(Path.Combine(saveDir, MonsterStatsStore.FileName(Environment.ProcessId, Player))), "logout: the save is gone");
Check.False((bool)next.Get("_monsterStatsStarted")!, "and not counting until the next login");
next.Call("TickMonsterStats");
Check.True((bool)next.Get("_monsterStatsStarted")! && next.Stats.Count == 0, "the next login starts fresh");
// A save for another character in this client isn't picked up.
var other = new MonsterStatsSave
{
ProcessId = Environment.ProcessId, ProcessStartUtcTicks = MonsterStatsStore.ProcessStartTicks, CharacterId = Player + 1,
SavedUtcTicks = DateTime.UtcNow.Ticks, SinceUtcTicks = DateTime.UtcNow.Ticks,
Rows = new List<MonsterStatsRow> { new("Drudge Skulker", 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) },
};
MonsterStatsStore.Save(saveDir, other);
var third = new Rig(saveDir);
third.Call("TickMonsterStats");
Check.Eq(third.Stats.Count, 0, "another character's save isn't this one's");
}
finally
{
try { Directory.Delete(saveDir, true); } catch { }
try { Directory.Delete(sessionDir, true); } catch { }
}
}
private static void DamageRowsCarryStats()
{
string dir = TempDir("ms-rows");
try
{
var rig = new Rig(dir);
Dictionary<string, JsonElement> rows = rig.DamageRows(Path.Combine(dir, "char"));
Check.True(rows.ContainsKey("Drudge Skulker") && rows.ContainsKey("Mosswart Worshipper"), "both monsters around are rows: " + string.Join(", ", rows.Keys));
Check.False(rows.ContainsKey("Some Fellow"), "the other player isn't");
Check.False(rows.Values.Any(r => r.TryGetProperty("mstats", out _)), "no numbers yet: no mstats");
for (int i = 0; i < 3; i++) rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 10));
rig.P.NoteCombatEvent(CombatEvents.EvasionAttackerNotification, NameBody("Drudge Skulker"));
rig.Chat("Drudge Skulker resists your spell");
rig.Chat("You blast Drudge Skulker for 40 points with Force Bolt VI.");
rig.Chat("You fail to affect Drudge Skulker with Surge of Affliction");
rig.P.NoteCombatEvent(CombatEvents.DefenderNotification, DefenderBody("Drudge Skulker", 7));
rig.P.NoteCombatEvent(CombatEvents.EvasionDefenderNotification, NameBody("Drudge Skulker"));
rig.Chat("Drudge Skulker zaps you for 9 points with Shock Wave II.");
rig.Chat("You resist the spell cast by Drudge Skulker");
rig.Set("_currentCombatMode", CombatMode.Melee);
rig.Call("NoteMonsterStatsKill", "You killed Drudge Skulker!");
rows = rig.DamageRows(Path.Combine(dir, "char"));
Check.False(rows["Drudge Skulker"].TryGetProperty("mstats", out _), "the panel's poll reads what the tick published (none yet)");
rig.Call("TickMonsterStats");
rows = rig.DamageRows(Path.Combine(dir, "char"));
Check.True(rows["Drudge Skulker"].TryGetProperty("mstats", out JsonElement m), "after the tick the row has mstats");
if (m.ValueKind == JsonValueKind.Object)
{
int I(string k) => m.TryGetProperty(k, out JsonElement v) ? v.GetInt32() : -1;
// The engine's DamageRowStats field names (RynthCore tools/DamageRowStatsTests).
Check.Eq((I("sw"), I("ev"), I("sp"), I("rs"), I("ne")), (5, 1, 3, 1, 1), "your side: 3 hits + the killing blow, 1 evaded; 3 spells, 1 resisted, 1 no effect");
Check.Eq((I("at"), I("yev"), I("ysp"), I("yrs"), I("yne")), (2, 1, 2, 1, 0), "its side");
Check.Eq((I("k"), I("dd"), I("dt")), (1, 70, 16), "kill and damage (30 + 40 dealt, 7 + 9 taken)");
Check.Eq(m.EnumerateObject().Count(), 13, "the thirteen fields");
}
Check.False(rows["Mosswart Worshipper"].TryGetProperty("mstats", out _), "a monster without numbers has none");
Check.True(rows["Drudge Skulker"].TryGetProperty("key", out _) && rows["Drudge Skulker"].TryGetProperty("kills", out _), "the row's own fields are all still there");
rig.Call("ResetMonsterStatsFromWindow");
rig.Call("TickMonsterStats");
rows = rig.DamageRows(Path.Combine(dir, "char"));
Check.False(rows["Drudge Skulker"].TryGetProperty("mstats", out _), "after a reset the line goes");
}
finally
{
try { Directory.Delete(dir, true); } catch { }
}
}
private static void EngineFlag()
{
string dir = TempDir("ms-flag");
try
{
// An older engine with plugin windows (the owner's API-90 core): no bit 8.
var older = new Rig(dir, uiFlags: 0x7Fu);
Check.False(older.P.EngineDrawsMonsterStats, "no bit 8: the Damage panel doesn't draw them");
Check.True(WindowWanted(older), "the fallback window is declared (and the Session Stats button offered: CreateMiniRemote uses the same rule)");
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, monsterStats: WindowWanted(older));
Check.True(json.Contains("\"window:monsterstats\""), "in the manifest");
var lines = older.Typed("/ra mstats show");
Check.True(lines.Count == 1 && lines[0].Text.Contains("Monster Stats window open") && PanelCalls.Last() == (RynthAiPlugin.MonsterStatsTitle, 1),
"/ra mstats show opens the window: " + Show(lines));
// An engine whose Damage panel draws them: no window, no button, show opens the panel.
var tab = new Rig(dir, uiFlags: 0x7Fu | RynthAiPlugin.DamageRowStatsFlag);
Check.True(tab.P.EngineDrawsMonsterStats, "bit 8: the Damage panel draws them");
Check.False(WindowWanted(tab), "no fallback window, and so no Session Stats button");
Check.False(SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, monsterStats: WindowWanted(tab))
.Contains("monsterstats"), "not in the manifest");
lines = tab.Typed("/ra mstats show");
Check.True(lines.Count == 1 && lines[0].Text.Contains("Damage panel (Monsters) open") && lines[0].Text.Contains("under its line")
&& PanelCalls.Last() == (RynthAiPlugin.DamagePanelKey, 1), "/ra mstats show opens the Damage panel: " + Show(lines));
lines = tab.Typed("/ra mstats hide");
Check.True(lines.Count == 1 && lines[0].Text.Contains("closed") && PanelCalls.Last() == (RynthAiPlugin.DamagePanelKey, 0), "hide closes it: " + Show(lines));
// No plugin windows at all (the rest of the tests' engine): neither, and show says why.
var none = new Rig(dir);
Check.False(none.P.EngineDrawsMonsterStats || WindowWanted(none), "no windows, no flag");
}
finally
{
try { Directory.Delete(dir, true); } catch { }
}
}
private static bool WindowWanted(Rig rig)
=> (bool)typeof(RynthAiPlugin).GetProperty("MonsterStatsWindowWanted", Any)!.GetValue(rig.P)!;
private static string Show(List<(string Text, int Type)> lines) => string.Join(" | ", lines.Select(l => $"[{l.Type}] {l.Text}"));
private static void Command()
{
string dir = TempDir("ms-cmd");
var rig = new Rig(dir);
var lines = rig.Typed("/ra mstats list");
Check.True(lines.Count == 1 && lines[0].Text.Contains("No monster stats yet"), "list with none: " + Show(lines));
lines = rig.Typed("/ra mstats Drudge Skulker");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("No monster stats for 'Drudge Skulker'")
&& lines[0].Text.Contains(RynthAiPlugin.MonsterStatsUsage), "none yet: why, and the usage: " + Show(lines));
for (int i = 0; i < 3; i++) rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 10));
rig.P.NoteCombatEvent(CombatEvents.EvasionAttackerNotification, NameBody("Drudge Skulker"));
rig.Chat("Drudge Skulker resists your spell");
rig.P.NoteCombatEvent(CombatEvents.EvasionDefenderNotification, NameBody("Mosswart Worshipper"));
rig.P.NoteCombatEvent(CombatEvents.EvasionDefenderNotification, NameBody("Drudge Ravener"));
lines = rig.Typed("/ra mstats Drudge Skulker");
Check.Eq(lines.Count, 3, "three lines: " + Show(lines));
Check.True(lines.All(l => l.Type == CommandReply.OkColor), "shown as an answer, not a failure");
Check.True(lines.Count == 3 && lines[0].Text.Contains("Drudge Skulker since login") && lines[1].Text.Contains("4 swings, 3 hit, it evaded 1 (25%)")
&& lines[1].Text.Contains("it resisted 1 (100%)") && lines[2].Text.Contains("0 attacks"), "its numbers: " + Show(lines));
lines = rig.Typed("/ra mstats moss");
Check.True(lines.Count == 3 && lines[0].Text.Contains("Mosswart Worshipper") && lines[2].Text.Contains("you evaded 1 (100%)"),
"part of a name: " + Show(lines));
lines = rig.Typed("/ra mstats Drudge");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("matches 2 monsters")
&& lines[0].Text.Contains("Drudge Skulker") && lines[0].Text.Contains("Drudge Ravener"), "two Drudges: say which: " + Show(lines));
lines = rig.Typed("/ra mstats Banderling");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("No monster stats for 'Banderling'")
&& lines[0].Text.Contains("Monsters with stats:") && lines[0].Text.Contains("Usage:"), "unknown: why, who has, the usage: " + Show(lines));
// No name: the monster selected (or fought).
lines = rig.Typed("/ra mstats");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("Select a monster or name one"),
"nothing selected: " + Show(lines));
rig.Set("_currentTargetId", Drudge);
lines = rig.Typed("/ra mstats");
Check.True(lines.Count == 3 && lines[0].Text.Contains("Drudge Skulker since login"), "the selected monster: " + Show(lines));
lines = rig.Typed("/ra mstats list");
Check.True(lines.Count == 4 && lines[0].Text.Contains("3 kinds") && lines.Skip(1).All(l => l.Text.Contains("it evades")), "the list: " + Show(lines));
lines = rig.Typed("/ra mstats show");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("plugin windows"),
"no plugin windows in this engine: says so: " + Show(lines));
lines = rig.Typed("/ra mstats reset");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.OkColor && lines[0].Text.Contains("started over (3 kinds"), "reset: " + Show(lines));
Check.Eq(rig.Stats.Count, 0, "and they are gone");
lines = rig.Typed("/ra mstats");
Check.True(lines.Count == 1 && lines[0].Type == CommandReply.FailColor && lines[0].Text.Contains("No monster stats for Drudge Skulker since login yet"),
"selected, but no numbers since the reset: " + Show(lines));
lines = rig.Typed("/ra help");
Check.True(lines.Any(l => l.Text.Contains("/ra mstats")), "the help lists it");
try { Directory.Delete(dir, true); } catch { }
}
private static void WindowView()
{
string dir = TempDir("ms-view");
var rig = new Rig(dir);
MonsterStatsView View() => (MonsterStatsView)rig.Get("_monsterStatsView")!;
Check.False(View().InWorld, "before the first tick: the empty view");
rig.Call("TickMonsterStats");
Check.True(View().InWorld && View().Rows.Length == 0 && View().PhysicalCounted, "the first tick in the world publishes, window or not");
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30));
rig.Set("_monsterStatsViewAtMs", 0L);
rig.Call("TickMonsterStats");
Check.Eq(View().Rows.Length, 0, "off screen a fight doesn't rebuild the view");
rig.Set("_monsterStatsDrawnMs", Environment.TickCount64); // the window drew a frame
rig.Set("_currentTargetId", Drudge);
rig.Call("TickMonsterStats");
Check.True(View().Rows.Length == 1 && View().Rows[0].Hits == 1, "on screen it follows the numbers");
Check.Eq(View().FocusName, "Drudge Skulker", "and the monster in focus (selected)");
rig.Set("_combatEventsStreaming", false);
rig.P.NoteCombatEvent(CombatEvents.EvasionAttackerNotification, NameBody("Drudge Skulker"));
rig.Set("_monsterStatsViewAtMs", 0L);
rig.Call("TickMonsterStats");
Check.False(View().PhysicalCounted, "no combat event stream: the window says melee and missile go uncounted");
rig.Call("OnLogoutMonsterStats");
Check.False(View().InWorld, "logout: the empty view at once");
try { Directory.Delete(dir, true); } catch { }
}
private static void ManifestWindow()
{
string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true, monsterStats: true);
SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error);
Check.Eq(error, string.Empty, "no parse error");
Check.Eq(m.Windows.Length, 2, "the dashboard and Monster Stats");
SectionWindowDecl w = m.Windows.Single(x => x.Id == "monsterstats");
Check.Eq(w.Title, RynthAiPlugin.MonsterStatsTitle, "title (its panel key)");
Check.Eq(w.Surface, RynthAiPlugin.MonsterStatsSurface, "surface");
Check.Eq(w.Surface, "window:monsterstats", "the surface PluginExports.RenderEmbed draws");
Check.False(w.Bar, "no bar button (the Session Stats view and /ra mstats show open it)");
Check.False(w.TakeOver || w.Frameless, "the engine's frame, nobody's place");
Check.True(w.Server.Length == 0, "every world");
Check.True(w.Width >= w.MinWidth && w.Height >= w.MinHeight, "sizes");
Check.True(m.Windows.Single(x => x.Id == "dashboard").TakeOver, "the dashboard window is unchanged");
SectionManifest alone = SectionManifestParser.Parse("RynthAi",
SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, monsterStats: true), out error);
Check.True(error.Length == 0 && alone.Windows.Length == 1 && alone.Windows[0].Id == "monsterstats", "without the dashboard (Classic look)");
SectionManifest none = SectionManifestParser.Parse("RynthAi", SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections), out _);
Check.Eq(none.Windows.Length, 0, "an engine before v89: no window declared");
Check.Eq(none.Contributions.Length, 5, "the section views are unchanged");
}
}

View file

@ -0,0 +1,312 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes, VTank's "idlebufftopoff"). The checkbox
// was saved and shown but nothing read it. What it means (the owner, 2026-10-30): an earlier timer for
// idle moments. With it on and the bot idle (no fight target, no monster within Monster Range, no
// corpse to loot, no salvage), a rebuff starts once a buff has Rebuff With + the margin (default 2
// minutes) left. The regular rebuff is unchanged, in a fight or not; an early top-off never starts in
// a fight and stops when one begins; margin 0 adds nothing.
internal static class RebuffWhenIdleTests
{
private const uint Player = 0x50000F01;
private const uint STypeCreature = 31, STypeLife = 33;
private const string Strength = "Strength Self VI", Willpower = "Willpower Self VI";
public static void Register(Runner r)
{
r.Add("rebuff when idle: idle, a buff inside Rebuff With + the margin is rebuffed early", IdleInsideMarginRebuffed);
r.Add("rebuff when idle: in a fight, a buff inside the margin but over Rebuff With is not rebuffed", FightInsideMarginWaits);
r.Add("rebuff when idle: in a fight, a buff at or under Rebuff With (or dispelled) is rebuffed as before", FightRegularRebuff);
r.Add("rebuff when idle: margin 0, or the option off, adds nothing", MarginZeroAddsNothing);
r.Add("rebuff when idle: an early top-off under way stops when a fight starts (the cast sent resolves); the regular rules take over", EarlyRunStopsForFight);
r.Add("rebuff when idle: Force Buff in a fight is unchanged", ForceBuffUnchanged);
r.Add("rebuff when idle: the margin defaults to 2, is saved, loaded, copied, bridged, in the settings map; idlebufftopoff imports the option", Setting);
}
// ── Rig ───────────────────────────────────────────────────────────────────
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).FirstOrDefault();
private static string NameOf(int id) => SpellTable.ById(id)?.Name ?? $"#{id}";
/// <summary>Creature and Life Magic 300 (tier 6), in Magic stance, knowing Strength and Willpower
/// Self VI; the macro on, Rebuff With 300 s, no vital lines, full vitals. <see cref="Idle"/> is what
/// the plugin's idle test answers (and not idle = a monster within Monster Range).</summary>
private sealed class Rig
{
public readonly LegacyUiSettings S;
public readonly BuffManager B;
public bool Idle = true;
private DateTime _now = new(2026, 10, 30, 12, 0, 0);
public Rig(bool rebuffWhenIdle, int marginMinutes = 2)
{
FakeHost.Reset();
foreach (string n in new[] { Strength, Willpower })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeCreature)] = (300, 2);
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
FakeHost.WeaponCalls = true; // GetCurrentCombatMode answers CombatModeValue
FakeHost.CombatModeValue = CombatMode.Magic;
var host = FakeHost.Create();
S = new LegacyUiSettings
{
IsMacroRunning = true, EnableBuffing = true, SpellCastIntervalMs = 0,
RebuffWhenIdle = rebuffWhenIdle, RebuffIdleMarginMinutes = marginMinutes, RebuffSecondsRemaining = 300,
HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, UseBuffItems = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
B = new BuffManager(host, S, sm, v) { InCombatOverride = () => !Idle, IdleForTopOff = () => Idle };
B.SetCharacterSkills(skills);
FakeHost.ServerTime = 100_000;
B.Clock = () => _now;
B.MarkLiveBuffsReadyForTests();
}
/// <summary>The live enchantment registry (spell, seconds left), read.</summary>
public void Live(params (string Name, double Left)[] enchantments)
{
FakeHost.Enchantments.Clear();
foreach (var (name, left) in enchantments) FakeHost.Enchantments.Add(((uint)Id(name), FakeHost.ServerTime + left));
B.RefreshFromLiveMemory();
}
/// <summary>A monster's dispel takes <paramref name="buff"/> off, as the engine reports it.</summary>
public void Dispel(string buff)
{
FakeHost.Enchantments.RemoveAll(e => e.SpellId == (uint)Id(buff));
B.OnEnchantmentRemoved((uint)Id(buff));
}
/// <summary>The server's answer to a buff cast: it lands (registry and result line).</summary>
public void Answer(string name)
{
FakeHost.Enchantments.RemoveAll(e => e.SpellId == (uint)Id(name));
FakeHost.Enchantments.Add(((uint)Id(name), FakeHost.ServerTime + 2700));
B.OnChatWindowText($"You cast {name} on yourself", 7);
}
/// <summary>One heartbeat a second; a cast it sends is answered unless <paramref name="answer"/> is false. The spell sent, or "".</summary>
public string Beat(bool answer = true)
{
_now = _now.AddSeconds(1);
int before = FakeHost.Casts.Count;
B.OnHeartbeat();
if (FakeHost.Casts.Count == before) return "";
string name = NameOf(FakeHost.Casts.Last().SpellId);
if (answer) Answer(name);
return name;
}
public List<string> Beats(int n)
{
var sent = new List<string>();
for (int i = 0; i < n; i++) { string s = Beat(); if (s.Length > 0) sent.Add(s); }
return sent;
}
/// <summary>The arbiter's choice, from the inputs RynthAiPlugin gives it (combat wants the tick when not idle).</summary>
public BotActivity Arbiter()
{
bool wantBuff = B.PendingSpellId != 0 || B.WantsVitalRecharge || (S.EnableBuffing && B.NeedsAnyBuff());
return ActivityArbiter.Decide(new ArbiterInputs(true, wantBuff, wantCombat: !Idle, wantLooting: false, wantSalvaging: false, wantNav: false,
combatEngaged: !Idle));
}
public bool Running => B.GetStateSnapshot().IsForceRebuffing;
public int Logged(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static string Show(IEnumerable<string> sent) => sent.Any() ? string.Join(", ", sent) : "(none)";
// ── Tests ─────────────────────────────────────────────────────────────────
private static void IdleInsideMarginRebuffed()
{
var rig = new Rig(rebuffWhenIdle: true);
Check.Eq(rig.B.RebuffLineSec(), 420, "idle: Rebuff With 300 s + 2 min");
rig.Live((Strength, 400), (Willpower, 3000)); // 400 s: over 300, inside 420
Check.True(rig.B.NeedsAnyBuff(), "Strength is due for an early top-off");
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "buffing takes the idle tick");
Check.Eq(Show(rig.Beats(5)), Strength, "Strength is topped off (Willpower, 3000 s left, is left alone)");
Check.Eq(rig.B.IdleTopOffRuns, 1, "one early top-off run");
Check.Eq(rig.Logged("[Buff] Rebuff When Idle: idle, and a buff has under 420 s left"), 1, "logged");
Check.False(rig.Running, "the run ends");
Check.False(rig.B.NeedsAnyBuff(), "nothing due afterwards");
// Just over the margin: nothing yet.
var over = new Rig(rebuffWhenIdle: true);
over.Live((Strength, 430), (Willpower, 3000));
Check.Eq(Show(over.Beats(5)), "(none)", "430 s left, over the 420 s line: not yet");
// Also Refresh Under at or below Rebuff With: the early run still casts the buff that started it, once.
var narrow = new Rig(rebuffWhenIdle: true);
narrow.S.RebuffTopOffSecondsRemaining = 300;
narrow.Live((Strength, 400), (Willpower, 3000));
Check.Eq(Show(narrow.Beats(8)), Strength, "the triggering buff is in the run, no loop");
Check.Eq(narrow.B.IdleTopOffRuns, 1, "one run");
}
private static void FightInsideMarginWaits()
{
var rig = new Rig(rebuffWhenIdle: true) { Idle = false };
Check.Eq(rig.B.RebuffLineSec(), 300, "in a fight: Rebuff With only");
rig.Live((Strength, 400), (Willpower, 3000));
Check.False(rig.B.NeedsAnyBuff(), "400 s left in a fight: not due");
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat keeps the tick");
Check.Eq(Show(rig.Beats(10)), "(none)", "no early top-off in a fight");
Check.Eq(rig.B.IdleTopOffRuns, 0, "none started");
rig.Idle = true;
Check.Eq(Show(rig.Beats(5)), Strength, "the fight over: topped off then");
}
private static void FightRegularRebuff()
{
var low = new Rig(rebuffWhenIdle: true) { Idle = false };
low.Live((Strength, 290), (Willpower, 3000)); // under Rebuff With 300
Check.True(low.B.NeedsAnyBuff(), "290 s left: due, fight or not");
Check.Eq(low.Arbiter(), BotActivity.Buffing, "buffing takes the tick, as before");
Check.Eq(Show(low.Beats(5)), Strength, "rebuffed in the fight");
Check.Eq(low.B.IdleTopOffRuns, 0, "a regular run, not an early top-off");
var dispel = new Rig(rebuffWhenIdle: true);
dispel.Live((Strength, 3000), (Willpower, 3000));
dispel.Beats(2);
dispel.Idle = false;
dispel.Dispel(Strength);
Check.Eq(Show(dispel.Beats(5)), Strength, "a buff dispelled mid-fight is recast at once, as before");
var off = new Rig(rebuffWhenIdle: false) { Idle = false };
off.Live((Strength, 290), (Willpower, 3000));
Check.Eq(Show(off.Beats(5)), Strength, "the same with the option off");
}
private static void MarginZeroAddsNothing()
{
var zero = new Rig(rebuffWhenIdle: true, marginMinutes: 0);
Check.Eq(zero.B.RebuffLineSec(), 300, "margin 0: Rebuff With only, idle too");
zero.Live((Strength, 400), (Willpower, 3000));
Check.Eq(Show(zero.Beats(5)), "(none)", "margin 0: 400 s left is not due");
zero.Live((Strength, 290), (Willpower, 3000));
Check.Eq(Show(zero.Beats(5)), Strength, "the regular rebuff still goes");
Check.Eq(zero.B.IdleTopOffRuns, 0, "never an early top-off");
var off = new Rig(rebuffWhenIdle: false, marginMinutes: 2);
Check.Eq(off.B.RebuffLineSec(), 300, "option off: the margin is not read");
off.Live((Strength, 400), (Willpower, 3000));
Check.Eq(Show(off.Beats(5)), "(none)", "option off: not due early");
var negative = new Rig(rebuffWhenIdle: true, marginMinutes: -5);
Check.Eq(negative.B.RebuffLineSec(), 300, "a negative margin counts as 0");
}
private static void EarlyRunStopsForFight()
{
var rig = new Rig(rebuffWhenIdle: true);
rig.Live((Strength, 400), (Willpower, 400)); // both inside the margin: one early run
string first = rig.Beat(answer: false);
Check.True(first == Strength || first == Willpower, $"idle: the early run starts ('{first}', hold: {rig.B.LastBuffSkipReason})");
Check.True(rig.Running, "the run is under way");
rig.Idle = false; // a monster comes
Check.Eq(rig.Arbiter(), BotActivity.Buffing, "the cast in flight keeps the slot until it resolves");
rig.Answer(first);
Check.Eq(rig.Beat(), "", "the next heartbeat casts nothing");
Check.False(rig.Running, "the run stopped at that safe point (before the arbiter reads it)");
Check.False(rig.B.NeedsAnyBuff(), "the early run no longer holds the tick");
Check.Eq(rig.Arbiter(), BotActivity.Combat, "combat has it");
Check.Eq(Show(rig.Beats(10)), "(none)", "nothing more is cast in the fight");
Check.Eq(rig.Logged("the early top-off stops"), 1, "logged once");
// The regular rules take over: the other buff dropping under Rebuff With is rebuffed in the fight.
string other = first == Strength ? Willpower : Strength;
rig.Live((first, 2700), (other, 290));
Check.Eq(Show(rig.Beats(5)), other, "under Rebuff With in the fight: rebuffed as usual");
// And an early run interrupted with the other buff still inside the margin finishes when idle again.
var again = new Rig(rebuffWhenIdle: true);
again.Live((Strength, 400), (Willpower, 400));
string a = again.Beat(answer: false);
again.Idle = false;
again.Answer(a);
again.Beats(5);
again.Idle = true;
Check.Eq(Show(again.Beats(5)), a == Strength ? Willpower : Strength, "idle again: the rest is topped off");
Check.Eq(again.B.IdleTopOffRuns, 2, "a second early run");
}
private static void ForceBuffUnchanged()
{
var rig = new Rig(rebuffWhenIdle: true) { Idle = false };
rig.Live((Strength, 3000), (Willpower, 3000));
rig.B.RequestForceFullRebuff();
var sent = rig.Beats(10);
Check.True(sent.Contains(Strength) && sent.Contains(Willpower), "Force Buff recasts everything, in a fight too: " + Show(sent));
Check.False(rig.Running, "and ends");
}
private static void Setting()
{
var fresh = new LegacyUiSettings();
Check.False(fresh.RebuffWhenIdle, "a new profile: Rebuff When Idle off");
Check.Eq(fresh.RebuffIdleMarginMinutes, 2, "the margin defaults to 2 minutes");
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffWhenIdle\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.RebuffWhenIdle && old.RebuffIdleMarginMinutes == 2, "a profile saved before the margin: 2");
var saved = JsonSerializer.Deserialize(
JsonSerializer.Serialize(new LegacyUiSettings { RebuffWhenIdle = true, RebuffIdleMarginMinutes = 0 }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(saved != null && saved.RebuffWhenIdle && saved.RebuffIdleMarginMinutes == 0, "saved and loaded (0 stays 0)");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { RebuffIdleMarginMinutes = 7 }, dst });
Check.Eq(dst.RebuffIdleMarginMinutes, 7, "a profile switch copies it");
// The engine's Settings face: sent; a save without it (an engine that doesn't know it) leaves it alone.
var s = new LegacyUiSettings { RebuffIdleMarginMinutes = 5 };
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
Check.True(sent?.RebuffIdleMarginMinutes == 5, "sent to the engine face");
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
Check.Eq(s.RebuffIdleMarginMinutes, 5, "a save without it leaves it alone");
dash.ApplySettingsJson("{\"RebuffIdleMarginMinutes\":0}");
Check.Eq(s.RebuffIdleMarginMinutes, 0, "a save with 0 sets 0");
var live = new LegacyUiSettings();
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
Check.True(map.TryGetValue("RebuffIdleMarginMinutes", out var entry), "RebuffIdleMarginMinutes is in the settings map");
Check.Eq(entry.Get(), "2", "reads 2");
entry.Set("4");
Check.Eq(live.RebuffIdleMarginMinutes, 4, "and sets it");
Check.True(map.TryGetValue("RebuffWhenIdle", out var on), "RebuffWhenIdle is in the settings map");
on.Set("1");
Check.True(live.RebuffWhenIdle, "and sets it on");
// VTank import: idlebufftopoff is the option; VTank has no time field for it in our tables, so the
// margin keeps its default on import.
Check.True(MetaManager.TryMapVtOption("idlebufftopoff", out string ra) && ra == "RebuffWhenIdle", "VTank's idlebufftopoff imports Rebuff When Idle");
}
}

View file

@ -0,0 +1,170 @@
using System.IO;
using System.Linq;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The session's death count (SessionStatsTracker: RynthAi's Mini Remote stats, which RynthTracker
// shows; 2026-10-30) against the engine calls it really reads each tick: the player's vitals
// (GetPlayerVitals) and the player's NumDeaths (PropertyInt 43). The count used to wait for the
// player's health in OnUpdateHealth, which the engine never sends for the player (it is a
// target's health), so it stayed 0. Here nothing ever calls OnUpdateHealth, as in the game.
internal static class SessionDeathTests
{
private const uint Player = 0x50000D01;
private const uint NumDeaths = 43;
private const string Tag = "[RynthAi] Mini Remote stats:";
public static void Register(Runner r)
{
r.Add("session stats: a death as the server sends it counts once (vitals, then NumDeaths)", DeathSequence);
r.Add("session stats: a reload while dead or during a death counts each death once", DeathsAcrossReload);
r.Add("session stats: deaths count on an engine at API 90", DeathsOnApi90);
}
private static string Folder(string name)
{
string dir = Path.Combine(Program.TempRoot, "session-deaths", name);
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
return dir;
}
private static SessionStatsTracker LogIn(RynthCoreHost host, string dir)
{
var t = new SessionStatsTracker(host, Tag, dir);
t.OnLoginComplete();
t.Tick();
return t;
}
/// <summary>A few ticks with the vitals (and NumDeaths, null = the character has none) as given.</summary>
private static void Ticks(SessionStatsTracker t, uint health, uint max, int? numDeaths, int ticks = 3)
{
FakeHost.Vitals = (health, max, 200, 200, 150, 150);
if (numDeaths is int n) FakeHost.Ints[(Player, NumDeaths)] = n;
else FakeHost.Ints.Remove((Player, NumDeaths));
for (int i = 0; i < ticks; i++) t.Tick();
}
private static int Counted() => FakeHost.Logs.Count(l => l.Contains("Death counted"));
// ACE's order (Player_Death): OnDeath sends the victim notice (no plugin event), then Die sends
// health 0 and NumDeaths in one packet; after the death animation the corpse and the portal; 3 s
// into portal space health comes back at 75 %.
private static void DeathSequence()
{
FakeHost.Reset();
try
{
var host = FakeHost.Create(Player);
FakeHost.Vitals = (0, 0, 0, 0, 0, 0); // login: 0/0 before the player's vitals
FakeHost.Ints[(Player, NumDeaths)] = 4;
var t = LogIn(host, Folder("sequence"));
Check.True(t.Active, "the session runs after login");
Ticks(t, 0, 0, 4);
Ticks(t, 0, 360, 4); // the max before the health
Ticks(t, 360, 360, 4);
Check.Eq(t.View.Deaths, 0, "login: the 0/0 packet and 0/max before the first reading are no death");
Ticks(t, 120, 360, 4); // a fight
t.OnKillNotification("You killed the Drudge Skulker!");
Ticks(t, 30, 360, 4);
Check.Eq(t.View.Deaths, 0, "a kill notice and low health are no death");
Ticks(t, 0, 360, 5, ticks: 1); // Die(): health 0 and NumDeaths 5, one packet
Check.Eq(t.View.Deaths, 1, "the death shows at once");
FakeHost.Portaling = true; // dead ~5 s: the corpse, the portal to the lifestone
Ticks(t, 0, 360, 5, ticks: 150);
Ticks(t, 270, 360, 5); // 3 s into portal space: 75 % health
FakeHost.Portaling = false;
Ticks(t, 360, 360, 5);
Check.Eq(t.View.Deaths, 1, "one death, once, through the portal and the respawn");
Check.Eq(Counted(), 1, "logged once");
Ticks(t, 200, 360, 5);
Ticks(t, 0, 360, 6);
Ticks(t, 270, 360, 6);
Check.Eq(t.View.Deaths, 2, "the next death counts");
Check.Eq(t.View.Kills, 1, "the kill stays one kill");
t.OnLogout();
}
finally { FakeHost.Reset(); }
}
// A hot reload is a Shutdown (the save) and a new copy's OnLoginComplete (the restore).
private static void DeathsAcrossReload()
{
FakeHost.Reset();
try
{
// Reloaded while dead: the new copy doesn't count that death again.
var host = FakeHost.Create(Player);
string dir = Folder("reload-dead");
FakeHost.Vitals = (360, 360, 200, 200, 150, 150);
FakeHost.Ints[(Player, NumDeaths)] = 4;
var a = LogIn(host, dir);
Ticks(a, 360, 360, 4);
Ticks(a, 0, 360, 5);
Check.Eq(a.View.Deaths, 1, "reload while dead: counted before the reload");
a.Shutdown();
var b = LogIn(host, dir);
Check.True(FakeHost.Logs.Any(l => l.Contains("Session carried over")), "the session carries over");
Ticks(b, 0, 360, 5);
Ticks(b, 270, 360, 5);
Check.Eq(b.View.Deaths, 1, "reload while dead: still one after it");
Ticks(b, 0, 360, 6);
Ticks(b, 270, 360, 6);
Check.Eq(b.View.Deaths, 2, "and the next death counts");
b.OnLogout();
// Died while the plugin was unloaded: the saved NumDeaths baseline counts it.
FakeHost.Reset();
host = FakeHost.Create(Player);
dir = Folder("reload-gap");
FakeHost.Vitals = (360, 360, 200, 200, 150, 150);
FakeHost.Ints[(Player, NumDeaths)] = 4;
var c = LogIn(host, dir);
Ticks(c, 360, 360, 4);
c.Shutdown();
FakeHost.Vitals = (0, 360, 200, 200, 150, 150); // the death lands before the new copy's first tick
FakeHost.Ints[(Player, NumDeaths)] = 5;
var d = LogIn(host, dir);
Ticks(d, 0, 360, 5);
Ticks(d, 270, 360, 5);
Check.Eq(d.View.Deaths, 1, "died during the reload: counted once");
// A real logout ends the session: the next login starts at 0 deaths.
d.OnLogout();
var e = LogIn(host, dir);
Ticks(e, 360, 360, 5);
Check.Eq(e.View.Deaths, 0, "a new login is a new session");
e.OnLogout();
}
finally { FakeHost.Reset(); }
}
// The two calls are older than the v66 baseline: an API 90 engine counts deaths the same way.
private static void DeathsOnApi90()
{
FakeHost.Reset();
try
{
FakeHost.ConfigureApi = (ref RynthCoreApiNative api) => api.Version = 90;
var host = FakeHost.Create(Player);
Check.Eq(host.Version, 90u, "the host is at API 90");
Check.True(host.HasGetPlayerVitals && host.HasGetObjectIntProperty, "both calls there");
FakeHost.Vitals = (300, 300, 200, 200, 150, 150);
var t = LogIn(host, Folder("api90"));
Ticks(t, 300, 300, null); // a character that never died: no NumDeaths yet
Ticks(t, 0, 300, 1); // its first death brings the counter
Ticks(t, 225, 300, 1);
Check.Eq(t.View.Deaths, 1, "API 90: a new character's first death counts once");
t.OnLogout();
}
finally { FakeHost.Reset(); }
}
}

View file

@ -136,6 +136,8 @@ internal static partial class Program
BankIncome = 9_000,
OwnSinceBank = 4_000,
RecentLum = { (Now.AddMinutes(-2).Ticks, 300), (Now.AddMinutes(-1).Ticks, 700) },
DeathCountBase = 17,
DeathOpen = true,
};
private static void SameState(TrackerSessionState a, TrackerSessionState b, string what)
@ -165,6 +167,8 @@ internal static partial class Program
Eq(a.BankIncome, b.BankIncome, what + " bankincome");
Eq(a.OwnSinceBank, b.OwnSinceBank, what + " ownsincebank");
Eq(string.Join(";", a.RecentLum), string.Join(";", b.RecentLum), what + " recentlum");
Eq(a.DeathCountBase, b.DeathCountBase, what + " deathsbase");
Eq(a.DeathOpen, b.DeathOpen, what + " deathopen");
}
// First read is the baseline; rises count; a drop only moves the baseline.
@ -195,6 +199,8 @@ internal static partial class Program
var s = Sample();
s.XpBase = null; s.LumBase = null; s.RadBase = null; s.BankedBase = null; s.DrawnBase = null;
s.BankLumBase = null;
s.DeathCountBase = null;
s.DeathOpen = false;
s.RecentLum.Clear();
s.MaxLevel = false;
Check(TrackerSessionStore.TryParse(TrackerSessionStore.Serialize(s), out var back), "null baselines parse");
@ -249,6 +255,21 @@ internal static partial class Program
Eq(oldBack.RecentLum.Count, 0, "older save: no recent luminance");
Check(!TrackerSessionStore.TryParse(good.Replace("lumown=5000", "lumown=x"), out _), "malformed new key rejected");
Check(!TrackerSessionStore.TryParse(good.Replace("recentlum=", "recentlum=12"), out _), "malformed recent luminance rejected");
// A save written before the 2026-10-30 death keys (the live release's) carries on too.
string preDeaths = good;
foreach (string key in new[] { "deathsbase", "deathopen" })
{
int at = preDeaths.IndexOf("\n" + key + "=", StringComparison.Ordinal);
int end = preDeaths.IndexOf('\n', at + 1);
preDeaths = preDeaths.Remove(at, end - at);
}
Check(TrackerSessionStore.TryParse(preDeaths, out var preBack), "save without the 2026-10-30 keys parses");
Eq(preBack.DeathsTotal, Sample().DeathsTotal, "older save keeps its deaths");
Eq(preBack.DeathCountBase, (long?)null, "older save: no death counter baseline (its first read is one)");
Check(!preBack.DeathOpen, "older save: no death waiting for its counter");
Check(!TrackerSessionStore.TryParse(good.Replace("deathsbase=17", "deathsbase=?"), out _), "malformed death counter baseline rejected");
Check(!TrackerSessionStore.TryParse(good.Replace("deathopen=1", "deathopen=yes"), out _), "malformed death flag rejected");
}
private static void TestShouldRestore()

View file

@ -21,6 +21,7 @@ internal static partial class Program
TestAelrynthAndRetailLum();
TestLumLast5Min();
TestKillsAndXpPerKill();
TestDeaths();
TestSessionStatsReloadMatches();
}
@ -169,8 +170,219 @@ internal static partial class Program
Eq(s.Kills, 2, "corpse kill joins the kills");
Eq(s.XpPerKill, 500L, "corpse kill takes the XP just before it: (600 + 400) / 2");
s.OnPlayerDied();
s.OnPlayerHealth(300, 300);
s.OnPlayerHealth(0, 300);
Eq(s.View(S0.AddHours(1)).Deaths, 1, "death");
Eq(s.Kills, 2, "a death is no kill");
}
// Deaths (2026-10-30): the vitals and NumDeaths, each death once.
/// <summary>One tick of SessionStatsTracker.CheckDeaths: the vitals, then the counter (null = not readable).</summary>
private static void Read(SessionStats s, uint health, uint max, int? numDeaths)
{
s.OnPlayerHealth(health, max);
if (numDeaths is int n) s.OnDeathCount(n);
}
/// <summary>Capture, save text, parse, apply: a plugin reload in the middle of the session.</summary>
private static SessionStats Reload(SessionStats s, DateTime t)
{
var st = Sample();
s.CaptureInto(st, t);
Check(TrackerSessionStore.TryParse(TrackerSessionStore.Serialize(st), out var back), "deaths: the save parses");
var next = new SessionStats();
next.ApplyFrom(back);
return next;
}
private static void TestDeaths()
{
TestDeathSequence();
TestDeathCounterOrder();
TestDeathsWithoutCounter();
TestDeathsWithoutVitals();
TestDeathReset();
TestDeathsAcrossReload();
}
// A real death as the server sends it (ACE Player_Death: OnDeath sends the victim notice, then Die
// sends health 0 and NumDeaths in one packet; the corpse and the portal follow the death animation,
// and 3 s into portal space health comes back at 75 %), read tick by tick as the tracker reads it.
private static void TestDeathSequence()
{
var s = new SessionStats();
s.Reset(S0);
DateTime t = S0;
// Login: 0/0 until the player's vitals land, and a moment with the max but no health yet.
Read(s, 0, 0, null);
Read(s, 0, 0, 4);
Read(s, 0, 360, 4);
Eq(s.Deaths, 0, "login: the 0/0 packet and 0/max before the first real reading are no death");
Read(s, 360, 360, 4);
Eq(s.Deaths, 0, "login: the death counter's first read is its baseline");
// A fight: health falls and the character lands a kill. Neither is a death.
Read(s, 120, 360, 4);
s.OnKillNotice("You killed the Drudge Skulker!", t.AddSeconds(1));
Read(s, 40, 360, 4);
Eq(s.Deaths, 0, "a kill notice and low health are no death");
Eq(s.Kills, 1, "the kill counts");
// Die(): health 0 and NumDeaths 5 in one packet, read in the same tick.
Read(s, 0, 360, 5);
Eq(s.Deaths, 1, "health 0 and NumDeaths +1: one death");
for (int i = 0; i < 300; i++) Read(s, 0, 360, 5); // ~5 s dead: the animation, the corpse, the portal
Eq(s.Deaths, 1, "still one through the death animation and the portal");
Read(s, 270, 360, 5); // 3 s into portal space: 75 % health
Read(s, 360, 360, 5);
Eq(s.Deaths, 1, "alive again: still one");
Eq(s.Kills, 1, "a death is no kill");
// The next death counts again.
Read(s, 200, 360, 5);
Read(s, 0, 360, 6);
Read(s, 0, 360, 6);
Read(s, 270, 360, 6);
Eq(s.Deaths, 2, "a second death");
Eq(s.View(S0.AddHours(1)).Deaths, 2, "the view shows them");
}
// The two readings of one death in either order: the pump can read the vitals just before the
// packet and the counter just after it, or the counter can come a tick after the health.
private static void TestDeathCounterOrder()
{
var s = new SessionStats();
s.Reset(S0);
Read(s, 360, 360, 10);
Read(s, 90, 360, 11); // the vitals read before the packet, the counter after it
Eq(s.Deaths, 1, "counter first: counted at once");
Read(s, 0, 360, 11);
Read(s, 0, 360, 11);
Eq(s.Deaths, 1, "its health 0 a tick later is the same death");
Read(s, 270, 360, 11);
Read(s, 0, 360, 11); // health first, the counter a tick behind
Eq(s.Deaths, 2, "health first: counted at once");
Read(s, 0, 360, 12);
Eq(s.Deaths, 2, "its counter rise a tick later is the same death");
Read(s, 270, 360, 12);
Eq(s.Deaths, 2, "two deaths, each once");
}
// A character that never died has no NumDeaths until its first death; a server may never send it.
private static void TestDeathsWithoutCounter()
{
var fresh = new SessionStats();
fresh.Reset(S0);
Read(fresh, 300, 300, null);
Read(fresh, 0, 300, 1); // the counter appears with the first death: that read is its baseline
Eq(fresh.Deaths, 1, "first death of a new character: health counts it");
Read(fresh, 225, 300, 1);
Read(fresh, 0, 300, 2);
Read(fresh, 225, 300, 2);
Eq(fresh.Deaths, 2, "its second death: health and the counter, once");
var none = new SessionStats();
none.Reset(S0);
for (int d = 0; d < 3; d++)
{
Read(none, 300, 300, null);
Read(none, 0, 300, null);
Read(none, 0, 300, null);
}
Read(none, 225, 300, null);
Eq(none.Deaths, 3, "no death counter from the server: each health 0 counts once");
}
// An engine without the vitals call: the counter alone, and two deaths between two reads.
private static void TestDeathsWithoutVitals()
{
var s = new SessionStats();
s.Reset(S0);
s.OnDeathCount(4);
s.OnDeathCount(5);
s.OnDeathCount(5);
Eq(s.Deaths, 1, "counter only: a rise is a death");
s.OnDeathCount(7);
Eq(s.Deaths, 3, "counter only: a rise of two is two deaths");
s.OnDeathCount(3);
s.OnDeathCount(4);
Eq(s.Deaths, 4, "a drop only moves the baseline");
}
// Reset while dead: that death was the old session's.
private static void TestDeathReset()
{
var s = new SessionStats();
s.Reset(S0);
Read(s, 360, 360, 4);
Read(s, 0, 360, 5);
Eq(s.Deaths, 1, "reset: a death first");
s.Reset(S0.AddMinutes(1));
Read(s, 0, 360, 5);
Read(s, 270, 360, 5);
Eq(s.Deaths, 0, "reset while dead: that death stays in the old session");
Read(s, 0, 360, 6);
Eq(s.Deaths, 1, "the next death counts");
}
// Plugin reloads around a death (the session save: SessionStats.CaptureInto / ApplyFrom).
private static void TestDeathsAcrossReload()
{
DateTime t = S0.AddMinutes(5);
// Reloaded while dead, after the death was counted: not counted again.
var a = new SessionStats();
a.Reset(S0);
Read(a, 360, 360, 4);
Read(a, 0, 360, 5);
a = Reload(a, t);
Read(a, 0, 360, 5);
Read(a, 270, 360, 5);
Eq(a.Deaths, 1, "reload while dead: still one");
Read(a, 0, 360, 6);
Eq(a.Deaths, 2, "and the next death after the reload counts");
// Health 0 counted, then the reload before the counter was read: its rise is the same death.
var b = new SessionStats();
b.Reset(S0);
Read(b, 360, 360, 4);
Read(b, 0, 360, 4);
b = Reload(b, t);
Read(b, 0, 360, 5);
Read(b, 270, 360, 5);
Eq(b.Deaths, 1, "reload between the health and the counter: still one");
// Died while the plugin was unloaded: the counter's saved baseline counts it.
var c = new SessionStats();
c.Reset(S0);
Read(c, 360, 360, 4);
c = Reload(c, t);
Read(c, 0, 360, 5);
Read(c, 0, 360, 5);
Read(c, 270, 360, 5);
Eq(c.Deaths, 1, "died during the reload: counted once, from the counter");
// Died and came back while the plugin was unloaded.
var d = new SessionStats();
d.Reset(S0);
Read(d, 360, 360, 4);
d = Reload(d, t);
Read(d, 270, 360, 5);
Eq(d.Deaths, 1, "died and revived during the reload: counted from the counter");
// An engine reload: the vitals start at 0/0 and can read 0/max before the health is seeded.
var e = new SessionStats();
e.Reset(S0);
Read(e, 360, 360, 4);
e = Reload(e, t);
Read(e, 0, 0, 4);
Read(e, 0, 360, 4);
Read(e, 360, 360, 4);
Eq(e.Deaths, 0, "engine reload: 0/max before the health is seeded is no death");
}
// A reload (capture, save text, parse, apply) mid-session gives the same numbers as none.

View file

@ -104,6 +104,17 @@ namespace RynthDefective.Tests
Run("corpses: gone, rotted, at most 20, forget", CorpseGoneAndExpiry);
Run("corpses: the files, this character's and the others'", CorpseStoreFiles);
Run("corpses: rows: places, times, distance and the arrow", CorpseRowText);
Run("quantity: typed numbers, max and half", QtyParse);
Run("quantity: a split leaves one, a give takes up to the stack, the box keeps what was typed", QtyCounts);
Run("quantity: a vendor's price (stacks, notes, rounding, a player's listing)", QtyVendorPrice);
Run("quantity: the most you can buy (money, slots, burden, stock)", QtyVendorMax);
Run("quantity: why a buy can't go, and the engine's refusals in words", QtyVendorRefusals);
Run("quantity: /rdef qty, split, give and buy parsing", QtyCommands);
Run("quantity: split - refusals, the pack, the open chest, the server's answer", QtySplit);
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("store: the quantity box setting; files from before read it on", QtyStore);
}
finally
{

View file

@ -0,0 +1,796 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Quantity;
using RynthCore.PluginSdk;
namespace RynthDefective.Tests
{
// The quantity box (2026-10-30): how many of a stack or of a vendor's item, and Split / Give / Buy
// that many (Model/Quantity.cs, Quantity/QuantityController.cs). The controller runs against a
// scripted world, so every refusal and every answer is checked without the game.
internal static partial class Program
{
private const uint QSack = 0x50000100, QSack2 = 0x50000101, QScarabs = 0x50000200, QGem = 0x50000201, QArrows = 0x50000202,
QNpc = 0x50000300, QOther = 0x50000301, QChest = 0x50000400, QChestStack = 0x50000401, QGround = 0x50000402,
QVendor = 0x50000500, QVScarab = 0x50000501, QVNote = 0x50000502, QVPack = 0x50000503, QVScroll = 0x50000504,
QMonster = 0x50000302;
internal sealed class FakeQtyWorld : IQtyWorld
{
public sealed class Obj
{
public string Name = string.Empty;
public uint Container, Wielder;
public int Stack;
public bool Creature, Monster;
}
public long NowMs { get; set; } = 1_000_000;
public uint PlayerId { get; set; } = Me;
public uint SelectedId { get; set; }
public uint PreviousSelectedId { get; set; }
public uint OpenContainerId { get; set; }
public readonly Dictionary<uint, Obj> Objects = new();
public readonly List<QtyPack> PackList = new();
public bool CanSplit { get; set; } = true;
public bool CanGive { get; set; } = true;
public bool CanTrade { get; set; } = true;
public bool SendFails;
public readonly List<string> Sent = new();
public int RefusalSeq { get; set; }
public uint RefusalError, RefusalEvent, RefusalObject;
public VendorInfo? Vendor;
public readonly List<VendorItem> Items = new();
public uint NextRequest = 40;
public VendorTradeStatus? Status;
public string? BuyRefusedWith;
public int FreeContainers = 3;
public long Burden = -1;
public bool TryGetName(uint id, out string name)
{
name = Objects.TryGetValue(id, out Obj? o) ? o.Name : string.Empty;
return name.Length > 0;
}
public bool Exists(uint id) => Objects.ContainsKey(id);
public bool CanReceive(uint id) => Objects.TryGetValue(id, out Obj? o) && o.Creature && !o.Monster;
public bool TryGetOwner(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
if (!Objects.TryGetValue(id, out Obj? o)) return false;
container = o.Container;
wielder = o.Wielder;
return true;
}
public int StackOf(uint id) => Objects.TryGetValue(id, out Obj? o) ? o.Stack : 0;
public IReadOnlyList<QtyPack> Packs()
{
var list = new List<QtyPack>(PackList);
if (OpenContainerId != 0 && Objects.TryGetValue(OpenContainerId, out Obj? c))
list.Add(new QtyPack(OpenContainerId, c.Name, 120, 30, QtyPackKind.Open));
return list;
}
public bool Split(uint id, uint into, int n)
{
if (SendFails) return false;
Sent.Add($"split {id:X} into {into:X} {n}");
return true;
}
public bool Give(uint id, uint to, int n)
{
if (SendFails) return false;
Sent.Add($"give {id:X} to {to:X} {n}");
return true;
}
public bool LastRefusal(out uint error, out uint eventType, out uint objectId)
{
error = RefusalError;
eventType = RefusalEvent;
objectId = RefusalObject;
return RefusalSeq != 0;
}
public void Refuse(uint error, uint eventType, uint objectId)
{
RefusalSeq++;
RefusalError = error;
RefusalEvent = eventType;
RefusalObject = objectId;
}
public bool TryGetVendor(out VendorInfo info)
{
info = Vendor!;
return CanTrade && Vendor != null;
}
public IReadOnlyList<VendorItem> VendorItems() => Vendor != null ? Items : Array.Empty<VendorItem>();
public uint Buy(uint vendorId, uint itemId, int n)
{
if (BuyRefusedWith != null)
{
Status = new VendorTradeStatus { RequestId = 0, State = VendorTradeState.Refused, Message = BuyRefusedWith, IsBuy = true };
return 0;
}
uint id = NextRequest++;
Sent.Add($"buy {itemId:X} from {vendorId:X} {n}");
Status = new VendorTradeStatus { RequestId = id, State = VendorTradeState.Queued, IsBuy = true, VendorId = vendorId, EntryCount = 1 };
return id;
}
public bool TryGetTradeStatus(out VendorTradeStatus status)
{
status = Status!;
return Status != null;
}
public int FreeContainerSlots() => FreeContainers;
public long FreeBurden() => Burden;
public void Advance(long ms) => NowMs += ms;
}
/// <summary>A character with a main pack (52 free), a sack (14 free), 100 scarabs, a gem, wielded arrows and an NPC nearby.</summary>
private static FakeQtyWorld QWorld()
{
var w = new FakeQtyWorld();
w.PackList.Add(new QtyPack(Me, "Main pack", 102, 50, QtyPackKind.Main));
w.PackList.Add(new QtyPack(QSack, "Sack", 24, 10, QtyPackKind.Side));
w.Objects[Me] = new FakeQtyWorld.Obj { Name = "Me", Creature = true };
w.Objects[QSack] = new FakeQtyWorld.Obj { Name = "Sack", Container = Me };
w.Objects[QScarabs] = new FakeQtyWorld.Obj { Name = "Mana Scarab", Container = QSack, Stack = 100 };
w.Objects[QGem] = new FakeQtyWorld.Obj { Name = "Sunstone", Container = Me, Stack = 1 };
w.Objects[QArrows] = new FakeQtyWorld.Obj { Name = "Arrow", Container = 0, Wielder = Me, Stack = 200 };
w.Objects[QNpc] = new FakeQtyWorld.Obj { Name = "Shopkeeper", Creature = true };
w.Objects[QOther] = new FakeQtyWorld.Obj { Name = "Guard", Creature = true };
w.Objects[QMonster] = new FakeQtyWorld.Obj { Name = "Drudge Skulker", Creature = true, Monster = true };
w.Objects[QGround] = new FakeQtyWorld.Obj { Name = "Pyreal", Container = 0, Stack = 50 };
w.Objects[QChest] = new FakeQtyWorld.Obj { Name = "Chest" };
w.Objects[QChestStack] = new FakeQtyWorld.Obj { Name = "Prismatic Taper", Container = QChest, Stack = 40 };
return w;
}
/// <summary>A vendor (sell rate 1.2) with scarabs (10 each, stacks of 100), a promissory note, a pack and 5 scrolls a player sold.</summary>
private static void QVendorOpen(FakeQtyWorld w, int coins = 1000)
{
w.Vendor = new VendorInfo { VendorId = QVendor, Name = "Shopkeeper", SellRate = 1.2f, BuyRate = 0.8f, PlayerCoins = coins,
AltCurrencyHave = -1, TradingAvailable = true, Generation = 1, ItemCount = 4 };
w.Items.Clear();
w.Items.Add(new VendorItem { ObjectId = QVScarab, Name = "Mana Scarab", ItemType = 0x80, Amount = -1, StackSize = 1, MaxStackSize = 100,
Value = 10, UnitValue = 10, UnitPrice = 12, Burden = 5, Unlimited = true, Stackable = true });
w.Items.Add(new VendorItem { ObjectId = QVNote, Name = "Trade Note (100)", ItemType = VendorQuote.ItemTypePromissoryNote, Amount = -1,
StackSize = 1, MaxStackSize = 100, Value = 100, UnitValue = 100, UnitPrice = 115, Unlimited = true, Stackable = true });
w.Items.Add(new VendorItem { ObjectId = QVPack, Name = "Sack", ItemType = 0x200, Amount = -1, StackSize = 1, MaxStackSize = 0,
Value = 50, UnitValue = 50, UnitPrice = 60, Burden = 20, Unlimited = true, NeedsContainerSlot = true });
w.Items.Add(new VendorItem { ObjectId = QVScroll, Name = "Scroll of Sneak Attack", ItemType = 0x8000, Amount = 5, StackSize = 5, MaxStackSize = 0,
Value = 400, UnitValue = 80, UnitPrice = 96, Burden = 25 });
}
private static (QuantityController C, List<(bool Ok, string Text)> Said) QController()
{
var said = new List<(bool, string)>();
var c = new QuantityController();
c.Report = (ok, text) => said.Add((ok, text));
return (c, said);
}
// ── The rules ───────────────────────────────────────────────────────
private static void QtyParse()
{
Check(QuantityRules.TryParse("25", out QtyAmount a, out _) && a == QtyAmount.Of(25), "25");
Check(QuantityRules.TryParse(" 1,000 ", out a, out _) && a.Number == 1000, "1,000 with a comma");
Check(QuantityRules.TryParse("MAX", out a, out _) && a == QtyAmount.Max, "max");
Check(QuantityRules.TryParse("all", out a, out _) && a == QtyAmount.Max, "all is max");
Check(QuantityRules.TryParse("half", out a, out _) && a == QtyAmount.Half, "half");
Check(QuantityRules.TryParse("1/2", out a, out _) && a == QtyAmount.Half, "1/2 is half");
Check(!QuantityRules.TryParse("0", out _, out string why) && why.Contains("at least 1", StringComparison.Ordinal), "0: at least 1");
Check(!QuantityRules.TryParse("-3", out _, out why) && why.Contains("at least 1", StringComparison.Ordinal), "negative: at least 1");
Check(!QuantityRules.TryParse("99999999", out _, out why) && why.Contains("8,388,607", StringComparison.Ordinal), "too many for one request: the limit said");
Check(!QuantityRules.TryParse("lots", out _, out why) && why.Contains("max or half", StringComparison.Ordinal), "a word: what it takes");
Check(!QuantityRules.TryParse("", out _, out why) && why.StartsWith("How many", StringComparison.Ordinal), "nothing: how many");
Eq(QtyAmount.Of(25).ToString(), "25", "shown as typed");
Eq(QtyAmount.Half.ToString(), "half", "half shown");
Check(QuantityRules.LooksLikeAmount("25") && QuantityRules.LooksLikeAmount("max") && QuantityRules.LooksLikeAmount("-3")
&& !QuantityRules.LooksLikeAmount("Sack") && !QuantityRules.LooksLikeAmount("into"), "what reads as a quantity");
Check(QuantityRules.TryParseLeading("25 into Sack", out QtyAmount? q, out string rest, out _) && q == QtyAmount.Of(25) && rest == "into Sack",
"a quantity, then the rest");
Check(QuantityRules.TryParseLeading("Mana Scarab", out q, out rest, out _) && q == null && rest == "Mana Scarab", "no quantity: all of it is the rest");
Check(QuantityRules.TryParseLeading("", out q, out rest, out _) && q == null && rest.Length == 0, "nothing at all");
Check(!QuantityRules.TryParseLeading("0 Sack", out _, out _, out why) && why.Contains("at least 1", StringComparison.Ordinal), "a wrong quantity first: why");
}
private static void QtyCounts()
{
// Split: one always stays.
Eq(QuantityRules.SplitCount(25, 100), 25, "split 25 of 100");
Eq(QuantityRules.SplitCount(100, 100), 99, "split the whole stack: one stays");
Eq(QuantityRules.SplitCount(500, 100), 99, "more than the stack: clamped");
Eq(QuantityRules.SplitCount(0, 100), 1, "below one: one");
Eq(QuantityRules.SplitCount(5, 1), 0, "one item: no split");
Eq(QuantityRules.SplitCount(1, 2), 1, "a stack of two: one");
Eq(QuantityRules.ForSplit(QtyAmount.Max, 100), 99, "split max: stack - 1");
Eq(QuantityRules.ForSplit(QtyAmount.Half, 100), 50, "split half of 100");
Eq(QuantityRules.ForSplit(QtyAmount.Half, 3), 1, "split half of 3");
Eq(QuantityRules.ForSplit(QtyAmount.Half, 2), 1, "split half of 2");
Eq(QuantityRules.ForSplit(QtyAmount.Max, 1), 0, "split max of one item: nothing");
// Give: up to the whole stack.
Eq(QuantityRules.GiveCount(150, 100), 100, "give more than the stack: the stack");
Eq(QuantityRules.ForGive(QtyAmount.Max, 100), 100, "give max: the whole stack");
Eq(QuantityRules.ForGive(QtyAmount.Half, 7), 3, "give half of 7");
Eq(QuantityRules.ForGive(QtyAmount.Of(1), 1), 1, "give the one item");
// The box: a typed number stays; max and half are of the selection.
Eq(QuantityRules.ForBox(QtyAmount.Of(500), 100), 500, "the box keeps a typed number");
Eq(QuantityRules.ForBox(QtyAmount.Max, 100), 100, "box max: the whole stack");
Eq(QuantityRules.ForBox(QtyAmount.Half, 100), 50, "box half");
Eq(QuantityRules.ForBox(QtyAmount.Half, 1), 1, "half of one is one");
Eq(QuantityRules.ForBox(QtyAmount.Max, 0), 0, "max of nothing");
Eq(QuantityRules.ForBuy(QtyAmount.Of(30), 10), 30, "a buy asks for exactly what was typed (the quote says why not)");
Eq(QuantityRules.ForBuy(QtyAmount.Max, 83), 83, "buy max");
Eq(QuantityRules.ForBuy(QtyAmount.Half, 83), 41, "buy half");
Eq(QuantityRules.ForBuy(QtyAmount.Max, 0), 0, "buy max with nothing affordable");
Eq(QuantityRules.Clamp(7, 0), 1, "clamp with nothing to clamp to");
var (c, _) = QController();
c.Value = 0;
Eq(c.Value, 1, "the box is at least 1");
c.Value = int.MaxValue;
Eq(c.Value, QuantityRules.MaxAmount, "and at most one request");
}
private static VendorQuote Scarabs(long funds = 1000, int freeSlots = 50, long freeBurden = -1) => new()
{
Name = "Mana Scarab", ItemType = 0x80, UnitValue = 10, UnitPrice = 12, ListingValue = 10, UnitBurden = 5, ListingBurden = 5,
MaxStack = 100, Unlimited = true, SellRate = 1.2f, Funds = funds, FreeItemSlots = freeSlots, FreeContainerSlots = 3, FreeBurden = freeBurden,
};
private static void QtyVendorPrice()
{
// Stackable: each created stack is priced on its own (ACE: max(1, ceil(value x rate - 0.1))).
VendorQuote q = Scarabs();
q.Estimate(250, out long cost, out long slots, out long burden);
Eq(cost, 3000L, "250 scarabs: two stacks of 100 (1,200 each) and one of 50 (600)");
Eq(slots, 3L, "three stacks, three slots");
Eq(burden, 1250L, "burden by the unit");
Eq(q.Cost(25), 300L, "25 at 12");
Eq(q.Cost(1), 12L, "one");
Eq(q.PriceLine(25), "300 pyreals · you have 1,000", "the price line");
Eq(q.Cost(0), 0L, "nothing costs nothing");
// Not stackable: one per slot.
var wand = new VendorQuote { Name = "Wand", UnitValue = 50, ListingValue = 50, MaxStack = 0, Unlimited = true, SellRate = 1.15f, Funds = 1000, FreeItemSlots = 10 };
wand.Estimate(3, out cost, out slots, out _);
Eq(cost, 174L, "three wands at ceil(57.5 - 0.1) = 58");
Eq(slots, 3L, "a slot each");
// A promissory note costs 1.15 of its value whatever the vendor's rate.
var note = new VendorQuote { Name = "Trade Note", ItemType = VendorQuote.ItemTypePromissoryNote, UnitValue = 100, MaxStack = 100,
Unlimited = true, SellRate = 2.0f, Funds = 10_000, FreeItemSlots = 10 };
Eq(note.Cost(1), 115L, "a note at 1.15");
// Rounding: never below one, and the -0.1 before the ceiling.
Eq(new VendorQuote { UnitValue = 1, MaxStack = 0, Unlimited = true, SellRate = 0.5f }.Cost(1), 1L, "at least one pyreal");
Eq(new VendorQuote { UnitValue = 9, MaxStack = 0, Unlimited = true, SellRate = 1.1f }.Cost(1), 10L, "9 x 1.1 = 9.9 -> 10");
// A limited listing (another player's sale, handed over whole) costs at least the whole listing.
var scrolls = new VendorQuote { Name = "Scroll", UnitValue = 80, ListingValue = 400, UnitBurden = 5, ListingBurden = 25, MaxStack = 0,
Unlimited = false, Stock = 5, SellRate = 1.0f, Funds = 1000, FreeItemSlots = 10 };
Eq(scrolls.Cost(2), 400L, "two of a limited five: the whole listing's price");
scrolls.Estimate(2, out _, out _, out burden);
Eq(burden, 25L, "and its whole burden");
}
private static void QtyVendorMax()
{
Eq(Scarabs(funds: 1000).MaxBuy(), 83, "1,000 pyreals at 12: 83 (996), not 84 (1,008)");
Eq(Scarabs(funds: 1_000_000, freeSlots: 2).MaxBuy(), 200, "two free slots: two stacks of 100");
Eq(Scarabs(funds: 1_000_000, freeSlots: 0).MaxBuy(), 0, "a full pack: none");
Eq(Scarabs(funds: 11).MaxBuy(), 0, "11 pyreals: not even one");
Eq(Scarabs(funds: 1_000_000, freeSlots: 50, freeBurden: 55).MaxBuy(), 11, "burden 55 at 5 each: 11");
var unknown = Scarabs(funds: -1, freeSlots: -1);
Eq(unknown.MaxBuy(), 100, "nothing known: one full stack");
Eq((unknown with { MaxStack = 0 }).MaxBuy(), 1, "nothing known, not stackable: one");
var scrolls = new VendorQuote { Name = "Scroll", UnitValue = 80, ListingValue = 400, MaxStack = 0, Unlimited = false, Stock = 5,
SellRate = 1.0f, Funds = 100_000, FreeItemSlots = 50 };
Eq(scrolls.MaxBuy(), 5, "the vendor's five");
Eq((scrolls with { Stock = 0 }).MaxBuy(), 0, "none left");
var big = Scarabs(funds: long.MaxValue / 4, freeSlots: int.MaxValue);
Eq(big.MaxBuy(), QuantityRules.MaxAmount, "no limit but one request's");
}
private static void QtyVendorRefusals()
{
VendorQuote q = Scarabs(funds: 1000);
Eq(q.Refusal(25), null, "25 fit");
Check(q.Refusal(0)!.Contains("at least 1", StringComparison.Ordinal), "zero");
string? why = q.Refusal(100);
Check(why != null && why.StartsWith("Not enough pyreals: 100 Mana Scarab cost 1,200, you have 1,000", StringComparison.Ordinal)
&& why.Contains("you can buy 83", StringComparison.Ordinal), $"not enough pyreals, with how many can be bought: {why}");
why = Scarabs(funds: 1_000_000, freeSlots: 0).Refusal(10);
Check(why != null && why.StartsWith("The pack is full", StringComparison.Ordinal), $"the pack is full: {why}");
why = Scarabs(funds: 1_000_000, freeSlots: 1).Refusal(250);
Check(why != null && why.StartsWith("Not enough room in your packs: 250 Mana Scarab need 3 free slots, you have 1", StringComparison.Ordinal)
&& why.Contains("you can buy 100", StringComparison.Ordinal), $"not enough room: {why}");
why = Scarabs(funds: 1_000_000, freeBurden: 10).Refusal(5);
Check(why != null && why.StartsWith("Too heavy", StringComparison.Ordinal) && why.Contains("you can buy 2", StringComparison.Ordinal), $"too heavy: {why}");
var pack = new VendorQuote { Name = "Sack", UnitValue = 50, MaxStack = 0, Unlimited = true, SellRate = 1f, Funds = 1000,
FreeItemSlots = 50, FreeContainerSlots = 0, NeedsContainerSlot = true };
why = pack.Refusal(1);
Check(why != null && why.StartsWith("No room for another pack", StringComparison.Ordinal), $"no container slot: {why}");
Eq((pack with { FreeContainerSlots = 2 }).Refusal(2), null, "two packs in two container slots");
var scrolls = new VendorQuote { Name = "Scroll", UnitValue = 80, ListingValue = 400, MaxStack = 0, Unlimited = false, Stock = 5,
SellRate = 1.0f, Funds = 100_000, FreeItemSlots = 50 };
Eq(scrolls.Refusal(25), "The vendor has only 5 Scroll.", "more than the vendor has");
Eq((scrolls with { Stock = 0 }).Refusal(1), "The vendor has no Scroll left.", "none left");
Check(Scarabs(funds: -1, freeSlots: -1).Refusal(5000) == null, "unknown money and room aren't held against it (the engine checks)");
// The vendor's own currency.
var info = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyWcid = 1234, AltCurrencyName = "Ancient Coin", AltCurrencyHave = 3, PlayerCoins = 99_999 };
var item = new VendorItem { ObjectId = QVScarab, Name = "Relic", UnitValue = 2, Value = 2, StackSize = 1, MaxStackSize = 0, Amount = -1, Unlimited = true };
VendorQuote alt = VendorQuote.From(info, item, 10, 2, -1);
Eq(alt.Currency, "Ancient Coin", "the vendor's currency by name");
Eq(alt.Funds, 3L, "counted in your packs, not pyreals");
Check(alt.Refusal(2)!.StartsWith("Not enough Ancient Coin: 2 Relic cost 4, you have 3", StringComparison.Ordinal), "not enough of it");
var pyInfo = new VendorInfo { VendorId = QVendor, SellRate = 1f, AltCurrencyHave = -1, PlayerCoins = 99_999 };
VendorQuote py = VendorQuote.From(pyInfo, item, 10, 2, -1);
Eq(py.Currency, "pyreals", "a pyreal vendor");
Eq(py.Funds, 99_999L, "your pyreals");
var stacked = new VendorItem { Name = "Bundle", StackSize = 5, Burden = 50, Value = 100, UnitValue = 20, Amount = 2 };
VendorQuote sq = VendorQuote.From(info, stacked, 10, 2, -1);
Eq(sq.UnitBurden, 10, "burden per unit from the listed stack");
Check(!sq.Unlimited && sq.Stock == 2, "a limited listing's stock");
// The engine's refusals, in the player's words.
Check(QtyReplies.VendorRefusal("costs 300 pyreals, you have 200").StartsWith("Not enough pyreals: it costs 300 pyreals, you have 200", StringComparison.Ordinal), "engine: pyreals");
Check(QtyReplies.VendorRefusal("costs 3 Ancient Coin, you have 1").StartsWith("Not enough Ancient Coin", StringComparison.Ordinal), "engine: the vendor's currency");
Check(QtyReplies.VendorRefusal("needs 3 free pack slots, you have 0").StartsWith("The pack is full", StringComparison.Ordinal), "engine: the pack is full");
Check(QtyReplies.VendorRefusal("needs 3 free pack slots, you have 1").StartsWith("Not enough room", StringComparison.Ordinal), "engine: not enough room");
Check(QtyReplies.VendorRefusal("needs 1 free container slots, you have 0").StartsWith("No room for another pack", StringComparison.Ordinal), "engine: container slots");
Check(QtyReplies.VendorRefusal("adds 500 burden, you can carry 20 more").StartsWith("Too heavy", StringComparison.Ordinal), "engine: burden");
Eq(QtyReplies.VendorRefusal("vendor only has 5 of 0x80001234, asked for 25"), "The vendor doesn't have that many.", "engine: stock");
Check(QtyReplies.VendorRefusal("no vendor open").Contains("closed", StringComparison.Ordinal), "engine: no vendor");
Check(QtyReplies.VendorRefusal("vendor window is closed").Contains("closed", StringComparison.Ordinal), "engine: closed before sending");
Eq(QtyReplies.VendorRefusal("0x80001234 is not on this vendor's list"), "The vendor doesn't sell that any more.", "engine: not on the list");
Eq(QtyReplies.VendorRefusal("4 requests already waiting"), QtyReplies.VendorBusy, "engine: busy");
Eq(QtyReplies.VendorRefusal("something new"), "The vendor didn't sell it: something new.", "engine: anything else as it is");
Eq(QtyReplies.VendorRefusal(null), "The vendor didn't sell it.", "engine: no message");
}
// ── The commands ────────────────────────────────────────────────────
private static void QtyCommands()
{
DefCommand c = DefCommandParser.Parse("qty");
Check(c.Verb == DefVerb.Quantity && c.Amount == null, "qty alone: say it");
c = DefCommandParser.Parse("qty 25");
Check(c.Verb == DefVerb.Quantity && c.Amount == QtyAmount.Of(25), "qty 25");
Check(DefCommandParser.Parse("quantity max").Amount == QtyAmount.Max, "quantity max");
c = DefCommandParser.Parse("qty 0");
Check(c.Verb == DefVerb.Error && c.Error.Contains("Usage", StringComparison.Ordinal), "qty 0: why and the usage");
c = DefCommandParser.Parse("qty 25 30");
Check(c.Verb == DefVerb.Error, "qty takes one quantity");
c = DefCommandParser.Parse("split");
Check(c.Verb == DefVerb.Split && c.Amount == null && c.Text.Length == 0, "split: the box's number into the chosen pack");
c = DefCommandParser.Parse("split 25 into Sack");
Check(c.Verb == DefVerb.Split && c.Amount == QtyAmount.Of(25) && c.Text == "Sack", "split 25 into Sack");
c = DefCommandParser.Parse("split half to main");
Check(c.Amount == QtyAmount.Half && c.Text == "main", "split half to main");
c = DefCommandParser.Parse("split into Inventory Bag");
Check(c.Amount == null && c.Text == "Inventory Bag", "split into a pack whose name starts like 'in'");
Check(DefCommandParser.Parse("split -2").Verb == DefVerb.Error, "split -2: why");
c = DefCommandParser.Parse("give 10");
Check(c.Verb == DefVerb.Give && c.Amount == QtyAmount.Of(10), "give 10");
Check(DefCommandParser.Parse("give").Amount == null, "give: the box's number");
c = DefCommandParser.Parse("give someone");
Check(c.Verb == DefVerb.Error && c.Error.Contains("Usage", StringComparison.Ordinal), "give a name: the usage (it goes to the last one selected)");
c = DefCommandParser.Parse("buy 25 Mana Scarab");
Check(c.Verb == DefVerb.Buy && c.Amount == QtyAmount.Of(25) && c.Text == "Mana Scarab", "buy 25 Mana Scarab");
c = DefCommandParser.Parse("buy Mana Scarab");
Check(c.Verb == DefVerb.Buy && c.Amount == null && c.Text == "Mana Scarab", "buy by name, the box's number");
Check(DefCommandParser.Parse("buy 25 of Mana Scarab").Text == "Mana Scarab", "buy 25 of ...");
Check(DefCommandParser.Parse("buy max").Amount == QtyAmount.Max && DefCommandParser.Parse("buy").Amount == null, "buy max, buy");
Check(DefCommandParser.Parse("buy 0 Mana Scarab").Verb == DefVerb.Error, "buy 0: why");
Check(DefCommandParser.Usage.Contains("qty", StringComparison.Ordinal) && DefCommandParser.Usage.Contains("buy", StringComparison.Ordinal), "in the usage");
}
// ── Split ───────────────────────────────────────────────────────────
private static void QtySplit()
{
var w = QWorld();
var (c, said) = QController();
// What can't be split, each with its reason.
c.Split(w, null, "");
Eq(said.Last(), (false, QtyReplies.NothingSelected), "nothing selected");
w.SelectedId = QGem;
c.Split(w, null, "");
Eq(said.Last(), (false, "That's not a stack: Sunstone is a single item."), "a single item");
w.SelectedId = QArrows;
c.Split(w, null, "");
Eq(said.Last(), (false, "Arrow is wielded: take it off first."), "wielded arrows");
w.SelectedId = QGround;
c.Split(w, null, "");
Eq(said.Last(), (false, "Pyreal isn't in your packs or in the container you have open."), "a stack on the ground");
Eq(w.Sent.Count, 0, "nothing sent for any of them");
// 25 of 100 into the main pack, answered by the smaller stack.
w.SelectedId = QScarabs;
c.Value = 25;
c.Split(w, null, "");
Eq(w.Sent.Last(), $"split {QScarabs:X} into {Me:X} 25", "the box's 25 into the main pack");
Check(c.Busy, "waiting for the game");
c.Split(w, null, "");
Eq(said.Last(), (false, QtyReplies.Busy), "one at a time");
w.Advance(300);
c.Tick(w);
Check(c.Busy, "no change yet");
w.Objects[QScarabs].Stack = 75;
c.Tick(w);
Eq(said.Last(), (true, "Split 25 Mana Scarab into the main pack."), "the answer");
Check(!c.Busy, "done");
Check(c.StatusAt(w.NowMs) is { Ok: true }, "the window's line says it");
Check(c.StatusAt(w.NowMs + QuantityController.StatusShownMs) == null, "and stops after a while");
// More than the stack: one stays.
c.Value = 500;
c.Split(w, null, "");
Eq(w.Sent.Last(), $"split {QScarabs:X} into {Me:X} 74", "500 of 75: 74 (one stays)");
w.Objects[QScarabs].Stack = 1;
c.Tick(w);
Eq(said.Last(), (true, "Split 74 Mana Scarab into the main pack."), "74 split");
w.Objects[QScarabs].Stack = 100;
// A typed amount and a named pack.
c.Split(w, QtyAmount.Half, "sack");
Eq(w.Sent.Last(), $"split {QScarabs:X} into {QSack:X} 50", "half into the sack (by name, any case)");
w.Objects[QScarabs].Stack = 50;
c.Tick(w);
Eq(said.Last(), (true, "Split 50 Mana Scarab into Sack."), "into Sack");
w.Objects[QScarabs].Stack = 100;
c.Split(w, QtyAmount.Of(5), "Bag");
Eq(said.Last(), (false, "No pack called 'Bag'. Your packs: Main pack, Sack."), "no such pack: the packs");
c.Split(w, QtyAmount.Of(5), "open");
Check(!said.Last().Ok && said.Last().Text.StartsWith("No chest", StringComparison.Ordinal), "no container open");
// The pack chosen in the window; a full one refuses before anything is sent.
c.Into = QSack;
c.Split(w, QtyAmount.Of(5), "");
Eq(w.Sent.Last(), $"split {QScarabs:X} into {QSack:X} 5", "the window's pack");
c.Tick(w); // not answered yet
w.Advance(QuantityController.SplitAnswerMs);
c.Tick(w);
Eq(said.Last(), (false, QtyReplies.NoAnswer("split")), "no answer in time");
c.Into = 0;
w.PackList[0] = new QtyPack(Me, "Main pack", 102, 102, QtyPackKind.Main);
int sent = w.Sent.Count;
c.Split(w, QtyAmount.Of(5), "");
Check(!said.Last().Ok && said.Last().Text.StartsWith("The main pack is full.", StringComparison.Ordinal), "the main pack is full");
Eq(w.Sent.Count, sent, "nothing sent to a full pack");
c.Into = 0xDEAD; // a pack that's gone: the main pack
c.Split(w, QtyAmount.Of(5), "");
Check(said.Last().Text.StartsWith("The main pack is full.", StringComparison.Ordinal), "a gone pack is the main pack");
w.PackList[0] = new QtyPack(Me, "Main pack", 102, 50, QtyPackKind.Main);
c.Into = 0;
// From the open chest into the pack.
w.OpenContainerId = QChest;
w.SelectedId = QChestStack;
c.Split(w, QtyAmount.Of(10), "");
Eq(w.Sent.Last(), $"split {QChestStack:X} into {Me:X} 10", "10 of the chest's 40 into the main pack");
w.Objects[QChestStack].Stack = 30;
c.Tick(w);
Check(said.Last().Ok, "taken");
w.SelectedId = QScarabs;
c.Split(w, QtyAmount.Of(10), "chest");
Eq(w.Sent.Last(), $"split {QScarabs:X} into {QChest:X} 10", "and 10 of yours into the open chest");
w.Objects[QScarabs].Stack = 90;
c.Tick(w);
Eq(said.Last(), (true, "Split 10 Mana Scarab into Chest."), "into the chest");
w.Objects[QScarabs].Stack = 100;
w.OpenContainerId = 0;
// The server's refusals: one naming the item at once; another item's is not ours; any other after a grace.
c.Split(w, QtyAmount.Of(5), "");
w.Refuse(0x0001, 0x00A0, QScarabs);
c.Tick(w);
Eq(said.Last(), (false, "The server refused the split (error 0x0001): nothing changed."), "refused, naming the item");
c.Split(w, QtyAmount.Of(5), "");
w.Refuse(0x0001, 0x00A0, QGem);
c.Tick(w);
Check(c.Busy, "another item's refusal isn't ours");
w.Refuse(0x0402, 0x028A, 0);
c.Tick(w);
Check(c.Busy, "a refusal that names nothing waits for the grace");
w.Advance(QuantityController.RefusalGraceMs);
c.Tick(w);
Eq(said.Last(), (false, "The server refused the split (error 0x0402): nothing changed."), "then it's the split's");
// Can't send, or no engine call.
w.SendFails = true;
c.Split(w, QtyAmount.Of(5), "");
Eq(said.Last(), (false, QtyReplies.NotSent("split")), "the send failed");
Check(!c.Busy, "nothing waits");
w.SendFails = false;
w.CanSplit = false;
c.Split(w, QtyAmount.Of(5), "");
Eq(said.Last(), (false, QtyReplies.NoSplitApi), "an engine without the call");
w.CanSplit = true;
// A vendor's item isn't split.
QVendorOpen(w);
w.SelectedId = QVScarab;
c.Split(w, null, "");
Check(!said.Last().Ok && said.Last().Text.Contains("Buy", StringComparison.Ordinal), "a vendor's item: Buy");
}
// ── Give ────────────────────────────────────────────────────────────
private static void QtyGive()
{
var w = QWorld();
var (c, said) = QController();
w.SelectedId = QScarabs;
c.Tick(w);
c.Give(w, QtyAmount.Of(10));
Eq(said.Last(), (false, QtyReplies.NoGiveTarget), "nobody selected before: who to");
// Select the NPC, then the stack: the NPC is the target.
w.SelectedId = QNpc;
c.Tick(w);
w.SelectedId = Me; // selecting yourself doesn't change it
c.Tick(w);
w.SelectedId = QMonster; // nor does a monster selected in a fight
c.Tick(w);
w.SelectedId = QScarabs;
c.Tick(w);
Check(c.TryGiveTarget(w, QScarabs, out uint to, out string toName) && to == QNpc && toName == "Shopkeeper", "the last creature selected");
c.Give(w, QtyAmount.Of(10));
Eq(w.Sent.Last(), $"give {QScarabs:X} to {QNpc:X} 10", "10 to the NPC");
w.Objects[QScarabs].Stack = 90;
c.Tick(w);
Eq(said.Last(), (true, "Gave 10 Mana Scarab to Shopkeeper."), "given");
// The whole stack goes as "all of it" (0), and is answered by the item leaving your packs.
c.Give(w, QtyAmount.Max);
Eq(w.Sent.Last(), $"give {QScarabs:X} to {QNpc:X} 0", "the whole stack: amount 0");
w.Objects.Remove(QScarabs);
c.Tick(w);
Eq(said.Last(), (true, "Gave 90 Mana Scarab to Shopkeeper."), "all 90 given");
w.Objects[QScarabs] = new FakeQtyWorld.Obj { Name = "Mana Scarab", Container = QSack, Stack = 100 };
// More than the stack: the stack.
c.Value = 999;
c.Give(w, null);
Eq(w.Sent.Last(), $"give {QScarabs:X} to {QNpc:X} 0", "999 of 100: the stack");
w.Objects[QScarabs].Container = QNpc;
c.Tick(w);
Check(said.Last().Ok, "it left your packs");
w.Objects[QScarabs].Container = QSack;
// No answer: the server may walk you there first, so it waits longer.
c.Give(w, QtyAmount.Of(1));
w.Advance(QuantityController.SplitAnswerMs);
c.Tick(w);
Check(c.Busy, "a give waits longer than a split");
w.Advance(QuantityController.GiveAnswerMs);
c.Tick(w);
Eq(said.Last(), (false, QtyReplies.NoAnswer("give")), "then gives up");
// Refusals before sending.
w.SelectedId = QChestStack;
w.OpenContainerId = QChest;
c.Give(w, null);
Eq(said.Last(), (false, "Prismatic Taper isn't in your packs: pick it up first."), "not yours yet");
w.SelectedId = QArrows;
c.Give(w, null);
Eq(said.Last(), (false, "Arrow is wielded: take it off first."), "wielded");
w.SelectedId = QGem;
c.Give(w, null);
Eq(w.Sent.Last(), $"give {QGem:X} to {QNpc:X} 0", "a single item can be given (all of it)");
w.Objects.Remove(QGem);
c.Tick(w);
Check(said.Last().Ok, "given");
// The target gone: AC's previous selection if it's a creature; else nobody.
var (c2, said2) = QController();
w.SelectedId = QScarabs;
w.PreviousSelectedId = QOther;
Check(c2.TryGiveTarget(w, QScarabs, out to, out toName) && to == QOther && toName == "Guard", "AC's previous selection");
w.PreviousSelectedId = QSack;
Check(!c2.TryGiveTarget(w, QScarabs, out _, out _), "a pack isn't someone to give to");
w.PreviousSelectedId = QMonster;
Check(!c2.TryGiveTarget(w, QScarabs, out _, out _), "nor is a monster");
w.SelectedId = QNpc;
c2.Tick(w);
w.SelectedId = QScarabs;
w.Objects.Remove(QNpc);
Check(!c2.TryGiveTarget(w, QScarabs, out _, out _), "the NPC is gone");
w.Objects[QNpc] = new FakeQtyWorld.Obj { Name = "Shopkeeper", Creature = true };
Check(c2.TryGiveTarget(w, QScarabs, out _, out _), "back in view");
w.Advance(QuantityController.GiveTargetMs);
Check(!c2.TryGiveTarget(w, QScarabs, out _, out _), "forgotten after a while");
w.CanGive = false;
c2.Give(w, null);
Eq(said2.Last(), (false, QtyReplies.NoGiveApi), "an engine without the call");
}
// ── Buy ─────────────────────────────────────────────────────────────
private static void QtyBuy()
{
var w = QWorld();
var (c, said) = QController();
c.Buy(w, QtyAmount.Of(25), "");
Eq(said.Last(), (false, QtyReplies.NoVendor), "no vendor open");
w.CanTrade = false;
c.Buy(w, QtyAmount.Of(25), "");
Eq(said.Last(), (false, QtyReplies.NoTradeApi), "an engine without vendor trading");
w.CanTrade = true;
QVendorOpen(w, coins: 1000);
w.SelectedId = QScarabs; // your own stack, not the vendor's
c.Buy(w, QtyAmount.Of(25), "");
Eq(said.Last(), (false, QtyReplies.NoVendorItem), "select the vendor's item");
// 25 of the selected scarabs: the price checked, the request sent, the answer said.
w.SelectedId = QVScarab;
c.Value = 25;
c.Buy(w, null, "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 25", "the box's 25");
Check(c.Busy, "waiting");
c.Tick(w);
Check(c.Busy, "queued is still waiting");
w.Status = new VendorTradeStatus { RequestId = 40, 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, with what it cost");
// Not enough pyreals: refused before anything is sent, with how many can be bought.
int sent = w.Sent.Count;
c.Buy(w, QtyAmount.Of(100), "");
Check(!said.Last().Ok && said.Last().Text.StartsWith("Not enough pyreals", StringComparison.Ordinal)
&& said.Last().Text.Contains("you can buy 83", StringComparison.Ordinal), $"not enough pyreals: {said.Last().Text}");
Eq(w.Sent.Count, sent, "nothing sent");
// max: the most you can buy.
c.Buy(w, QtyAmount.Max, "");
Eq(w.Sent.Last(), $"buy {QVScarab:X} from {QVendor:X} 83", "buy max: 83");
w.Status = new VendorTradeStatus { RequestId = 41, State = VendorTradeState.Refused, Message = "costs 996 pyreals, you have 990" };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("Not enough pyreals: it costs 996", StringComparison.Ordinal), "the engine's own refusal, in words");
// By name: whole, start, part; several or none ask again.
c.Buy(w, QtyAmount.Of(2), "trade note");
Eq(w.Sent.Last(), $"buy {QVNote:X} from {QVendor:X} 2", "by its whole name");
w.Status = new VendorTradeStatus { RequestId = 42, State = VendorTradeState.Done, Result = VendorTradeResult.AnsweredNoRefresh };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.Contains("the server said no", StringComparison.Ordinal), "the server answered without selling");
c.Buy(w, QtyAmount.Of(1), "Scroll");
Eq(w.Sent.Last(), $"buy {QVScroll:X} from {QVendor:X} 1", "by the start of its name");
w.Status = new VendorTradeStatus { RequestId = 43, State = VendorTradeState.Done, Result = VendorTradeResult.TimedOut };
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("No answer from the vendor", StringComparison.Ordinal), "the engine's time-out");
w.Items.Add(new VendorItem { ObjectId = 0x50000599, Name = "Mana Stone", Amount = -1, Unlimited = true, UnitValue = 5, Value = 5, StackSize = 1 });
c.Buy(w, QtyAmount.Of(1), "Mana");
Check(!said.Last().Ok && said.Last().Text.Contains("type more of the name", StringComparison.Ordinal), $"several match: {said.Last().Text}");
c.Buy(w, QtyAmount.Of(1), "Dragon Egg");
Eq(said.Last(), (false, "The vendor doesn't sell 'Dragon Egg'."), "not sold here");
// The vendor's stock and the pack's room.
c.Buy(w, QtyAmount.Of(6), "Scroll of Sneak Attack");
Eq(said.Last(), (false, "The vendor has only 5 Scroll of Sneak Attack."), "only five");
w.FreeContainers = 0;
c.Buy(w, QtyAmount.Of(1), "Sack");
Check(!said.Last().Ok && said.Last().Text.StartsWith("No room for another pack", StringComparison.Ordinal), "no container slot for a pack");
w.FreeContainers = 3;
w.PackList[0] = new QtyPack(Me, "Main pack", 102, 102, QtyPackKind.Main);
w.PackList[1] = new QtyPack(QSack, "Sack", 24, 24, QtyPackKind.Side);
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
Check(!said.Last().Ok && said.Last().Text.StartsWith("The pack is full", StringComparison.Ordinal), $"the pack is full: {said.Last().Text}");
w.PackList[0] = new QtyPack(Me, "Main pack", 102, 50, QtyPackKind.Main);
w.PackList[1] = new QtyPack(QSack, "Sack", 24, 10, QtyPackKind.Side);
// The engine refuses at once (0): its reason; another plugin's trade after ours; no answer.
w.BuyRefusedWith = "vendor window is closed";
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
Check(!said.Last().Ok && said.Last().Text.Contains("closed", StringComparison.Ordinal), "refused at once: why");
w.BuyRefusedWith = null;
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
w.Status = new VendorTradeStatus { RequestId = 99, State = VendorTradeState.Queued };
c.Tick(w);
Check(said.Last().Text.Contains("another trade followed", StringComparison.Ordinal), "another trade's status replaced ours");
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
w.Status = null;
w.Advance(QuantityController.BuyAnswerMs);
c.Tick(w);
Check(!said.Last().Ok && said.Last().Text.StartsWith("No answer about 1 Mana Scarab", StringComparison.Ordinal), "no answer at all");
// A vendor RynthCore can't read, or one with a trade going.
w.Vendor = new VendorInfo { VendorId = QVendor, SellRate = 1.2f, PlayerCoins = 1000, TradingAvailable = false };
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
Eq(said.Last(), (false, QtyReplies.VendorUnreadable), "a vendor the engine can't read");
w.Vendor = new VendorInfo { VendorId = QVendor, SellRate = 1.2f, PlayerCoins = 1000, TradingAvailable = true, TradeInFlight = true };
c.Buy(w, QtyAmount.Of(1), "Mana Scarab");
Eq(said.Last(), (false, QtyReplies.VendorBusy), "a trade still going");
}
// ── The box: /rdef qty and the window's view ────────────────────────
private static void QtyBoxAndView()
{
var w = QWorld();
var (c, said) = QController();
c.SetBox(w, null);
Eq(said.Last(), (true, "Quantity 1."), "/rdef qty: the number");
c.SetBox(w, QtyAmount.Max);
Eq(said.Last(), (false, QtyReplies.MaxNeedsSelection), "max of nothing: why");
c.SetBox(w, QtyAmount.Of(25));
Eq(c.Value, 25, "set");
w.SelectedId = QScarabs;
c.SetBox(w, QtyAmount.Half);
Eq(c.Value, 50, "half of the selected 100");
Eq(said.Last(), (true, "Quantity 50 (the selected Mana Scarab: a stack of 100; a split takes up to 99)."), "said with the stack");
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 100, "max: the whole stack");
c.SetBox(w, QtyAmount.Of(500));
Eq(c.Value, 500, "a typed number stays (each action clamps)");
QVendorOpen(w, coins: 1000);
w.SelectedId = QVScarab;
c.SetBox(w, QtyAmount.Max);
Eq(c.Value, 83, "max of a vendor's item: the most you can buy");
Check(said.Last().Text.Contains("you can buy 83", StringComparison.Ordinal) && said.Last().Text.Contains("996 pyreals", StringComparison.Ordinal), $"said with the price: {said.Last().Text}");
QVendorOpen(w, coins: 5);
c.SetBox(w, QtyAmount.Max);
Check(!said.Last().Ok && said.Last().Text.StartsWith("Not enough pyreals", StringComparison.Ordinal), "max with nothing affordable: why");
// The window's view: only a stack or a vendor's item.
w.Vendor = null;
w.SelectedId = 0;
Check(c.View(w) == null, "nothing selected: no box");
w.SelectedId = QGem;
Check(c.View(w) == null, "a single item: no box");
w.SelectedId = QNpc;
Check(c.View(w) == null, "a creature: no box");
w.SelectedId = QGround;
Check(c.View(w) == null, "a stack on the ground: no box (the split command still says why)");
w.SelectedId = QScarabs;
w.OpenContainerId = QChest;
QuantityView? v = c.View(w);
Check(v != null && v.Subject.Mode == QtyMode.Stack && v.Subject.Where == QtyWhere.Carried && v.Subject.Stack == 100, "a stack in the sack");
Eq(string.Join(", ", v!.Targets.Select(t => t.Label)), "Main pack, Sack, Chest (open)", "the packs, the open chest last");
Eq(v.TargetIndex, 0, "the main pack first");
Eq(v.Target!.Value.Free, 52, "its free slots");
c.Into = QChest;
Eq(c.View(w)!.TargetIndex, 2, "the chosen pack");
c.Into = 0;
w.SelectedId = QChestStack;
Eq(c.View(w)!.Subject.Where, QtyWhere.Open, "a stack in the open chest");
w.SelectedId = QArrows;
Eq(c.View(w)!.Subject.Where, QtyWhere.Wielded, "wielded arrows show the box (and why it can't split)");
QVendorOpen(w);
w.SelectedId = QVScarab;
v = c.View(w);
Check(v != null && v.Subject.Mode == QtyMode.Vendor && v.Subject.MaxBuy == 83 && v.Subject.Quote != null && v.Targets.Length == 0,
"a vendor's item: its price and max, no packs");
Eq(v!.Subject.BoxMax, 83, "the box's max is the most you can buy");
c.Reset();
Check(c.Into == 0 && !c.Busy && c.StatusAt(w.NowMs) == null, "logout forgets the action, the pack and the line");
}
private static void QtyStore()
{
var store = new DefStore(System.IO.Path.Combine(_temp, "qty"));
var d = new DefData();
Check(d.Settings.QuantityBox, "on by default");
d.Settings.QuantityBox = false;
Check(store.Save("Qty Server", "Qty Test", d) == null, "saved");
Check(!store.Load("Qty Server", "Qty Test", out _).Settings.QuantityBox, "off read back");
string path = store.PathFor("Qty Server", "Qty Old");
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
System.IO.File.WriteAllText(path, "{\"version\":1,\"settings\":{\"slotCount\":8}}");
Check(store.Load("Qty Server", "Qty Old", out _).Settings.QuantityBox, "a file from before: on");
}
}
}

View file

@ -83,7 +83,8 @@ namespace RynthDefective.Tests
private static void ReplyEveryVerb()
{
// Wrong words: the parser's error is the reply, with an example or the usage.
string[] wrong = { "use", "set", "set x", "set 0", "spell 3", "spell", "clear", "clear x", "bind 3", "bind", "unbind", "unbind x", "slots", "slots 99" };
string[] wrong = { "use", "set", "set x", "set 0", "spell 3", "spell", "clear", "clear x", "bind 3", "bind", "unbind", "unbind x", "slots", "slots 99",
"qty 0", "qty lots", "split 0", "give someone", "give -1", "buy 0 Mana Scarab" };
foreach (string w in wrong)
{
DefCommand c = DefCommandParser.Parse(w);
@ -102,6 +103,8 @@ namespace RynthDefective.Tests
("set 2", DefVerb.Set), ("spell 3 Heal Self VI", DefVerb.Spell), ("clear 4", DefVerb.Clear),
("bind 3 F9", DefVerb.Bind), ("unbind 3", DefVerb.Unbind), ("slots 12", DefVerb.Slots),
("Stamina Kit", DefVerb.Use), ("corpses", DefVerb.Corpses), ("corpses clear", DefVerb.Corpses),
("qty", DefVerb.Quantity), ("qty 25", DefVerb.Quantity), ("split", DefVerb.Split), ("split 25 into Sack", DefVerb.Split),
("give 10", DefVerb.Give), ("buy 25 Mana Scarab", DefVerb.Buy), ("buy max", DefVerb.Buy),
};
var seen = new HashSet<DefVerb>();
foreach (var (typed, verb) in right)

View file

@ -11,7 +11,9 @@
stance that follows it, RynthAi's macro, refusals and time-outs), and that the windows'
display lists - icons and image buttons included - are accepted by the engine's own parser
(RynthCore src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the
sibling RynthCore checkout) and that clicks reach the code that drew the button.
sibling RynthCore checkout) and that clicks reach the code that drew the button; the quantity box
(counts, max and half, a vendor's price and the most you can buy, every refusal, split / give / buy
against a scripted world).
Nothing native is loaded: no AC, no ImGui context. Files go to a temp folder, never C:\Games.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->