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

@ -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)
-->