Snapshot for release 2026.10.22.2 (internal e613280)

This commit is contained in:
Tom Bohar 2026-10-22 16:42:33 -04:00
commit 893973d0dd
16 changed files with 871 additions and 188 deletions

249
GameTests/RynthSelfTest.af Normal file
View file

@ -0,0 +1,249 @@
~~ RynthSelfTest: RynthAi tests itself in game (2026-10-22). Load with /ra meta load RynthSelfTest and
~~ start the macro (/ra start); scripts\Run-GameTest.ps1 in RynthCore does both and reads the results.
~~ Each check saves rt_<check> = PASS / FAIL / SKIP and rt_<check>_why in this character's
~~ RynthAi\pvars\<name>.txt, and says it in chat. rt_status is RUNNING, then DONE.
~~ It turns Combat, Buffing, Looting and Nav on and off as it goes and puts them back at the end.
~~ Missile crafting is tested only with arrowhead and shaft bundles in the pack and no melee weapon
~~ or wand in hand. To test MAKING ammo, carry no finished ammo (only what is wielded, which the
~~ test takes off): with loose ammo in the pack RynthAi just puts that back on.
~~ Source: RynthSuite GameTests/RynthSelfTest.af. Indent with tabs only; RynthAiHostTests (SelfTestMetaTests) parses and plays it.
STATE: {Default} ~~ {
IF: Always
DO: DoAll
GetOpt {EnableCombat} {rt_o_combat}
GetOpt {EnableBuffing} {rt_o_buff}
GetOpt {EnableLooting} {rt_o_loot}
GetOpt {EnableNav} {rt_o_nav}
SetOpt {EnableCombat} {False}
SetOpt {EnableBuffing} {False}
SetOpt {EnableLooting} {False}
SetOpt {EnableNav} {False}
DoExpr {setpvar[rt_status,`RUNNING`]}
DoExpr {setpvar[rt_started,getunixtime[]]}
DoExpr {setpvar[rt_buff,`PENDING`]}
DoExpr {setpvar[rt_fight,`PENDING`]}
DoExpr {setpvar[rt_loot,`PENDING`]}
DoExpr {setpvar[rt_craft,`PENDING`]}
DoExpr {setpvar[rt_buff_why,`-`]}
DoExpr {setpvar[rt_fight_why,`-`]}
DoExpr {setpvar[rt_loot_why,`-`]}
DoExpr {setpvar[rt_craft_why,`-`]}
DoExpr {setpvar[rt_meta,`PASS`]}
DoExpr {setpvar[rt_meta_why,`the meta loaded and runs; expressions and saved variables work`]}
DoExpr {echo[`[RynthTest] started: buffing, a kill, looting, missile crafting (10 minutes at most)`,1]}
IF: SecsInStateGE 3
DO: SetState {T1 Buff}
~~ }
STATE: {T1 Buff} ~~ {
IF: Always
DO: DoAll
DoExpr {setvar[rt_settled,0]}
DoExpr {setvar[rt_t,getunixtime[]]}
SetOpt {EnableBuffing} {True}
Chat {/ra buff force}
IF: All
ChatMatch {^\[RynthAi\] Force Rebuff Complete\.}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_buff,`PASS`]}
DoExpr {setpvar[rt_buff_why,`a force rebuff finished in `+cstr[getunixtime[]-getvar[rt_t]]+` s`]}
DoExpr {echo[`[RynthTest] PASS buffing: `+getpvar[rt_buff_why],1]}
SetState {T2 Fight}
IF: All
ChatCapture {^\[RynthAi\] (?<msg>(Sequence cancelled|Can't enter Magic mode|Buff stance wedged).*)} {}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_buff,`FAIL`]}
DoExpr {setpvar[rt_buff_why,getvar[capturegroup_msg]]}
DoExpr {echo[`[RynthTest] FAIL buffing: `+getpvar[rt_buff_why],2]}
SetState {T2 Fight}
IF: All
SecsInStateGE 300
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_buff,`FAIL`]}
DoExpr {setpvar[rt_buff_why,`no "Force Rebuff Complete" within 300 s of /ra buff force`]}
DoExpr {echo[`[RynthTest] FAIL buffing: `+getpvar[rt_buff_why],2]}
SetState {T2 Fight}
~~ }
STATE: {T2 Fight} ~~ {
IF: Always
DO: DoAll
DoExpr {setvar[rt_settled,0]}
DoExpr {setvar[rt_t,getunixtime[]]}
SetOpt {EnableBuffing} {False}
IF: All
SecsInStateGE 2
Expr {wobjectfindnearestmonster[]==0}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_fight,`SKIP`]}
DoExpr {setpvar[rt_fight_why,`nothing attackable in view`]}
DoExpr {echo[`[RynthTest] SKIP fight: `+getpvar[rt_fight_why],1]}
SetState {T3 Loot}
IF: All
SecsInStateGE 2
Expr {getvar[rt_settled]==0}
DO: SetOpt {EnableCombat} {True}
IF: All
Expr {secondssincelastkill[]<(getunixtime[]-getvar[rt_t])}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_fight,`PASS`]}
DoExpr {setpvar[rt_fight_why,`killed a monster `+cstr[getunixtime[]-getvar[rt_t]]+` s after combat went on`]}
DoExpr {echo[`[RynthTest] PASS fight: `+getpvar[rt_fight_why],1]}
SetState {T3 Loot}
IF: All
SecsInStateGE 30
Expr {ratargetcount[]<1}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_fight,`SKIP`]}
DoExpr {setpvar[rt_fight_why,`combat found nothing it may attack within 30 s (nearest attackable: `+wobjectgetname[wobjectfindnearestmonster[]]+`)`]}
DoExpr {echo[`[RynthTest] SKIP fight: `+getpvar[rt_fight_why],1]}
SetState {T3 Loot}
IF: All
SecsInStateGE 180
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_fight,`FAIL`]}
DoExpr {setpvar[rt_fight_why,`no kill within 180 s of combat going on; combat sees `+cstr[ratargetcount[]]+` target(s); nearest attackable: `+wobjectgetname[wobjectfindnearestmonster[]]]}
DoExpr {echo[`[RynthTest] FAIL fight: `+getpvar[rt_fight_why],2]}
SetState {T3 Loot}
~~ }
STATE: {T3 Loot} ~~ {
IF: Always
DO: DoAll
DoExpr {setvar[rt_settled,0]}
DoExpr {setvar[rt_t,getunixtime[]]}
IF: All
Expr {getpvar[rt_fight]!=`PASS`}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_loot,`SKIP`]}
DoExpr {setpvar[rt_loot_why,`no kill of our own to loot`]}
DoExpr {echo[`[RynthTest] SKIP looting: `+getpvar[rt_loot_why],1]}
SetState {T4 Craft}
IF: All
SecsInStateGE 1
Expr {getvar[rt_settled]==0}
DO: SetOpt {EnableLooting} {True}
IF: All
ChatCapture {^\[RynthAi\] (?<msg>(Looted \[|Nothing on ).*)} {}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_loot,`PASS`]}
DoExpr {setpvar[rt_loot_why,`after `+cstr[getunixtime[]-getvar[rt_t]]+` s: `+getvar[capturegroup_msg]]}
DoExpr {echo[`[RynthTest] PASS looting: `+getpvar[rt_loot_why],1]}
SetState {T4 Craft}
IF: All
ChatCapture {^\[RynthAi\] (?<msg>Corpse (timeout|refuses to open).*)} {}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_loot,`FAIL`]}
DoExpr {setpvar[rt_loot_why,getvar[capturegroup_msg]]}
DoExpr {echo[`[RynthTest] FAIL looting: `+getpvar[rt_loot_why],2]}
SetState {T4 Craft}
IF: All
SecsInStateGE 120
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_loot,`FAIL`]}
DoExpr {setpvar[rt_loot_why,`no "Looted" or "Nothing on ... matches" line within 120 s of looting going on`]}
DoExpr {echo[`[RynthTest] FAIL looting: `+getpvar[rt_loot_why],2]}
SetState {T4 Craft}
~~ }
STATE: {T4 Craft} ~~ {
IF: Always
DO: DoAll
DoExpr {setvar[rt_settled,0]}
SetOpt {EnableCombat} {False}
SetOpt {EnableLooting} {False}
DoExpr {setvar[rt_heads,wobjectfindininventorybynamerx[`bundle of .*heads$`]]}
DoExpr {setvar[rt_shafts,wobjectfindininventorybynamerx[`bundle of .*shafts$`]]}
DoExpr {setvar[rt_wtype,getequippedweapontype[]]}
IF: All
Expr {getvar[rt_heads]==0||getvar[rt_shafts]==0}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_craft,`SKIP`]}
DoExpr {setpvar[rt_craft_why,`no arrowhead and shaft bundles in the pack`]}
DoExpr {echo[`[RynthTest] SKIP missile crafting: `+getpvar[rt_craft_why],1]}
SetState {Done}
IF: All
Expr {getvar[rt_wtype]==`Melee`||getvar[rt_wtype]==`Wand`}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_craft,`SKIP`]}
DoExpr {setpvar[rt_craft_why,`a `+getvar[rt_wtype]+` weapon is in hand, not a bow, crossbow or atlatl`]}
DoExpr {echo[`[RynthTest] SKIP missile crafting: `+getpvar[rt_craft_why],1]}
SetState {Done}
IF: All
SecsInStateGE 2
Expr {getvar[rt_settled]==0}
DO: SetState {T4 Craft run}
~~ }
STATE: {T4 Craft run} ~~ {
IF: Always
DO: DoAll
DoExpr {setvar[rt_settled,0]}
DoExpr {setvar[rt_crafted,0]}
DoExpr {setvar[rt_t,getunixtime[]]}
DoExpr {setvar[rt_ammo,wobjectfindininventorybynamerx[`^(?!.*(bundle|head|shaft)).*(arrow|quarrel|bolt|dart)s?$`]]}
DoExpr {ifthen[getvar[rt_ammo]!=0,actiontrymove[getvar[rt_ammo],wobjectgetplayer[]],0]}
IF: ChatMatch {^\[RynthAi Craft\] Crafting }
DO: DoExpr {setvar[rt_crafted,1]}
IF: All
ChatCapture {^\[RynthAi Craft\] (?<msg>(No bundles|No ammo and no bundles|No ammo, and Fletching|Craft timed out|Timeout after|Could not find ammo|Equip timed out|Equip error|UseObjectOn returned false|Stopped by an error).*)} {}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_craft,`FAIL`]}
DoExpr {setpvar[rt_craft_why,getvar[capturegroup_msg]]}
DoExpr {echo[`[RynthTest] FAIL missile crafting: `+getpvar[rt_craft_why],2]}
SetState {Done}
IF: All
ChatMatch {^\[RynthAi Craft\] (Equipped ammo|Done: )}
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_craft,`PASS`]}
DoExpr {setpvar[rt_craft_why,ifthen[getvar[rt_crafted]==1,`made ammo from the bundles`,`put carried ammo back on (to test making ammo, carry none)`]+` in `+cstr[getunixtime[]-getvar[rt_t]]+` s`]}
DoExpr {echo[`[RynthTest] PASS missile crafting: `+getpvar[rt_craft_why],1]}
SetState {Done}
IF: All
SecsInStateGE 75
Expr {getvar[rt_settled]==0}
DO: DoAll
DoExpr {setvar[rt_settled,1]}
DoExpr {setpvar[rt_craft,`FAIL`]}
DoExpr {setpvar[rt_craft_why,`nothing from Missile Crafting within 75 s of the ammo coming off (a launcher must be in hand and Missile Crafting on)`]}
DoExpr {echo[`[RynthTest] FAIL missile crafting: `+getpvar[rt_craft_why],2]}
SetState {Done}
~~ }
STATE: {Done} ~~ {
IF: Always
DO: DoAll
SetOpt {EnableCombat} {getvar[rt_o_combat]}
SetOpt {EnableBuffing} {getvar[rt_o_buff]}
SetOpt {EnableLooting} {getvar[rt_o_loot]}
SetOpt {EnableNav} {getvar[rt_o_nav]}
DoExpr {setpvar[rt_finished,getunixtime[]]}
DoExpr {setpvar[rt_status,`DONE`]}
DoExpr {echo[`[RynthTest] done: buffing `+getpvar[rt_buff]+`; fight `+getpvar[rt_fight]+`; looting `+getpvar[rt_loot]+`; missile crafting `+getpvar[rt_craft],1]}
IF: SecsInStateGE 3
DO: Chat {/ra stop}
~~ }

View file

@ -6,23 +6,25 @@
// Measured by health, not by counting heal attempts: a round of FailsafeRoundMs
// with no rise of FailsafeRiseMinPct counts as a failed round (whatever the
// reason: a stuck cast, 'too busy', no mana, no kits).
// 1. FailsafeRoundsToBreak failed rounds: ActionPacer.ForceBreak (a jump; on
// ACE's fast tick it fails the cast in progress, Player.HandleActionJump).
// Starts are held until landed, then the vitals step heals again.
// 2. FailsafeRoundsToRecall more failed rounds after the break: recall to the
// lifestone ("/lifestone", ACE GameAction TeleToLifestone) when
// HpFailsafeRecall is on. The macro is switched off first, because ACE
// cancels the recall when the character moves during its animation and
// refuses it while busy (Player_Location.HandleActionTeleToLifestone).
// 3. No "<our name> is recalling to the lifestone." after RecallMaxSends tries
// (ACE refuses the recall while busy, under a PK timer or with recalls
// disabled, which is just the stuck state this is for): the macro is
// switched back on, so the heals and kits run again, and the failsafe
// re-arms; the next recall waits RecallCooldownMs. A failed recall must not
// leave the character standing at low health with nothing running. Only a
// macro the failsafe itself stopped is switched back on, never past a VTank
// yield (MayRestartMacro), and a death drops the pending recall (the player's
// Stop Macro On Death stands).
// 1. FailsafeRoundsToBreak failed rounds (FailsafeRoundsToRecallBreak with
// HpFailsafeRecall on): ActionPacer.ForceBreak (a jump; on ACE's fast tick it
// fails the cast in progress, Player.HandleActionJump). Starts are held until
// landed, then the vitals step heals again.
// 2. HpFailsafeRecall on: at once, with the jump, the Lifestone Recall SPELL
// (RecallSpellId), not "/lifestone" (2026-10-22: /lifestone's long kneel was
// killing characters, and a move during it cancels it). The macro is switched
// off first so nothing else casts, swings or moves over it; the recall goes on
// the next heartbeat, through the emergency heal's Magic stance step, and is
// cast again every RecallResendMs until portal space shows it went. No recall
// for a character without the spell or the mana for it: it keeps healing.
// Recall off: FailsafeRoundsToRecall more failed rounds are only logged.
// 3. No portal space after RecallMaxSends casts, or by RecallGiveUpMs (refused:
// busy, out of mana, a fizzle run): the macro is switched back on, so the
// heals and kits run again, and the failsafe re-arms; the next recall waits
// RecallCooldownMs. A failed recall must not leave the character standing at
// low health with nothing running. Only a macro the failsafe itself stopped is
// switched back on, never past a VTank yield (MayRestartMacro), and a death
// drops the pending recall (the player's Stop Macro On Death stands).
// Health back over the line (or 100%) ends the episode. Nothing counts in portal space.
// The failsafe (jump included) is for a character that can heal: it arms only with a heal that went
// out in the last minute, or a heal spell / kit / health potion at hand (HealCapableNow). A melee
@ -38,17 +40,20 @@ public partial class BuffManager
{
internal const double FailsafeRoundMs = 2500;
internal const int FailsafeRoundsToBreak = 3;
/// <summary>With HpFailsafeRecall on, the jump (and the recall with it) comes sooner: 5 s, not 7.5 s.</summary>
internal const int FailsafeRoundsToRecallBreak = 2;
internal const int FailsafeRoundsToRecall = 3;
// A rise this large (health %) means a heal landed; natural regeneration is smaller.
private const int FailsafeRiseMinPct = 3;
// The recall goes this long after the macro stop (the stop edge runs on the next tick),
// and is sent again this often, a few times, until our "is recalling to the lifestone" is seen.
private const double RecallFirstDelayMs = 600;
private const double RecallResendMs = 1500;
private const int RecallMaxSends = 3;
/// <summary>Lifestone Recall, the spell (SpellDatabase).</summary>
internal const int RecallSpellId = 1635;
// The recall is cast again this often until portal space shows it went (a fizzle, a refusal),
// at most RecallMaxSends times, and given up RecallGiveUpMs after the macro stop.
internal const double RecallResendMs = 3000;
internal const int RecallMaxSends = 3;
internal const double RecallGiveUpMs = 12_000;
/// <summary>After a recall that never started, the next one waits this long (the heals run meanwhile).</summary>
internal const double RecallCooldownMs = 30_000;
internal const string RecallCommand = "/lifestone";
private bool _fsActive;
private DateTime _fsRoundStart;
@ -59,9 +64,11 @@ public partial class BuffManager
private DateTime _fsRecallNotBefore = DateTime.MinValue;
private bool _recallPending;
private bool _recallSeen;
private int _recallSends;
private DateTime _recallNextAt;
private DateTime _recallStartedAt;
private string _recallWait = "";
private bool _fsNoRecallLogged;
/// <summary>Set by the plugin: the rest of a /ra stop (nav stop, pause cancel) for the recall.</summary>
internal Action? MacroStopForRecall { get; set; }
@ -70,7 +77,6 @@ public partial class BuffManager
// The macro is off because the failsafe stopped it for a recall (only then does it switch it back on).
private bool _macroStoppedByFailsafe;
private bool _recallNameLogged;
internal int HpFailsafeBreaks { get; private set; }
internal int HpFailsafeRecalls { get; private set; }
@ -121,19 +127,30 @@ public partial class BuffManager
_fsFailedRounds++;
_fsRoundStart = now;
double failedSec = _fsFailedRounds * FailsafeRoundMs / 1000.0;
bool recallOn = _settings.HpFailsafeRecall;
if (!_fsBroken)
{
if (_fsFailedRounds < FailsafeRoundsToBreak) return;
if (_fsFailedRounds < (recallOn ? FailsafeRoundsToRecallBreak : FailsafeRoundsToBreak)) return;
string why = $"HP failsafe: health {hp}% at or under Emergency Heal At {at}%, no heal landed in {failedSec:0.#} s";
bool jumped = ActionPacer.ForceBreak(_host, why);
if (jumped) HpFailsafeBreaks++;
_host.Log($"[Vitals] {why}: {(jumped ? "breaking the cast with a jump, then healing again" : "no jump available (or one under way), healing again")}.");
_fsBroken = true;
_fsFailedRounds = 0;
string? noRecall = recallOn ? RecallUnavailable(now) : null;
if (recallOn && noRecall == null)
{
// No more waiting: the jump frees a stuck cast and the recall goes on the next heartbeat.
_host.Log($"[Vitals] {why}: {(jumped ? "breaking the cast with a jump" : "no jump available (or one under way)")}, then Lifestone Recall at once.");
StartFailsafeRecall(now, hp, failedSec);
return;
}
_host.Log($"[Vitals] {why}: {(jumped ? "breaking the cast with a jump, then healing again" : "no jump available (or one under way), healing again")}" +
(noRecall != null ? $"; no recall: {noRecall}" : "") + ".");
if (noRecall != null) _fsNoRecallLogged = true;
return;
}
if (_fsFailedRounds < FailsafeRoundsToRecall) return;
if (!_settings.HpFailsafeRecall)
if (!recallOn)
{
if (!_fsRecallLogged)
{
@ -149,9 +166,35 @@ public partial class BuffManager
_fsFailedRounds = 0;
return;
}
string? cannot = RecallUnavailable(now);
if (cannot != null)
{
if (!_fsNoRecallLogged)
{
_fsNoRecallLogged = true;
_host.Log($"[Vitals] HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break; no recall: {cannot}.");
}
return;
}
StartFailsafeRecall(now, hp, failedSec);
}
/// <summary>
/// Why the Lifestone Recall spell can't go now (null = it can): the cooldown after one that never
/// started, a spellbook that hasn't got it, or less mana than it costs. The character keeps healing.
/// </summary>
private string? RecallUnavailable(DateTime now)
{
if (now < _fsRecallNotBefore)
return $"the last recall never started, the next in {(_fsRecallNotBefore - now).TotalSeconds:0} s";
if (_spellManager.IsKnownSnapshotWarm && !_spellManager.IsKnownSpellId(RecallSpellId))
return "this character doesn't know Lifestone Recall";
int cost = SpellManaCost(RecallSpellId);
if (cost > 0 && _vitals.MaxMana > 0 && _vitals.CurrentMana < cost)
return $"mana {_vitals.CurrentMana} is under Lifestone Recall's cost ({cost})";
return null;
}
// A heal (spell, kit or potion) that actually went out: the failsafe's proof the character can heal.
private DateTime _lastHealSentAt = DateTime.MinValue;
private DateTime _healCapableCheckAt = DateTime.MinValue;
@ -211,6 +254,7 @@ public partial class BuffManager
_fsFailedRounds = 0;
_fsBroken = false;
_fsRecallLogged = false;
_fsNoRecallLogged = false;
}
private void StartFailsafeRecall(DateTime now, int hp, double failedSec)
@ -218,28 +262,33 @@ public partial class BuffManager
HpFailsafeRecalls++;
_settings.IsMacroRunning = false;
_macroStoppedByFailsafe = true;
_recallNameLogged = false;
MacroStopForRecall?.Invoke();
// The heal the jump broke is not waited on, here or by the pacer: a stuck cast may never be
// answered, and the recall must not wait for its breaker steps (seconds). It still waits to
// land from the jump (ActionPacer's airborne hold is kept).
if (_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId) _pendingSpellId = 0;
ActionPacer.Forget("HP failsafe recall");
_recallPending = true;
_recallSeen = false;
_recallSends = 0;
_recallNextAt = now.AddMilliseconds(RecallFirstDelayMs);
string line = $"HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break: macro stopped, recalling to the lifestone.";
_recallStartedAt = now;
_recallNextAt = now; // the next heartbeat: the macro-stop edge has run by then
_recallWait = "";
string line = $"HP failsafe: health {hp}%, no heal landed in {failedSec:0.#} s: casting Lifestone Recall (macro off until it goes; back on if it can't).";
_host.Log("[Vitals] " + line);
_host.WriteToChat("[RynthAi] " + line, 2);
ResetHpFailsafe();
}
/// <summary>Every heartbeat, macro running or not: sends a pending recall, or gives up on it.</summary>
/// <summary>Every heartbeat, macro running or not: casts a pending recall, or gives up on it.</summary>
private void TickFailsafeRecall()
{
if (!_recallPending) return;
DateTime now = Now;
if (_recallSeen)
if (Portaling())
{
_recallPending = false;
_macroStoppedByFailsafe = false;
_host.Log("[Vitals] HP failsafe: the recall started.");
_host.Log($"[Vitals] HP failsafe: the recall went (portal space, {(now - _recallStartedAt).TotalMilliseconds:0} ms after the stop, {_recallSends} cast(s)).");
return;
}
if (_vitals.MaxHealth > 0 && _vitals.CurrentHealth == 0)
@ -255,15 +304,16 @@ public partial class BuffManager
_host.Log("[Vitals] HP failsafe: the macro was started again; the recall is dropped.");
return;
}
if (now < _recallNextAt) return;
if (_recallSends >= RecallMaxSends || !_host.HasInvokeChatParser)
bool spent = _recallSends >= RecallMaxSends && now >= _recallNextAt;
bool late = (now - _recallStartedAt).TotalMilliseconds >= RecallGiveUpMs;
if (spent || late || !_host.HasCastSpell)
{
_recallPending = false;
HpFailsafeRecallsFailed++;
_fsRecallNotBefore = now.AddMilliseconds(RecallCooldownMs);
string why = _host.HasInvokeChatParser
? $"no recall seen after {_recallSends} tries of {RecallCommand} (refused: busy, a PK timer or recalls disabled)"
: "this engine has no chat parser, so no recall";
string why = !_host.HasCastSpell ? "this engine can't cast, so no recall"
: _recallSends == 0 ? $"Lifestone Recall couldn't be cast in {RecallGiveUpMs / 1000:0} s ({(_recallWait.Length > 0 ? _recallWait : "no reason seen")})"
: $"no portal space after {_recallSends} cast(s) of Lifestone Recall (refused or fizzled)";
string what;
if (!_macroStoppedByFailsafe) what = "the macro stays as it is";
else if (MayRestartMacro != null && !MayRestartMacro()) what = "the macro stays off (VTank yield)";
@ -278,14 +328,45 @@ public partial class BuffManager
_host.WriteToChat("[RynthAi] " + line, 2);
return;
}
_host.InvokeChatParser(RecallCommand);
if (now < _recallNextAt || _recallSends >= RecallMaxSends) return;
string wait = RecallCastHolds();
if (wait.Length > 0)
{
if (wait != _recallWait) _host.Log($"[Vitals] HP failsafe: Lifestone Recall waits: {wait}.");
_recallWait = wait;
return;
}
_recallWait = "";
uint me = unchecked((uint)_host.GetPlayerId());
bool sent = me != 0 && _host.CastSpellFor(me, RecallSpellId, "HpFailsafe", "Lifestone Recall");
_lastCastAttempt = RynthClock.Now;
if (!sent)
{
_recallWait = "the client refused the cast";
_recallNextAt = now.AddMilliseconds(500);
return;
}
_recallSends++;
_recallNextAt = now.AddMilliseconds(RecallResendMs);
_host.Log($"[Vitals] HP failsafe: Lifestone Recall cast ({_recallSends}/{RecallMaxSends}, {(now - _recallStartedAt).TotalMilliseconds:0} ms after the stop).");
}
/// <summary>
/// What holds the recall cast back now ("" = nothing): the Magic stance (the emergency heal's step,
/// wand swap included) and the pacer at emergency health (in the air after the jump, a server
/// answer it must wait for). Nothing else of RynthAi runs meanwhile: the macro is off.
/// </summary>
private string RecallCastHolds()
{
if (!EnsureMagicMode(urgentHeal: true))
return _magicModeBlocked ? "can't switch to Magic mode" : "wand swap / Magic stance";
if (!PacerAllows(out string pacerWhy)) return "the server: " + pacerWhy;
return "";
}
/// <summary>
/// The plugin's death hold (and a 0-health read): a pending recall is dropped and the macro is
/// left off, so nothing re-sends /lifestone or restarts the macro after the respawn.
/// left off, so nothing casts the recall again or restarts the macro after the respawn.
/// </summary>
/// <summary>
/// A death or a portal dropped whatever the server had open: a wand use in flight is forgotten,
@ -306,32 +387,4 @@ public partial class BuffManager
_macroStoppedByFailsafe = false;
_host.Log($"[Vitals] HP failsafe: the pending recall is dropped ({why}); the macro stays off.");
}
/// <summary>OnChatWindowText: "<our name> is recalling to the lifestone." while a recall is pending.</summary>
private void ObserveRecallLine(string lower)
{
if (!_recallPending || !lower.Contains("is recalling to the lifestone")) return;
string me = "";
try
{
uint id = unchecked((uint)_host.GetPlayerId());
if (id != 0 && _host.HasGetObjectName && _host.TryGetObjectName(id, out string n)) me = n ?? "";
}
catch { me = ""; }
// Someone else's recall ("Bob is recalling to the lifestone.") is not ours. The chat layer
// can drop a line's first letter ("ou cast ..."), so the name may arrive without it.
if (me.Length > 0)
{
string who = lower.Substring(0, lower.IndexOf(" is recalling to the lifestone", StringComparison.Ordinal)).Trim();
string mine = me.ToLowerInvariant();
bool ours = who == mine || (who.Length == mine.Length - 1 && who.Length > 0 && mine.EndsWith(who, StringComparison.Ordinal));
if (!ours) return;
}
else if (!_recallNameLogged)
{
_recallNameLogged = true;
_host.Log("[Vitals] HP failsafe: our name could not be read; any 'is recalling to the lifestone' line is taken as ours.");
}
_recallSeen = true;
}
}

View file

@ -4272,7 +4272,6 @@ public partial class BuffManager : IDisposable
public void OnChatWindowText(string text, int chatType)
{
string lower = text.ToLowerInvariant();
ObserveRecallLine(lower);
// A scroll read that taught a spell (ACE: "The scroll is destroyed."): read the spellbook on
// the next buff check, so a newly learned higher level is cast (an upgrade) at once.

View file

@ -672,10 +672,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("HP Failsafe Recall", ref _settings.HpFailsafeRecall);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"At or under Emergency Heal At with heals failing: break the\n" +
"stuck cast with a jump and heal again; if that fails too,\n" +
"recall to the lifestone. Off by default; only a character that\n" +
"can heal (a heal spell, kit or potion) is ever recalled.");
"At or under Emergency Heal At with no heal landing for 5 s:\n" +
"break the stuck cast with a jump and cast Lifestone Recall at\n" +
"once (the spell, not /ls). The macro waits while it casts and\n" +
"comes back on if the recall can't go. Needs the spell and its\n" +
"mana; only a character that can heal (a heal spell, kit or\n" +
"potion) is ever recalled. Off: the jump only, after 7.5 s.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);

View file

@ -451,9 +451,14 @@ public sealed class LegacyUiSettings
/// <summary>
/// HP failsafe: at or under Emergency Heal At with heals failing for a while, the stuck-cast
/// breaker runs and the heal is tried again; when that fails too, recall to the lifestone.
/// breaker runs and the Lifestone Recall spell is cast at once (BuffManager.HpFailsafe.cs).
/// Off: the breaker still runs, no recall.
/// Saved under a new name since 2026-10-22, so it is off for everyone until ticked again: the
/// recall stops the macro (heals included) in the middle of a fight, and it was killing players.
/// The 10-18 default change only reached profiles that never saved it; an old saved
/// "HpFailsafeRecall": true (the default until then) no longer loads.
/// </summary>
[JsonPropertyName("HpFailsafeRecallOptIn")]
public bool HpFailsafeRecall = false;
/// <summary>

View file

@ -205,6 +205,12 @@ internal sealed partial class ExpressionEngine
private KillClock? _killClock;
public void SetKillClock(KillClock? clock) => _killClock = clock;
// ratargetcount[] (RynthAi only, 2026-10-22): the targets that passed every combat filter in combat's
// last scan (CombatManager.LastScanPossible). -1 before the first scan or with no combat manager. The
// self-test meta uses it to tell "nothing here to fight" from "a fight that never happened":
// wobjectfindnearestmonster[] also finds attackable NPCs (a buff bot) combat rightly leaves alone.
internal Func<int>? CombatTargetCount { get; set; }
// ── Backward-compat shim ──────────────────────────────────────────────────
/// <summary>Executes an expression for its side effects. Always returns true.</summary>
@ -386,6 +392,7 @@ internal sealed partial class ExpressionEngine
"getunixtime" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture),
// Whole seconds since our last kill; before the first, since the macro start (or login).
"secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture),
"ratargetcount" => (CombatTargetCount?.Invoke() ?? -1).ToString(CultureInfo.InvariantCulture),
// ── World object queries ──────────────────────────────────────────
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),

View file

@ -188,6 +188,14 @@ internal sealed class MetaManager
if (_expressions != null) _expressions.CorpseOpenedByMe = check;
}
// Combat's target count for ratargetcount[] (the last scan's candidates).
private Func<int>? _combatTargetCount;
public void SetCombatTargetCount(Func<int>? count)
{
_combatTargetCount = count;
if (_expressions != null) _expressions.CombatTargetCount = count;
}
public void SetPlayerId(uint id)
{
_playerId = id;
@ -241,6 +249,7 @@ internal sealed class MetaManager
engine.SetCreatureStore(_creatureStore);
engine.SetKillClock(_killClock);
engine.CorpseOpenedByMe = _corpseOpenedByMe;
engine.CombatTargetCount = _combatTargetCount;
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
engine.VtOptionSetter = TrySetVtOption;
engine.VtOptionGetter = GetVtOption;

View file

@ -791,6 +791,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager.SetCreatureStore(_creatureStore);
_metaManager.SetKillClock(_killClock);
_metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id));
_metaManager.SetCombatTargetCount(() => _combatManager?.LastScanPossible ?? -1);
if (_dashboard != null)
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();

View file

@ -45,17 +45,56 @@ internal sealed class Atlas
public string Generated { get; }
public string Path { get; }
/// <summary>
/// The recalls' landing spots as places of type <see cref="RecallType"/> (2026-10-22), for
/// finding a place by name (<see cref="Search"/>, <see cref="FindBest"/>): the world database
/// names only the /telepoi towns, so "neft" found nothing while Lost City of Neftet Recall lands
/// there. Kept out of <see cref="Locations"/>, which the route planner reads. The engine's
/// Atlas panel lists the same places (RynthCore UI/Data/RynthNavAtlasRecalls.cs).
/// </summary>
public IReadOnlyList<AtlasLocation> RecallPlaces { get; }
public const string RecallType = "Recall";
private readonly Dictionary<int, AtlasLocation> _byId = new();
private Atlas(List<AtlasLocation> locations, List<AtlasRecall> recalls, string generated, string path)
{
Locations = locations;
Recalls = recalls;
RecallPlaces = RecallPlacesOf(recalls);
Generated = generated;
Path = path;
foreach (var l in locations) _byId[l.Id] = l;
}
private static List<AtlasLocation> RecallPlacesOf(List<AtlasRecall> recalls)
{
var places = new List<AtlasLocation>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var r in recalls)
{
string name = r.Name.Trim();
// A spell listed twice for one spot (Ulgrim's Recall) is one place.
string key = string.Create(CultureInfo.InvariantCulture, $"{name}|{r.OnMap}|{r.Ns:0.00}|{r.Ew:0.00}|{r.In}");
if (name.Length == 0 || !seen.Add(key)) continue;
places.Add(new AtlasLocation
{
Id = -r.SpellId, // locations have positive ids
Name = name, Type = RecallType, OnMap = r.OnMap, Ns = r.Ns, Ew = r.Ew,
Place = r.OnMap ? "outdoor" : "dungeon",
Desc = r.In.Length > 0 ? "in " + r.In : "",
});
}
return places;
}
/// <summary>What a name search looks through: the locations, then the recall places.</summary>
private IEnumerable<AtlasLocation> Searchable()
{
foreach (var l in Locations) yield return l;
foreach (var l in RecallPlaces) yield return l;
}
public static Atlas Load(string path) => Parse(File.ReadAllText(path), path);
public static Atlas Parse(string json, string path = "")
@ -185,6 +224,7 @@ internal sealed class Atlas
"Town" => 0,
"Dungeon" => 1,
"Landmark" => 2,
RecallType => 2,
"Lifestone" => 3,
"Bindstone" => 4,
"Portal" => 5,
@ -205,7 +245,7 @@ internal sealed class Atlas
AtlasLocation? best = null;
int bestScore = 0, bestRank = int.MaxValue;
double bestDist = double.MaxValue;
foreach (var l in Locations)
foreach (var l in Searchable())
{
if (!l.OnMap) continue;
int s = MatchScore(l.Name, q);
@ -229,7 +269,7 @@ internal sealed class Atlas
{
string q = query.Trim();
var hits = new List<(AtlasLocation L, int S)>();
foreach (var l in Locations)
foreach (var l in Searchable())
{
if (!string.IsNullOrEmpty(type) && !l.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue;
int s = MatchScore(l.Name, q);

View file

@ -56,6 +56,7 @@ internal static class Program
MagItemDescriberTests.Register(runner);
ExpressionTests.Register(runner);
MetaTests.Register(runner);
SelfTestMetaTests.Register(runner);
NoKillTests.Register(runner);
MetaSchedulerTests.Register(runner);
NavEngineTests.Register(runner);

View file

@ -10,9 +10,10 @@ using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// HP failsafe: under Emergency Heal At with heals failing (here: every heal sent and never answered,
// as in a client log's hung casts), the character must not sit and die. 3 rounds of 2.5 s with no
// rise: a forced jump (ActionPacer.ForceBreak), then healing again; 3 more: the macro stops and
// "/lifestone" goes out (HpFailsafeRecall, default off; the tests turn it on).
// as in a client log's hung casts), the character must not sit and die. Recall off: 3 rounds of 2.5 s
// with no rise, a forced jump (ActionPacer.ForceBreak), then healing again. HpFailsafeRecall on
// (default off; most tests here turn it on): 2 rounds, the jump, and the Lifestone Recall SPELL at
// once (2026-10-22: not "/lifestone", whose long kneel got characters killed).
internal static class HpFailsafeTests
{
private const uint Player = 0x50000B31;
@ -20,19 +21,18 @@ internal static class HpFailsafeTests
public static void Register(Runner r)
{
r.Add("hp failsafe: 7.5 s at Emergency Heal At with no heal landing -> one jump; 7.5 s more -> macro stop and /lifestone", BreakThenRecall);
r.Add("hp failsafe: recall on, 5 s at Emergency Heal At with no heal landing -> one jump, the macro stop and Lifestone Recall cast once landed; portal space ends it", BreakThenRecall);
r.Add("hp failsafe: a heal landing (+3%) restarts the count; health over the line ends it", HealLandingResets);
r.Add("hp failsafe: HP Failsafe Recall off -> the jump still, no recall; no recall line -> 3 sends, then it gives up", RecallOffAndResends);
r.Add("hp failsafe: HP Failsafe Recall off -> the jump at 7.5 s, no recall; no portal space -> 3 casts 3 s apart, then it gives up", RecallOffAndResends);
r.Add("hp failsafe: a recall that never starts turns the macro back on and re-arms; the next recall after 30 s", FailedRecallResumes);
r.Add("hp failsafe: another player's recall line is not ours; ours with its first letter dropped is", RecallLineIsOurs);
r.Add("hp failsafe: Emergency Heal At 100 at full health is not an emergency", FullHealthAtHundred);
r.Add("hp failsafe: nothing counts in portal space", NothingInPortalSpace);
r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no /lifestone, the macro stays off", DeathDropsRecall);
r.Add("hp failsafe: a death drops the pending recall (0 health, and the plugin's death hold): no Lifestone Recall, the macro stays off", DeathDropsRecall);
r.Add("hp failsafe: a failed recall does not switch the macro back on past a VTank yield", VTankYieldRespected);
r.Add("hp failsafe: our name unreadable: the recall line is taken as ours, and that is logged once", RecallNameUnreadable);
r.Add("hp failsafe: HP Failsafe Recall is off by default; a profile with no saved value loads off, one that saved true keeps it", RecallOffByDefault);
r.Add("hp failsafe: no recall without the spell or its mana: the jump, healing on, the macro keeps running, said once", NoSpellNoManaNoRecall);
r.Add("hp failsafe: HP Failsafe Recall is off by default; a profile with no saved value loads off, an old saved true (before 10-22) loads off, a tick since then stays", RecallOffByDefault);
r.Add("hp failsafe: a character that cannot heal at all (no spell, kit or potion) never jumps or recalls", NoHealCapabilityNeverFires);
r.Add("hp failsafe: a character that can heal (a known Heal Self) and is stuck still jumps, then recalls when the option is on", CapableStuckStillRecalls);
r.Add("hp failsafe: a character that can heal (a known Heal Self) and is stuck still jumps, then casts Lifestone Recall when the option is on", CapableStuckStillRecalls);
r.Add("hp failsafe: a heal that went out proves the character can heal (a listed potion, no spell)", PotionSentProvesCapability);
r.Add("vitals (L8):a heal the server leaves unanswered is not re-sent at the 2.5 s give-up after a 'too busy' answer", VitalResendObeysLatch);
r.Add("vitals: under Emergency Heal At with a weapon out and no usable kit, a health potion before Heal Self's wand swap", EmergencyPotionBeforeWandSwap);
@ -136,7 +136,7 @@ internal static class HpFailsafeTests
public readonly RynthCore.PluginSdk.RynthCoreHost Host;
public int MacroStops;
public Rig(int healthPct = 20, bool canHeal = true, bool recall = true)
public Rig(int healthPct = 20, bool canHeal = true, bool recall = true, bool knowsRecall = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
@ -150,6 +150,7 @@ internal static class HpFailsafeTests
if (canHeal)
{
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
if (!knowsRecall) FakeHost.Spellbook.Remove((uint)BuffManager.RecallSpellId);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
}
else
@ -194,6 +195,19 @@ internal static class HpFailsafeTests
public void At(double seconds) => NowAt = T0.AddMilliseconds(Math.Round(seconds * 1000));
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
public static int Recalls => FakeHost.Casts.Count(c => c.SpellId == BuffManager.RecallSpellId);
/// <summary>Heartbeats as <see cref="Run"/>; each recall cast is answered at once (done, no teleport: a fizzle or refusal).</summary>
public void RunAnswered(double from, double to)
{
for (int ms = (int)Math.Round(from * 1000); ms <= (int)Math.Round(to * 1000); ms += 100)
{
At(ms / 1000.0);
int before = Recalls;
B.OnHeartbeat();
if (Recalls > before) FakeHost.UseDone(0);
}
}
/// <summary>Heartbeats every 100 ms from <paramref name="from"/> up to and including <paramref name="to"/>.</summary>
public void Run(double from, double to)
@ -227,17 +241,26 @@ internal static class HpFailsafeTests
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
// A profile with no saved value for it: off.
var node = System.Text.Json.Nodes.JsonNode.Parse(System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings(), ctx))!.AsObject();
Check.True(node.Remove("HpFailsafeRecall"), "the key is a serialized setting");
Check.True(node.Remove("HpFailsafeRecallOptIn"), "the key is a serialized setting, under its 10-22 name");
Check.False(node.ContainsKey("HpFailsafeRecall"), "the old name is no longer written");
var noKey = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live = new LegacyUiSettings { HpFailsafeRecall = true };
CopySettings(noKey, live);
Check.False(live.HpFailsafeRecall, "no saved value: the recall loads off");
// A profile that saved true (the owner turned it on, or the earlier default was saved): kept.
// A profile saved before 10-22 with the old name on (the default until 10-18): off now. The
// recall stops the macro, heals included, mid-fight, and it was killing players.
node["HpFailsafeRecall"] = true;
var old = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live2 = new LegacyUiSettings { HpFailsafeRecall = true };
CopySettings(old, live2);
Check.False(live2.HpFailsafeRecall, "an old saved true (the old name) loads off");
// Ticked again since (saved under the new name): kept.
node.Remove("HpFailsafeRecall");
node["HpFailsafeRecallOptIn"] = true;
var saved = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live2 = new LegacyUiSettings();
CopySettings(saved, live2);
Check.True(live2.HpFailsafeRecall, "a saved true stays on");
var live3 = new LegacyUiSettings();
CopySettings(saved, live3);
Check.True(live3.HpFailsafeRecall, "ticked since 10-22: stays on");
}
// A melee character with nothing to heal with (no spell, kit or potion), resting or out-healed at
@ -251,7 +274,7 @@ internal static class HpFailsafeTests
Check.Eq(FakeHost.Casts.Count, 0, "nothing to cast with");
Check.Eq(FakeHost.TapJumps, 0, "no failsafe jump");
Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no /lifestone");
Check.Eq(Rig.Recalls, 0, "no Lifestone Recall");
Check.Eq(r.B.HpFailsafeRecalls, 0, "no recall");
Check.True(r.S.IsMacroRunning, "the macro keeps running");
@ -270,7 +293,7 @@ internal static class HpFailsafeTests
p.B.SetWorldObjectCache(cache);
p.Run(0, 40);
Check.Eq(FakeHost.TapJumps, 0, "no spell known, potions off: no jump");
Check.Eq(FakeHost.ChatCommands.Count, 0, "and no recall");
Check.Eq(Rig.Recalls, 0, "and no recall");
Check.True(p.S.IsMacroRunning, "the macro keeps running");
}
finally { Done(); }
@ -282,18 +305,19 @@ internal static class HpFailsafeTests
try
{
var r = new Rig(healthPct: 20, canHeal: true, recall: true);
r.Run(0, 15.0);
r.Run(0, 5.0);
Check.Eq(FakeHost.TapJumps, 1, "capable + stuck: the jump");
Check.False(r.S.IsMacroRunning, "capable + stuck + recall on: the macro stops");
r.Run(15.1, 16.0);
Check.Eq(FakeHost.ChatCommands.Count, 1, "and /lifestone goes out");
r.Run(5.1, 7.0);
Check.Eq(Rig.Recalls, 1, "and Lifestone Recall is cast");
Check.Eq(FakeHost.ChatCommands.Count, 0, "never /lifestone");
// The option off (the default): the jump only, the macro keeps running.
var d = new Rig(healthPct: 20, canHeal: true, recall: false);
d.Run(0, 30.0);
Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still");
Check.True(d.S.IsMacroRunning, "recall off: no stop");
Check.Eq(FakeHost.ChatCommands.Count, 0, "recall off: no /lifestone");
Check.Eq(Rig.Recalls, 0, "recall off: no Lifestone Recall");
}
finally { Done(); }
}
@ -318,7 +342,9 @@ internal static class HpFailsafeTests
r.Run(0, 15.0);
Check.True(FakeHost.Uses.Contains(Potion), "the potion is drunk");
Check.Eq(FakeHost.TapJumps, 1, "it did not raise health: the failsafe jump");
Check.False(r.S.IsMacroRunning, "and the recall stage");
// This spellbook has no Lifestone Recall: no recall, healing goes on.
Check.True(r.S.IsMacroRunning, "no recall spell: the macro keeps running");
Check.True(r.Logged("no recall: this character doesn't know Lifestone Recall"), "said why");
}
finally { Done(); }
}
@ -328,32 +354,28 @@ internal static class HpFailsafeTests
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 7.4);
r.Run(0, 4.9);
Check.True(FakeHost.Casts.Count > 0, "a heal went out (and is never answered)");
Check.Eq(FakeHost.TapJumps, 0, "7.4 s: no jump yet");
r.Run(7.5, 7.5);
Check.Eq(FakeHost.TapJumps, 1, "7.5 s (3 rounds, no rise): one jump");
Check.Eq(FakeHost.TapJumps, 0, "4.9 s: no jump yet");
r.Run(5.0, 5.0);
Check.Eq(FakeHost.TapJumps, 1, "5 s (2 rounds, no rise, recall on): one jump");
Check.Eq(r.B.HpFailsafeBreaks, 1, "counted");
Check.True(r.Logged("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in 7.5 s: breaking the cast with a jump"),
"the break is logged");
r.Run(7.6, 14.9);
Check.Eq(FakeHost.TapJumps, 1, "only one jump");
Check.True(r.S.IsMacroRunning, "14.9 s: still running");
r.Run(15.0, 15.0);
Check.False(r.S.IsMacroRunning, "15 s (3 more rounds): the macro is stopped");
Check.True(r.Logged("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in 5 s: breaking the cast with a jump, then Lifestone Recall at once"),
"the break is logged: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("HP failsafe"))));
Check.False(r.S.IsMacroRunning, "with the jump: the macro is stopped, no second wait");
Check.Eq(r.MacroStops, 1, "with the rest of a /ra stop");
Check.Eq(r.B.HpFailsafeRecalls, 1, "counted");
Check.True(FakeHost.Chat.Any(c => c.Contains("recalling to the lifestone")), "and said in chat");
Check.Eq(FakeHost.ChatCommands.Count, 0, "the recall waits for the stop to take effect");
r.Run(15.1, 15.5);
Check.Eq(FakeHost.ChatCommands.Count, 0, "500 ms later: still waiting for the stop to take effect");
r.Run(15.6, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "600 ms later: one recall");
Check.Eq(FakeHost.ChatCommands[0], BuffManager.RecallCommand, "/lifestone");
r.B.OnChatWindowText("Mira is recalling to the lifestone.", 0);
r.Run(15.7, 20);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the recall line: no resend");
Check.True(r.Logged("HP failsafe: the recall started"), "logged");
Check.True(FakeHost.Chat.Any(c => c.Contains("casting Lifestone Recall")), "and said in chat");
Check.Eq(Rig.Recalls, 0, "not in the same heartbeat: the stop edge runs first");
r.Run(5.1, 6.6);
Check.Eq(Rig.Recalls, 1, "once landed from the jump (400 ms or more): one Lifestone Recall: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("HP failsafe")).TakeLast(6)));
Check.Eq(FakeHost.Casts.Last(c => c.SpellId == BuffManager.RecallSpellId).Target, Player, "on ourselves");
Check.Eq(FakeHost.ChatCommands.Count, 0, "never /lifestone");
FakeHost.Portaling = true; // the recall went
r.Run(6.7, 20);
Check.Eq(Rig.Recalls, 1, "portal space: no recast");
Check.True(r.Logged("HP failsafe: the recall went (portal space"), "logged");
FakeHost.Portaling = false;
}
finally { Done(); }
}
@ -362,13 +384,14 @@ internal static class HpFailsafeTests
{
try
{
var r = new Rig(healthPct: 20);
// The round counting, recall off (the jump at 3 rounds).
var r = new Rig(healthPct: 20, recall: false);
r.Run(0, 5.0);
r.V.CurrentHealth = 22; // +2: regeneration, not a heal
r.Run(5.1, 7.5);
Check.Eq(FakeHost.TapJumps, 1, "+2% is not a heal landing: the jump at 7.5 s");
var h = new Rig(healthPct: 20);
var h = new Rig(healthPct: 20, recall: false);
h.Run(0, 5.0);
h.V.CurrentHealth = 23; // +3: a heal landed
h.Run(5.1, 12.4);
@ -376,7 +399,7 @@ internal static class HpFailsafeTests
h.Run(12.5, 12.6);
Check.Eq(FakeHost.TapJumps, 1, "7.5 s after the heal with no other: the jump");
var o = new Rig(healthPct: 20);
var o = new Rig(healthPct: 20, recall: false);
o.Run(0, 5.0);
o.V.CurrentHealth = 31; // over Emergency Heal At 30
o.Run(5.1, 5.1);
@ -397,15 +420,17 @@ internal static class HpFailsafeTests
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 1, "recall off: the jump still");
Check.True(r.S.IsMacroRunning, "recall off: the macro keeps running");
Check.Eq(FakeHost.ChatCommands.Count, 0, "no recall");
Check.Eq(Rig.Recalls, 0, "no recall");
Check.True(r.Logged("HP Failsafe Recall is off"), "said once in the log");
var n = new Rig(healthPct: 20);
n.Run(0, 15.0);
n.Run(0, 5.0);
Check.False(n.S.IsMacroRunning, "recall: macro stopped");
n.Run(15.1, 25);
Check.Eq(FakeHost.ChatCommands.Count, 3, "no recall line: sent 3 times, 1.5 s apart, then stopped");
Check.True(n.Logged("no recall seen after 3 tries"), "and logged");
n.RunAnswered(5.1, 8.0);
Check.Eq(Rig.Recalls, 1, "the first cast; answered, no portal space");
n.RunAnswered(8.1, 25);
Check.Eq(Rig.Recalls, 3, "cast 3 times, 3 s apart, then stopped: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("HP failsafe")).TakeLast(8)));
Check.True(n.Logged("no portal space after 3 cast(s) of Lifestone Recall"), "and logged");
}
finally { Done(); }
}
@ -416,41 +441,22 @@ internal static class HpFailsafeTests
try
{
var n = new Rig(healthPct: 20);
n.Run(0, 15.0);
n.Run(0, 5.0);
Check.False(n.S.IsMacroRunning, "recall: macro stopped");
n.Run(15.1, 21.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line");
n.RunAnswered(5.1, 17.0);
Check.Eq(Rig.Recalls, 3, "3 casts, no portal space");
Check.True(n.S.IsMacroRunning, "the macro is back on (the heals and kits run again)");
Check.Eq(n.B.HpFailsafeRecallsFailed, 1, "a failed recall counted");
Check.True(FakeHost.Chat.Any(c => c.Contains("macro back on to keep healing")), "said in chat");
n.Run(21.1, 49.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "inside the 30 s cooldown: no recall");
n.RunAnswered(17.1, 40.0);
Check.Eq(Rig.Recalls, 3, "inside the 30 s cooldown: no recall");
Check.True(n.S.IsMacroRunning, "and the macro keeps running");
int breaks = FakeHost.Logs.Count(l => l.Contains("HP failsafe: health 20% at or under Emergency Heal At 30%, no heal landed in"));
Check.True(breaks >= 2, $"the failsafe re-armed: it reached the break stage again ({breaks})");
n.Run(49.1, 75.0);
Check.True(n.Logged("no recall: the last recall never started"), "the cooldown is said");
n.RunAnswered(40.1, 75.0);
Check.Eq(n.B.HpFailsafeRecalls, 2, "after the cooldown: the next recall");
Check.True(FakeHost.ChatCommands.Count > 3, "sent");
}
finally { Done(); }
}
// Only our own recall line ends the wait.
private static void RecallLineIsOurs()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall");
r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0);
r.Run(15.7, 17.1);
Check.Eq(FakeHost.ChatCommands.Count, 2, "another player's recall line: sent again");
Check.False(r.Logged("HP failsafe: the recall started"), "not taken as ours");
r.B.OnChatWindowText("ira is recalling to the lifestone.", 0); // the first letter dropped by the chat layer
r.Run(17.2, 22);
Check.Eq(FakeHost.ChatCommands.Count, 2, "ours (first letter dropped): no more sends");
Check.True(r.Logged("HP failsafe: the recall started"), "logged");
Check.True(Rig.Recalls > 3, "cast");
}
finally { Done(); }
}
@ -469,31 +475,31 @@ internal static class HpFailsafeTests
finally { Done(); }
}
// A pending recall is dropped on death: after the respawn it must not send /lifestone or switch
// A pending recall is dropped on death: after the respawn it must not cast the recall or switch
// the macro on, against Stop Macro On Death.
private static void DeathDropsRecall()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 15.0);
r.Run(0, 5.0);
Check.False(r.S.IsMacroRunning, "recall pending: macro stopped");
r.V.CurrentHealth = 0; // dead before the first send
r.Run(15.1, 30);
Check.Eq(FakeHost.ChatCommands.Count, 0, "0 health: no /lifestone");
r.V.CurrentHealth = 0; // dead before the first cast
r.Run(5.1, 30);
Check.Eq(Rig.Recalls, 0, "0 health: no Lifestone Recall");
Check.False(r.S.IsMacroRunning, "the macro stays off");
Check.True(r.Logged("the pending recall is dropped (dead)"), "logged");
// The plugin's death hold drops it too (the vitals cache still reads the old health).
var p = new Rig(healthPct: 20);
p.Run(0, 15.0);
p.Run(0, 5.0);
var plugin = new RynthAiPlugin();
PacerEdgeTests.SetHost(plugin, p.Host);
typeof(RynthAiPlugin).GetField("_buffManager", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(plugin, p.B);
FakeHost.Vitals = (0, 100, 0, 100, 0, 100);
typeof(RynthAiPlugin).GetMethod("HoldForDeath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(plugin, null);
p.Run(15.1, 30);
Check.Eq(FakeHost.ChatCommands.Count, 0, "death hold: no /lifestone after the respawn");
p.Run(5.1, 30);
Check.Eq(Rig.Recalls, 0, "death hold: no Lifestone Recall after the respawn");
Check.False(p.S.IsMacroRunning, "death hold: the macro stays off");
Check.True(p.Logged("the pending recall is dropped (death)"), "logged");
}
@ -507,26 +513,35 @@ internal static class HpFailsafeTests
{
var r = new Rig(healthPct: 20);
r.B.MayRestartMacro = () => false; // VTank runs and yield is on
r.Run(0, 21.0);
Check.Eq(FakeHost.ChatCommands.Count, 3, "3 tries, no recall line");
r.RunAnswered(0, 21.0);
Check.Eq(Rig.Recalls, 3, "3 casts, no portal space");
Check.False(r.S.IsMacroRunning, "VTank yield: the macro stays off");
Check.True(FakeHost.Chat.Any(c => c.Contains("the macro stays off (VTank yield)")), "said in chat");
}
finally { Done(); }
}
private static void RecallNameUnreadable()
// No recall the character can't make: without the spell, or with less mana than it costs, the jump
// runs, healing goes on and the macro keeps running; the reason is logged once per episode.
private static void NoSpellNoManaNoRecall()
{
try
{
var r = new Rig(healthPct: 20);
FakeHost.Names.Remove(Player);
r.Run(0, 15.6);
Check.Eq(FakeHost.ChatCommands.Count, 1, "the first recall");
r.B.OnChatWindowText("Bob is recalling to the lifestone.", 0);
r.Run(15.7, 20);
Check.Eq(FakeHost.ChatCommands.Count, 1, "no name to compare: taken as ours, no resend");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("our name could not be read")), 1, "logged once");
var r = new Rig(healthPct: 20, knowsRecall: false);
r.Run(0, 20);
Check.True(FakeHost.TapJumps >= 1, "the jump still");
Check.Eq(Rig.Recalls, 0, "no Lifestone Recall");
Check.True(r.S.IsMacroRunning, "the macro keeps running");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no recall: this character doesn't know Lifestone Recall")), 1, "said once");
var m = new Rig(healthPct: 20);
BuffManager.ManaCostOverride = id => id == BuffManager.RecallSpellId ? 50 : 0; // FakeHost.Reset sets 0 for all
m.V.CurrentMana = 10;
m.Run(0, 20);
Check.True(FakeHost.TapJumps >= 1, "no mana: the jump still");
Check.Eq(Rig.Recalls, 0, "no mana: no Lifestone Recall");
Check.True(m.S.IsMacroRunning, "no mana: the macro keeps running");
Check.True(m.Logged("is under Lifestone Recall's cost"), "said why");
}
finally { Done(); }
}

View file

@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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;
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
namespace RynthCore.RynthAiHostTests.Tests;
// The in-game self-test meta (GameTests\RynthSelfTest.af, 2026-10-22): RynthAi tests itself on a
// character by running this meta, and RynthCore's scripts\Run-GameTest.ps1 reads the results it saves
// (rt_<check> = PASS / FAIL / SKIP in the character's pvars). These check offline that it parses as
// written and that it walks its states and records results the way the script expects, on the fake
// clock with RynthAi's own chat lines fed in. Nothing here plays the game: the real run does that.
internal static class SelfTestMetaTests
{
private const uint Player = 0x50000A01;
private static readonly string[] States = { "Default", "T1 Buff", "T2 Fight", "T3 Loot", "T4 Craft", "T4 Craft run", "Done" };
public static void Register(Runner r)
{
r.Add("self-test meta: RynthSelfTest.af parses cleanly and every SetState goes to one of its states", ParsesCleanly);
r.Add("self-test meta: a run with nothing to fight or craft passes buffing, skips the rest, puts options back", PlaysThrough);
r.Add("self-test meta: buffing fails after 300 s without \"Force Rebuff Complete\"", BuffTimesOut);
r.Add("self-test meta: missile crafting passes on \"Equipped ammo\", fails on a crafting error", Crafting);
r.Add("self-test meta: ratargetcount[] is combat's target count; the fight is a SKIP when combat finds nothing to attack", FightTargets);
}
// The first run on Freya (2026-10-22) failed the fight beside a buff bot: wobjectfindnearestmonster[]
// found it (attackable), combat rightly left it alone, and after 180 s that read as a FAIL.
private static void FightTargets()
{
var bare = new Run(Host());
Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "-1", "not wired: -1");
bare.M.SetCombatTargetCount(() => 3);
Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "3", "wired: combat's count");
Run Beside(int targets)
{
FakeHost.Reset();
FakeHost.Names[Player] = "Selftest";
FakeHost.Positions[Player] = (0xA9B4001Cu, 50f, 50f, 0f);
const uint buffBot = 0x80000021;
FakeHost.Names[buffBot] = "Pumpkin Buffer";
FakeHost.Positions[buffBot] = (0xA9B4001Cu, 60f, 50f, 0f);
FakeHost.ItemTypes[buffBot] = 0x10;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { buffBot }, new Dictionary<uint, float> { [buffBot] = 1f });
var r = new Run(host, cache, "T2 Fight");
r.M.SetCombatTargetCount(() => targets);
return r;
}
var idle = Beside(0);
idle.Tick();
idle.Tick(2);
Check.Eq(idle.P("rt_fight"), "PENDING", "something attackable in view: no SKIP at 2 s");
Check.True(idle.S.EnableCombat, "combat on");
idle.Tick(27);
Check.Eq(idle.P("rt_fight"), "PENDING", "still waiting at 29 s");
idle.Tick(2);
Check.Eq(idle.P("rt_fight"), "SKIP", "SKIP at 30 s when combat's scan has no target");
Check.True(idle.P("rt_fight_why").Contains("Pumpkin Buffer"), "names what was in view: " + idle.P("rt_fight_why"));
var stuck = Beside(2);
stuck.Tick();
stuck.Tick(2);
stuck.Tick(30);
Check.Eq(stuck.P("rt_fight"), "PENDING", "combat has targets: no SKIP at 30 s");
stuck.Tick(150);
Check.Eq(stuck.P("rt_fight"), "FAIL", "targets but no kill in 180 s: FAIL");
Check.True(stuck.P("rt_fight_why").Contains("combat sees 2 target(s)"), "says what combat saw: " + stuck.P("rt_fight_why"));
}
private static LoadedMeta Load()
{
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent)
{
string path = Path.Combine(dir.FullName, "GameTests", "RynthSelfTest.af");
if (File.Exists(path)) return AfFileParser.LoadFromText(File.ReadAllText(path));
}
throw new FileNotFoundException("GameTests\\RynthSelfTest.af not found above " + AppContext.BaseDirectory);
}
private static IEnumerable<MetaRule> AllRules(IEnumerable<MetaRule> rules)
{
foreach (MetaRule r in rules)
{
yield return r;
foreach (MetaRule c in AllRules(r.Children)) yield return c;
foreach (MetaRule c in AllRules(r.ActionChildren)) yield return c;
}
}
private static void ParsesCleanly()
{
LoadedMeta meta = Load();
Check.Eq(string.Join(" | ", meta.Warnings), "", "no parse warnings");
Check.Eq(string.Join(", ", meta.DeclaredStates), string.Join(", ", States), "the states, in order");
Check.Eq(meta.StartState, "Default", "starts in Default");
var all = AllRules(meta.Rules).ToList();
// A DoAll's children are actions only (their Condition stays at the default, Never).
var conditions = meta.Rules.Concat(meta.Rules.SelectMany(r => AllRules(r.Children)));
Check.False(conditions.Any(r => r.Condition == C.Never), "no condition read as Never (an unknown keyword)");
// An All's children are conditions only (their Action stays None); a DoAll's are the actions.
var actions = meta.Rules.Concat(meta.Rules.SelectMany(r => AllRules(r.ActionChildren)));
Check.False(actions.Any(r => r.Action == A.None), "no action read as None (an unknown keyword)");
foreach (MetaRule r in all.Where(r => r.Action == A.SetMetaState))
Check.True(meta.DeclaredStates.Contains(r.ActionData), $"SetState {{{r.ActionData}}} (in {r.State}) is a declared state");
Check.True(all.Any(r => r.Action == A.ChatCommand && r.ActionData == "/ra stop"), "it stops the macro at the end");
}
private sealed class Run
{
public readonly LegacyUiSettings S;
public readonly MetaManager M;
public readonly List<string> Ra = new();
public DateTime Now = new(2026, 10, 22, 12, 0, 0);
public Run(RynthCoreHost host, WorldObjectCache? cache = null, string startState = "Default")
{
S = new LegacyUiSettings
{
IsMacroRunning = true, EnableMeta = true, CurrentState = startState, ForceStateReset = true,
EnableCombat = true, EnableBuffing = true, EnableLooting = true, EnableNavigation = true,
MetaRules = Load().Rules,
};
M = new MetaManager(S, host, new PlayerVitalsCache()) { Clock = () => Now };
M.SetPlayerId(Player);
M.SetRaCommandHandler(Ra.Add);
if (cache != null) M.SetObjectCache(cache);
}
public void Tick(double seconds = 0) { Now = Now.AddSeconds(seconds); M.Think(); }
/// <summary>Ticks a second at a time until the meta is in <paramref name="state"/>, at most <paramref name="max"/> times.</summary>
public bool TickUntil(string state, int max = 20)
{
for (int i = 0; i < max && !string.Equals(S.CurrentState, state, StringComparison.OrdinalIgnoreCase); i++) Tick(1);
return string.Equals(S.CurrentState, state, StringComparison.OrdinalIgnoreCase);
}
public void Chat(string line) { M.HandleChat(line); Tick(); }
public string P(string key) => M.Expressions.Evaluate($"getpvar[{key}]");
}
private static RynthCoreHost Host()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Selftest";
return FakeHost.Create();
}
private static void PlaysThrough()
{
var run = new Run(Host());
run.Tick();
Check.False(run.S.EnableCombat || run.S.EnableBuffing || run.S.EnableLooting || run.S.EnableNavigation, "Default turns combat, buffing, looting and nav off");
Check.Eq(run.P("rt_status"), "RUNNING", "rt_status RUNNING");
Check.Eq(run.P("rt_meta"), "PASS", "rt_meta PASS");
Check.Eq(run.P("rt_buff"), "PENDING", "rt_buff PENDING until tested");
Check.True(run.TickUntil("T1 Buff"), "on to T1 Buff");
run.Tick();
Check.True(run.S.EnableBuffing, "buffing on for the test");
Check.True(run.Ra.Any(c => c.Contains("buff force")), "asks for a force rebuff");
run.Chat("[RynthAi] Force Rebuff Complete.");
Check.Eq(run.P("rt_buff"), "PASS", "buffing PASS on \"Force Rebuff Complete\"");
Check.True(run.P("rt_buff_why").StartsWith("a force rebuff finished in "), "says how long it took: " + run.P("rt_buff_why"));
Check.True(run.TickUntil("Done"), "no monster, no kill, no bundles: on to Done");
Check.Eq(run.P("rt_fight"), "SKIP", "fight SKIP with no monster in view");
Check.Eq(run.P("rt_loot"), "SKIP", "looting SKIP without a kill");
Check.Eq(run.P("rt_craft"), "SKIP", "missile crafting SKIP without bundles");
run.Tick();
Check.Eq(run.P("rt_status"), "DONE", "rt_status DONE");
Check.True(run.S.EnableCombat && run.S.EnableBuffing && run.S.EnableLooting && run.S.EnableNavigation, "options put back as they were");
run.Tick(3);
Check.True(run.Ra.Any(c => c.TrimEnd().EndsWith("stop")), "stops the macro");
}
private static void BuffTimesOut()
{
var run = new Run(Host());
Check.True(run.TickUntil("T1 Buff"), "on to T1 Buff");
run.Tick();
run.Tick(299);
Check.Eq(run.P("rt_buff"), "PENDING", "still waiting at 299 s");
run.Tick(2);
Check.Eq(run.P("rt_buff"), "FAIL", "FAIL after 300 s");
Check.True(run.P("rt_buff_why").Contains("300 s"), "says why: " + run.P("rt_buff_why"));
var wedged = new Run(Host());
wedged.TickUntil("T1 Buff");
wedged.Tick();
wedged.Chat("[RynthAi] Can't enter Magic mode (no wand found) - buffing paused.");
Check.Eq(wedged.P("rt_buff"), "FAIL", "FAIL at once on a buffing error");
Check.True(wedged.P("rt_buff_why").StartsWith("Can't enter Magic mode"), "the error is the reason: " + wedged.P("rt_buff_why"));
}
private static (RynthCoreHost, WorldObjectCache) Archer()
{
var host = Host();
FakeHost.Names[0x60000001] = "Bundle of Deadly Prismatic Arrowheads";
FakeHost.Names[0x60000002] = "Bundle of Arrowshafts";
FakeHost.Containers[0x60000001] = Player;
FakeHost.Containers[0x60000002] = Player;
host = FakeHost.Create();
return (host, FakeHost.MakeCache(host, Player, new uint[] { 0x60000001, 0x60000002 }));
}
private static void Crafting()
{
var (host, cache) = Archer();
var run = new Run(host, cache, "T4 Craft");
Check.True(run.TickUntil("T4 Craft run"), "bundles carried, no melee weapon or wand in hand: the craft runs");
run.Tick();
run.Chat("[RynthAi Craft] No wielded Arrows. Evaluating...");
run.Chat("[RynthAi Craft] Crafting Deadly Prismatic Arrow x2");
Check.Eq(run.P("rt_craft"), "PENDING", "not decided while crafting");
run.Chat("[RynthAi Craft] Equipped ammo (id=0x80001234)");
Check.Eq(run.P("rt_craft"), "PASS", "PASS on \"Equipped ammo\"");
Check.True(run.P("rt_craft_why").StartsWith("made ammo from the bundles"), "says ammo was made: " + run.P("rt_craft_why"));
Check.Eq(run.S.CurrentState, "Done", "then Done");
var (host2, cache2) = Archer();
var rewield = new Run(host2, cache2, "T4 Craft");
rewield.TickUntil("T4 Craft run");
rewield.Tick();
rewield.Chat("[RynthAi Craft] Equipping Deadly Prismatic Arrow");
rewield.Chat("[RynthAi Craft] Equipped ammo (id=0x80001234)");
Check.True(rewield.P("rt_craft_why").StartsWith("put carried ammo back on"), "says carried ammo went back on: " + rewield.P("rt_craft_why"));
var (host3, cache3) = Archer();
var broken = new Run(host3, cache3, "T4 Craft");
broken.TickUntil("T4 Craft run");
broken.Tick();
broken.Chat("[RynthAi Craft] Craft timed out — no response from server");
Check.Eq(broken.P("rt_craft"), "FAIL", "FAIL on a crafting error");
Check.True(broken.P("rt_craft_why").StartsWith("Craft timed out"), "the error is the reason: " + broken.P("rt_craft_why"));
var (host4, cache4) = Archer();
var silent = new Run(host4, cache4, "T4 Craft");
silent.TickUntil("T4 Craft run");
silent.Tick();
silent.Tick(76);
Check.Eq(silent.P("rt_craft"), "FAIL", "FAIL when Missile Crafting says nothing for 75 s (the 10.19.1 break)");
}
}

View file

@ -96,8 +96,16 @@ internal static partial class Program
unsafe
{
Eq(RynthCore.Plugin.Shared.RynthAiHubApiV1.BaseStructSize, (uint)(8 + 10 * sizeof(nint)), "the hub table's base size (10 functions)");
Eq((uint)sizeof(RynthCore.Plugin.Shared.RynthAiHubApiV1), RynthCore.Plugin.Shared.RynthAiHubApiV1.BaseStructSize + (uint)sizeof(nint),
"SessionStatsMore appended right after the base");
// Append-only: each field added after the base sits at the offset readers check it by
// (VaultedDungeonsEnabled, BackAwayFrom and SetPlayerCounter came after SessionStatsMore).
RynthCore.Plugin.Shared.RynthAiHubApiV1 t = default;
byte* at = (byte*)&t;
Eq((int)((byte*)&t.SessionStatsMore - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.SessionStatsMoreOffset, "SessionStatsMore appended right after the base");
Eq((int)((byte*)&t.VaultedDungeonsEnabled - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.VaultedDungeonsEnabledOffset, "VaultedDungeonsEnabled next");
Eq((int)((byte*)&t.BackAwayFrom - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.BackAwayFromOffset, "BackAwayFrom next");
Eq((int)((byte*)&t.SetPlayerCounter - at), RynthCore.Plugin.Shared.RynthAiHubApiV1.SetPlayerCounterOffset, "SetPlayerCounter next");
Eq((uint)sizeof(RynthCore.Plugin.Shared.RynthAiHubApiV1), (uint)(RynthCore.Plugin.Shared.RynthAiHubApiV1.SetPlayerCounterOffset + sizeof(nint)),
"SetPlayerCounter is the last field (a new one appends here, with its own offset check)");
}
}

View file

@ -381,18 +381,22 @@ namespace RynthLua.ScriptWindowsTests
var (underId, under) = found.First(f => f.Id != iconId);
AcIconImage? both = AcIconDecoder.Compose(dat, iconId, underId, 0);
Check(both != null && both.Width == icon.Width && both.Height == icon.Height, "stacked: the icon's size");
if (both == null) return;
// Since 2026-10-09 (engine fd12e93) Compose repaints the dat's white outline band, as the client
// does, so the icon on its own is Compose with no layers, not the raw Decode.
AcIconImage? alone = AcIconDecoder.Compose(dat, iconId, 0, 0);
Check(alone != null && alone.Pixels.Length == icon.Pixels.Length, "the icon alone: same size as decoded");
if (both == null || alone == null) return;
bool overOk = true, underOk = true;
for (int i = 0; i < 1024; i++)
{
int a = icon.Pixels[i * 4 + 3];
if (a == 255 && !both.Pixels.AsSpan(i * 4, 4).SequenceEqual(icon.Pixels.AsSpan(i * 4, 4))) overOk = false;
if (a == 255 && !both.Pixels.AsSpan(i * 4, 4).SequenceEqual(alone.Pixels.AsSpan(i * 4, 4))) overOk = false;
if (a == 0 && !both.Pixels.AsSpan(i * 4, 4).SequenceEqual(under.Pixels.AsSpan(i * 4, 4)) && under.Pixels[i * 4 + 3] == 255) underOk = false;
}
Check(overOk, $"stacked: opaque icon pixels win (0x{iconId:X8} over 0x{underId:X8})");
Check(underOk, "stacked: where the icon is clear, the underlay shows");
AcIconImage? missingLayers = AcIconDecoder.Compose(dat, iconId, 0x06FFFFFE, 0x06FFFFFD);
Check(missingLayers != null && missingLayers.Pixels.AsSpan().SequenceEqual(icon.Pixels), "a missing underlay / overlay is left out");
Check(missingLayers != null && missingLayers.Pixels.AsSpan().SequenceEqual(alone.Pixels), "a missing underlay / overlay is left out");
Check(AcIconDecoder.Compose(dat, 0x06FFFFFE, underId, 0) == null, "no picture when the icon itself is missing");
}
}

View file

@ -1820,10 +1820,13 @@ namespace RynthLua.ScriptWindowsTests
int Renders() => (int)r.Eval("renders").Number;
long f = System.Diagnostics.Stopwatch.Frequency;
// Each pass is timed between a stamp before and one after it, not from "now" after it: on a
// busy PC the gap after a pass can be longer than the 1/60 s being checked (2026-10-22).
long before = System.Diagnostics.Stopwatch.GetTimestamp();
RunHudPasses(p);
long after = System.Diagnostics.Stopwatch.GetTimestamp();
Check(Renders() == 1 && h.EverPassed && !h.FirstPassSinceShown && !h.PassNow, "just shown: a pass on the first tick");
long left = h.NextPassAt - System.Diagnostics.Stopwatch.GetTimestamp();
Check(left > 0 && left <= f / 20, "the next pass is one 20/s interval away");
Check(h.NextPassAt > before && h.NextPassAt <= after + f / 20, "the next pass is one 20/s interval away");
RunHudPasses(p);
Check(Renders() == 1, "no pass before the interval");
h.NextPassAt = 0;
@ -1837,13 +1840,14 @@ namespace RynthLua.ScriptWindowsTests
Check(Renders() == 3 && h.NextPassAt == due + f / 20, "interval passes keep their cadence");
r.Do("hud.RefreshRate = 60");
before = System.Diagnostics.Stopwatch.GetTimestamp();
RunHudPasses(p);
left = h.NextPassAt - System.Diagnostics.Stopwatch.GetTimestamp();
Check(Renders() == 4 && left > 0 && left <= f / 60, "a new RefreshRate starts at once, 60/s");
after = System.Diagnostics.Stopwatch.GetTimestamp();
Check(Renders() == 4 && h.NextPassAt > before && h.NextPassAt <= after + f / 60, "a new RefreshRate starts at once, 60/s");
r.Do("hud.RefreshRate = 1");
before = System.Diagnostics.Stopwatch.GetTimestamp();
RunHudPasses(p);
left = h.NextPassAt - System.Diagnostics.Stopwatch.GetTimestamp();
Check(Renders() == 5 && left > f / 2, "1/s");
Check(Renders() == 5 && h.NextPassAt - before > f / 2, "1/s");
// Input: a pass on the next tick whatever the rate.
ApplyHudEvents(p, Ev(HudFormat.EvClicked, 1, h.Hash, Fnv("B", h.Hash), 1, 0));

View file

@ -44,6 +44,7 @@ internal static partial class Program
Run(nameof(RecallNotLinked), RecallNotLinked);
Run(nameof(DungeonLandblocksFromTheAtlas), DungeonLandblocksFromTheAtlas);
Run(nameof(AtlasSearchAndBestMatch), AtlasSearchAndBestMatch);
Run(nameof(AtlasRecallPlaces), AtlasRecallPlaces);
Run(nameof(ArrowSingleTarget), ArrowSingleTarget);
Run(nameof(ArrowAlongRoute), ArrowAlongRoute);
Run(nameof(FavoritesAndRecent), FavoritesAndRecent);
@ -380,6 +381,36 @@ internal static partial class Program
// ── Atlas ────────────────────────────────────────────────────────────────
// The recalls' landing spots are found by name (2026-10-22, Skippy: "neft" found nothing).
private static void AtlasRecallPlaces()
{
Atlas atlas = Atlas.Parse(@"{""locations"":[
{""id"":1,""name"":""Holtburg"",""type"":""Town"",""cell"":""A9B40019"",""place"":""outdoor"",""ns"":42.1,""ew"":33.6}],
""recalls"":[
{""spell"":5541,""name"":""Lost City of Neftet Recall"",""cell"":""8763000E"",""place"":""outdoor"",""ns"":-22.21,""ew"":6.22},
{""spell"":1635,""name"":""Ulgrim's Recall"",""cell"":""01960118"",""place"":""dungeon""},
{""spell"":1636,""name"":""Ulgrim's Recall"",""cell"":""01960118"",""place"":""dungeon""},
{""spell"":2479,""name"":""Advance Camp Recall"",""cell"":""027B0200"",""place"":""dungeon"",""in"":""Vile-Smelling Refuse""},
{""spell"":0,""name"":"" "",""cell"":""00000000"",""place"":""dungeon""}]}");
Check(atlas.Locations.Count == 1, "the recalls stay out of Locations (the route planner's list)");
Check(atlas.Recalls.Count == 5, "the recalls themselves unchanged");
Check(atlas.RecallPlaces.Count == 3, "three recall places (Ulgrim's twice is one; no name, none)");
bool allRecall = true;
foreach (var p in atlas.RecallPlaces) allRecall &= p.Type == Atlas.RecallType && p.Id < 0;
Check(allRecall, "type Recall, negative ids");
var hits = atlas.Search("neft", null, 10);
Check(hits.Count == 1 && hits[0].Name == "Lost City of Neftet Recall", "\"neft\" finds Lost City of Neftet Recall");
Check(hits.Count == 1 && hits[0].OnMap && Math.Abs(hits[0].Ns + 22.21) < 1e-9 && Math.Abs(hits[0].Ew - 6.22) < 1e-9, "at 22.21S, 6.22E");
var best = atlas.FindBest("neftet", false, 0, 0);
Check(best != null && best.Type == Atlas.RecallType, "/rnav go neftet resolves to it");
Check(atlas.FindBest("ulgrim", false, 0, 0) == null, "a dungeon recall is no arrow target");
var camp = atlas.Search("advance camp", null, 10);
Check(camp.Count == 1 && camp[0].Desc == "in Vile-Smelling Refuse", "a dungeon recall says where it is");
Check(atlas.Search("", Atlas.RecallType, 50).Count == 3, "the Recall type filter");
Check(atlas.Search("holtburg", null, 10).Count == 1, "other searches unchanged");
}
private static void AtlasSearchAndBestMatch()
{
Atlas atlas = Atlas.Parse(AtlasJson);