RynthAi: stuck-cast breaker, no re-send into a busy server, recovery retry, HP failsafe

Two casts were held open 40.8 s and 37 s by ACE's fast-tick turn-to-cast
wait; every later send was answered UseDone 0x1D and a heal was re-sent
every 2.5 s.

- ActionPacer: after a 0x1D UseDone nothing starts until the server answers;
  with no cast of ours open, one probe after 1.5 s, then doubling (max 6 s).
  Attack repeats are not held (ACE sends no UseDone for a swing), and a latch
  with no cast of ours open ends after LatchMaxMs (15 s). A cast still
  unanswered 1 s past its normal cycle (learned per spell, at least 3 s) is
  turned to face its target; 2 s past it (capped by Stuck Cast Break, default
  8000 ms) or on a 0x1D while it has been open 3 s, it is broken with a jump
  (TapJump; ACE fails a cast on a fast-tick jump). Starts wait until landed;
  no UseDone 3 s after landing -> Peace mode; 3 s more -> going on. Every
  hold is bounded: a cast StaleCastMs old, or sent before a frame gap of 5 s
  (keyed on the gap's end), is dropped with the latch, never broken. No
  breaker step in portal space; Forget on portal-enter and the death hold.
  A burst of 5 'too busy' answers in a second holds every start except a
  heal. A refused forced jump with no cast open leaves no breaker stage.
  A cast a script chose (the combat hook) is not jumped before 6 s from its
  send (ScriptCastMinBreakMs, the held-cast nudge's HeldAfterIncantMs).
  Stuck Cast Break is read from the settings once per tick.
- MoveAudit: no start in the tick of a movement change; 150 ms and a clear
  motion queue (or 600 ms) let it go. A held stop sent later by
  FlushPendingStops counts as a movement change too; the forced flush in
  CastSpellFor still goes out in the same tick as the cast that follows it.
- Blacklist: casts answered 0x1D (or unanswered while the server is busy) are
  not no-damage casts.
- Combat hook: ctx.pending is the cast in flight; ctx.last is the most recent
  RESOLVED cast, its err final (the first UseDone after its send; nil only
  when none could be read: 7 s timeout, or another answer came first). The
  casts in flight of both kinds resolve in send order through one queue.
  The send-time UseDone count comes from the pacer (LastCastSeqAtSend).
  CombatRequestV1 appends Resolved*/Pending* fields (StructSize-gated, no
  Version bump); an older RynthAi keeps the old ctx.last.
- HP failsafe (BuffManager.HpFailsafe.cs): at or under Emergency Heal At with
  no heal landing for 3 rounds of 2.5 s, a forced jump; 3 more rounds, the
  macro stops and /lifestone goes out (HP Failsafe Recall, default on).
  Nothing counts in portal space; a pending recall is dropped on death; a
  recall that never starts turns the macro back on (only one the failsafe
  stopped, never past the VTank yield) and re-arms after a 30 s cooldown.

Recovery retry: recovery vitals (Heal Self, Stamina to Health, Revitalize,
Stamina to Mana) refused for "not enough mana" retry after Recovery Retry
(200 ms, a setting) instead of resting the family: ACE rolls Mana Conversion
on every attempt before the windup and a refusal costs nothing. At most 5
recovery casts a second, 20 refusals in a row, stamina and Mana Conversion
checks, an episode with no refusal for 7 s ends; an episode summary line.
Stamina to Mana and Revitalize are still held under their cost by the mana
reserve (AttemptVitalCast), so for them the retry applies when the mana
reading is stale or costs are unknown; Heal Self and Stamina to Health,
which are tried below cost, gain the most.
When the retry stops, the vital rests as the existing mana reserve has it
(LowManaHealRestSec, 2 s). Script heals and other casts are unchanged.

Tests: StuckCastTests (incl. the script cast's break floor), PacerEdgeTests,
RecoveryRetryTests (incl. costs known: Stamina to Mana held), HpFailsafeTests,
CombatHookTests (ctx.last/ctx.pending, send order, an answer during the send,
0x1D blacklist, script heal keeps its rest, script attack and heal not jumped
before 6 s with or without a 'too busy' answer); HealLatencyTests' and ManaReserveTests' low-mana rest
cases pin untrained Mana Conversion; RynthLua compat combathook.lua.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-12 16:23:37 -07:00
commit 2d8bebb0f4
30 changed files with 3156 additions and 53 deletions

View file

@ -85,9 +85,13 @@ internal static unsafe class FakeHost
public static readonly List<bool> AutoRunCalls = new();
public static bool AutoRun;
public static int Jumps;
/// <summary>Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send).</summary>
public static Action? AfterCastSpell;
/// <summary>Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in <see cref="TapJumps"/>.</summary>
public static bool TapJumpCalls;
public static int TapJumps;
/// <summary>TapJump returns 0 (the client refused the jump); the call still counts in TapJumps.</summary>
public static bool TapJumpRefuse;
public static int Turns;
public static readonly List<(uint Target, int SpellId)> Casts = new();
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
@ -208,8 +212,8 @@ internal static unsafe class FakeHost
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
@ -651,10 +655,10 @@ internal static unsafe class FakeHost
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TapJump() { TapJumps++; return 1; }
private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; }
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -101,6 +101,10 @@ internal static class Program
CastNoDamageTests.Register(runner);
ManaReserveTests.Register(runner);
DamageRowsTests.Register(runner);
StuckCastTests.Register(runner);
PacerEdgeTests.Register(runner);
RecoveryRetryTests.Register(runner);
HpFailsafeTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -703,7 +703,7 @@ internal static class ActionPacingTests
_t += 110;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "the wand waits: the swing hasn't animated yet");
Check.True(why.Contains("swing"), "why: " + why);
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "the next attack isn't held");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "the next attack isn't held");
_t += 200;
FakeHost.CastBusy = 1;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits");
@ -830,10 +830,10 @@ internal static class ActionPacingTests
{
var host = World(combatMode: 2);
FakeHost.CastBusy = 1; // the last swing still plays
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "a melee attack repeat is not held by the animation");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "a melee attack repeat is not held by the animation");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything gated is");
host.UseFor(Corpse, "Loot", "open");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, gestureGate: false), "but an attack still waits for an unanswered corpse use (the server's turn)");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "but an attack still waits for an unanswered corpse use (the server's turn)");
FakeHost.UseDone(0);
Check.True(ActionPacer.Current(host) == null, "the use is answered");
ActionPacer.Enabled = false;

View file

@ -49,6 +49,15 @@ internal static class CombatHookTests
r.Add("combat hook: ctx.monsters leaves out a Priority 0 (ignored) monster, even one hitting us", HookScanSkipsIgnored);
r.Add("combat hook: a script answer at an ignored monster is rejected, even one hitting us (RynthAi casts its own)", HookRejectsIgnoredTarget);
r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget);
r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged);
r.Add("combat hook: ctx.pending is the cast in flight; ctx.last the last resolved one, err its first UseDone (final; -1 when missed or after 7 s)", LastErrIsTheCastsAnswer);
r.Add("combat hook: an attack and a heal in flight take their UseDones in send order (attack 0x401, heal 0)", AnswersInSendOrder);
r.Add("combat hook: a script heal refused for mana keeps its 2 s rest (no recovery fast retry)", ScriptHealNoFastRetry);
r.Add("combat hook: a script attack with no answer is not jumped in 5.5 s; RynthAi's own cast is", ScriptAttackNotJumpedEarly);
r.Add("combat hook: a script heal (a drain) with no answer is not jumped in 5.5 s", ScriptHealNotJumpedEarly);
r.Add("combat hook: a 'too busy' answer at 3.5 s does not jump a script attack before 6 s; RynthAi's own cast is jumped", ScriptAttackRefusalNoEarlyJump);
r.Add("combat hook: a 'too busy' answer at 3.5 s does not jump a script heal before 6 s", ScriptHealRefusalNoEarlyJump);
r.Add("combat hook: a UseDone that lands during the send is the cast's answer (ctx.last.err)", AnswerDuringSendIsTheCasts);
r.Add("combat hook: a script cast at the fight target is tagged for the Damage tab (element and tier from its spell)", ScriptCastAttribution);
r.Add("combat hook: a heal request names the fight target and its health; a nil answer target still heals the player", HealRequestNamesFightTarget);
r.Add("combat hook: a refusal after another cast (a heal) or after the script spell landed does not park the script spell", RefusalNotMisattributed);
@ -584,8 +593,9 @@ internal static class CombatHookTests
public readonly PlayerVitalsCache V;
public readonly CombatManager C;
public readonly WorldObjectCache Cache;
public readonly RynthCoreHost Host;
public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0)
public HealRig(int healthPct = 40, int mode = CombatMode.Magic, int emergencyAt = 0, Action? setup = null)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
@ -599,7 +609,8 @@ internal static class CombatHookTests
FakeHost.Names[(uint)Target] = "Drudge Skulker";
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f);
FakeHost.ItemTypes[(uint)Target] = 0x10;
var host = FakeHost.Create(Player);
setup?.Invoke();
var host = Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = emergencyAt, StaminaToHealthAt = 0,
@ -916,6 +927,24 @@ internal static class CombatHookTests
Check.False(FakeHost.Casts.Any(c => c.SpellId == drain), "the drain is not cast");
});
// Recovery retry: only RynthAi's own recovery vitals retry fast after "not enough mana"; a script's heal
// (even the same Heal Self) keeps the rest it had, with Mana Conversion trained.
private static void ScriptHealNoFastRetry() => Guard(() =>
{
int heal = Id("Heal Self V");
var rig = new HealRig();
FakeHost.Skills[(Player, 16)] = (300, 2); // Mana Conversion trained
Claim(HealKind);
rig.B.CheckVitals();
CombatHook.Decide(OpenSeq(HealKind), HealKind, (uint)heal, 0, 0);
rig.B.CheckVitals();
Check.Eq(FakeHost.Casts.Single(), (Player, heal), "the script's Heal Self V is cast");
rig.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
Check.False(rig.B.RecoveryRetryOpen, "a script heal: no fast-retry episode");
Check.True(FakeHost.Logs.Any(l => l.Contains("not enough mana; resting the family 2s")), "the 2 s heal rest, as before");
Check.False(FakeHost.Logs.Any(l => l.Contains("retrying in 200 ms")), "no retry line");
});
private static void NoJudgeSkipsBlacklist() => Guard(() =>
{
int drain = Id("Drain Health Other V");
@ -951,6 +980,310 @@ internal static class CombatHookTests
}
});
// In a client log, three healthy targets were blacklisted "after 3 no-damage casts" whose casts
// the server had refused with UseDone 0x1D.
private static void RefusedCastsNotJudged() => Guard(() =>
{
int drain = Id("Drain Health Other V");
foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr })
{
string what = answer == 0 ? "answered 0" : "answered 0x1D";
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
rig.S.BlacklistAttempts = 2;
rig.S.EnableRaycasting = false;
Claim(Atk);
for (int i = 0; i < 2; i++)
{
ScriptCast(rig, drain);
Check.Eq(FakeHost.Casts.Count, i + 1, $"{what}: cast {i + 1} went out");
FakeHost.UseDone(answer);
SetField(rig.C, "_pendingOffensiveCastAt", DateTime.Now.AddSeconds(-5));
CallPrivate(rig.C, "JudgePendingOffensiveCast");
if (Field<DateTime>(rig.C, "_pendingJudgeCastAt") != DateTime.MinValue)
SetField(rig.C, "_pendingJudgeCastAt", DateTime.Now.AddSeconds(-30));
CallPrivate(rig.C, "JudgePendingCast");
}
if (answer == 0)
Check.Eq(rig.C.activeTargetId, 0, "answered 0: two no-damage casts blacklist and drop the target");
else
{
Check.Eq(rig.C.activeTargetId, Target, "answered 0x1D: refusals are not casts, the target is kept");
Check.Eq(rig.C.RefusedCastsNotJudged, 2, "both kept out of the count");
Check.True(FakeHost.Logs.Any(l => l.Contains("refused 'too busy' (UseDone 0x1D): not counted")), "logged");
}
}
});
private static void LastErrIsTheCastsAnswer() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
FakeHost.UseDone(0); // an earlier answer
CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError);
try
{
Claim(Atk);
ScriptCast(rig, drain);
uint firstSeq = CombatHook.Attack.PendingSeq;
rig.Attack(); // the next request opens
Check.True(CombatHook.Poll(Atk, out var r1), "a request is open");
Check.Eq(r1.PendingSpell, (uint)drain, "ctx.pending: the drain, in flight");
Check.Eq(r1.PendingSeq, firstSeq, "ctx.pending.seq");
Check.Eq(r1.ResolvedSpell, 0u, "ctx.last: no resolved cast yet");
Check.Eq(r1.ResolvedErr, -1, "no answer: -1 (nil in Lua)");
FakeHost.UseDone(ActionPacer.TooBusyErr);
CombatHook.ObserveUseDone();
FakeHost.UseDone(0); // a later answer (another action) must not overwrite it
CombatHook.ObserveUseDone();
Check.True(CombatHook.Poll(Atk, out var r2), "still open");
Check.Eq((r2.ResolvedSeq, r2.ResolvedSpell), (firstSeq, (uint)drain), "ctx.last: the drain, resolved");
Check.Eq(r2.ResolvedErr, (int)ActionPacer.TooBusyErr, "its own answer: 0x1D, final");
Check.Eq(r2.PendingSpell, 0u, "ctx.pending: none");
// Its first answer missed (two UseDones before RynthAi looked): resolved with none (-1),
// not with the second one's error.
ScriptCast(rig, drain);
uint secondSeq = CombatHook.Attack.PendingSeq;
Check.True(secondSeq != 0 && secondSeq != firstSeq, "the second cast is in flight");
FakeHost.UseDone(ActionPacer.TooBusyErr);
FakeHost.UseDone(0);
CombatHook.ObserveUseDone();
rig.Attack();
Check.True(CombatHook.Poll(Atk, out var r3), "a request is open");
Check.Eq(r3.ResolvedSeq, secondSeq, "ctx.last: the second cast");
Check.Eq(r3.ResolvedErr, -1, "its answer was not read: -1, not the later 0");
// No UseDone at all: resolved with none after ResolveTimeoutMs.
ScriptCast(rig, drain);
uint thirdSeq = CombatHook.Attack.PendingSeq;
_now += RynthAiCombat.ResolveTimeoutMs - 1;
CombatHook.ObserveUseDone();
Check.Eq(CombatHook.Attack.PendingSeq, thirdSeq, "just under the timeout: still in flight");
_now += 1;
CombatHook.ObserveUseDone();
Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (thirdSeq, -1), "at the timeout: resolved, no answer");
// The next cast goes out before any answer to this one: this one resolves first, with none.
uint SendOne()
{
Claim(Atk); // the lease ran out with the clock
var slot = CombatHook.Attack;
CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _);
Check.True(CombatHook.Decide(slot.Request.Seq, Atk, (uint)drain, 0, 0), "decided");
Check.Eq(CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _), CombatHook.Outcome.Decided, "taken");
uint seq = slot.Request.Seq;
CombatHook.Cast(slot, (uint)drain, 0x80000777u);
return seq;
}
uint fourthSeq = SendOne();
Check.Eq(CombatHook.Attack.PendingSeq, fourthSeq, "the fourth cast is in flight");
uint fifthSeq = SendOne();
Check.Eq(CombatHook.Attack.PendingSeq, fifthSeq, "the fifth cast is in flight");
Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (fourthSeq, -1), "the fourth: resolved by the fifth's send, no answer");
}
finally { CombatHook.LastUseDone = null; }
});
// An attack unanswered, then a heal sent: the UseDones answer them in send order.
private static void AnswersInSendOrder() => Guard(() =>
{
int drain = Id("Drain Health Other V");
int heal = Id("Heal Other V");
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
FakeHost.UseDone(0);
CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError);
try
{
Claim(Atk | HealKind);
uint Send(CombatHook.Slot slot, uint kind, int spell)
{
CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _);
Check.True(CombatHook.Decide(slot.Request.Seq, kind, (uint)spell, 0, 0), "decided");
Check.Eq(CombatHook.Step(slot, 0x80000777u, () => new CombatRequestV1(), null, out _, out _, out _), CombatHook.Outcome.Decided, "taken");
uint seq = slot.Request.Seq;
CombatHook.Cast(slot, (uint)spell, 0x80000777u);
return seq;
}
uint atkSeq = Send(CombatHook.Attack, Atk, drain);
uint healSeq = Send(CombatHook.Heal, HealKind, heal);
Check.Eq(CombatHook.Attack.PendingSeq, atkSeq, "the attack is in flight");
Check.Eq(CombatHook.Heal.PendingSeq, healSeq, "the heal is in flight");
FakeHost.UseDone(0x401);
CombatHook.ObserveUseDone();
Check.Eq((CombatHook.Attack.ResolvedSeq, CombatHook.Attack.ResolvedErr), (atkSeq, 0x401), "the first answer is the attack's");
Check.Eq(CombatHook.Heal.PendingSeq, healSeq, "the heal waits for its own");
FakeHost.UseDone(0);
CombatHook.ObserveUseDone();
Check.Eq((CombatHook.Heal.ResolvedSeq, CombatHook.Heal.ResolvedErr), (healSeq, 0), "the second is the heal's");
}
finally { CombatHook.LastUseDone = null; }
});
// -- The stuck-cast breaker and the hook: both hook paths mark their cast as a script's
// (ActionPacer.MarkScriptCast), and the breaker gives it ScriptCastMinBreakMs from the send.
private static long _paceT;
private static void PacerGates()
{
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.TapJumpCalls = true;
}
private static void PaceOn()
{
_paceT = 70_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _paceT;
MoveAudit.Reset();
MoveAudit.NowMs = () => _paceT;
ActionPacer.StuckCastMs = 8000;
FakeHost.UseDone(0); // an earlier action's answer: the observer's baseline
}
private static void PaceOff()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
}
/// <summary>The pacer's checks every 100 ms for <paramref name="ms"/> (no UseDone comes).</summary>
private static void RunPacer(RynthCoreHost host, long ms)
{
for (long s = 0; s < ms; s += 100) { _paceT += 100; ActionPacer.MayStart(host, "Test", HealNeed.Heal, out _); }
}
/// <summary>A heal let ahead of the open cast, answered 'too busy' (the refusal trigger).</summary>
private static void RefuseAnother(RynthCoreHost host)
{
int heal = Id("Heal Self V");
Check.True(host.CastSpellFor(Player, heal, "Buff", "Heal Self V"), "another send");
FakeHost.UseDone(ActionPacer.TooBusyErr);
}
private static void ScriptHealCast(HealRig rig, int drain)
{
Claim(HealKind);
rig.B.CheckVitals();
CombatHook.Decide(OpenSeq(HealKind), HealKind, (uint)drain, (uint)Target, 0);
rig.B.CheckVitals();
Check.Eq(FakeHost.Casts.Single(), ((uint)Target, drain), "the script's drain went out");
}
private static void ScriptAttackNotJumpedEarly() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var own = new AttackRig(setup: PacerGates);
PaceOn();
try
{
Check.True(own.Host.CastSpellFor((uint)Target, drain, "Combat", "Drain Health Other V"), "control: RynthAi's own cast");
RunPacer(own.Host, 5500);
Check.Eq(FakeHost.TapJumps, 1, "control: RynthAi's own cast is jumped at 5 s (cycle 3 s + 2 s)");
}
finally { PaceOff(); }
var rig = new AttackRig(setup: PacerGates);
PaceOn();
try
{
Claim(Atk);
ScriptCast(rig, drain);
Check.Eq(FakeHost.Casts.Last(), ((uint)Target, drain), "the script's drain went out");
RunPacer(rig.Host, 5500);
Check.Eq(FakeHost.TapJumps, 0, "a script attack: no jump in 5.5 s");
}
finally { PaceOff(); }
});
private static void ScriptHealNotJumpedEarly() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var rig = new HealRig(setup: PacerGates);
PaceOn();
try
{
ScriptHealCast(rig, drain);
RunPacer(rig.Host, 5500);
Check.Eq(FakeHost.TapJumps, 0, "a script heal: no jump in 5.5 s");
}
finally { PaceOff(); }
});
private static void ScriptAttackRefusalNoEarlyJump() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var own = new AttackRig(setup: PacerGates);
PaceOn();
try
{
Check.True(own.Host.CastSpellFor((uint)Target, drain, "Combat", "Drain Health Other V"), "control: RynthAi's own cast");
RunPacer(own.Host, 3500);
Check.Eq(FakeHost.TapJumps, 0, "control: no jump before the refusal");
RefuseAnother(own.Host);
RunPacer(own.Host, 200);
Check.Eq(FakeHost.TapJumps, 1, "control: a 0x1D past 3 s jumps RynthAi's own cast at once");
}
finally { PaceOff(); }
var rig = new AttackRig(setup: PacerGates);
PaceOn();
try
{
Claim(Atk);
ScriptCast(rig, drain);
RunPacer(rig.Host, 3500);
RefuseAnother(rig.Host);
RunPacer(rig.Host, 2000);
Check.Eq(FakeHost.TapJumps, 0, "a script attack: a 0x1D at 3.5 s does not jump it by 5.5 s");
}
finally { PaceOff(); }
});
private static void ScriptHealRefusalNoEarlyJump() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var rig = new HealRig(setup: PacerGates);
PaceOn();
try
{
ScriptHealCast(rig, drain);
RunPacer(rig.Host, 3500);
RefuseAnother(rig.Host);
RunPacer(rig.Host, 2000);
Check.Eq(FakeHost.TapJumps, 0, "a script heal: a 0x1D at 3.5 s does not jump it by 5.5 s");
}
finally { PaceOff(); }
});
private static void AnswerDuringSendIsTheCasts() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
FakeHost.UseDone(0); // an earlier answer
CombatHook.LastUseDone = () => (FakeHost.UseDoneSeq, FakeHost.LastUseDoneError);
try
{
Claim(Atk);
FakeHost.AfterCastSpell = () => FakeHost.UseDone(0x402); // the answer lands before CombatHook.Cast runs
ScriptCast(rig, drain);
FakeHost.AfterCastSpell = null;
uint seq = CombatHook.Attack.PendingSeq;
Check.True(seq != 0, "the drain is in flight");
rig.Attack(); // the next request opens (ctx as the script sees it)
Check.True(CombatHook.Poll(Atk, out var r), "a request is open");
Check.Eq((r.ResolvedSeq, r.ResolvedSpell), (seq, (uint)drain), "ctx.last: the drain");
Check.Eq(r.ResolvedErr, 0x402, "ctx.last.err: the answer that came during the send");
}
finally { CombatHook.LastUseDone = null; FakeHost.AfterCastSpell = null; }
});
private static void ScriptCastAttribution() => Guard(() =>
{
int shock = Id("Shock Wave IV");

View file

@ -184,6 +184,9 @@ internal static class HealLatencyTests
{
var r = new Rig(healthPct: 40, manaPct: 2);
r.S.GetManaAt = 50; r.S.TopOffMana = 50;
// Mana Conversion untrained: the rests below. Trained, a recovery vital retries in 200 ms
// instead (RecoveryRetryTests).
FakeHost.Skills[(Player, 16)] = (10, 1);
Check.True(r.B.CheckVitals(), "40% health: Heal Self is cast");
Check.Eq(HealSelfCasts(), 1, "one Heal Self");
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);

View file

@ -0,0 +1,363 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
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 on).
internal static class HpFailsafeTests
{
private const uint Player = 0x50000B31;
private const uint STypeLife = 33;
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: 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: 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 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("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);
}
// No re-send into a busy server: a client log re-sent a heal every 2.5 s (the vitals give-up) into a server
// answering 0x1D. Through the whole vitals step (BuffManager heartbeats, pacer on, the pacer's
// breaker off to isolate the latch): a heal goes out, the server never answers it, and another
// send is refused 0x1D. No heal is re-sent while that heal is unanswered.
private static void VitalResendObeysLatch()
{
try
{
var r = new Rig(healthPct: 40);
r.S.EmergencyHealAt = 0; // the failsafe out of it
r.S.SpellCastIntervalMs = 100;
r.Run(0, 0);
Check.Eq(FakeHost.Casts.Count, 1, "the heal goes out (and is never answered)");
r.Run(0.1, 0.5);
int heal = FakeHost.Casts[0].SpellId;
// Another send goes out over the open heal (as when a cast hangs) and is refused 'too busy'.
Check.True(r.Host.CastSpellFor(0x80000AAAu, 1237, "Combat", "Drain Health Other I"), "the other send");
FakeHost.UseDone(ActionPacer.TooBusyErr);
// Real time too: BuffManager's own retry limits run on the real clock.
for (int ms = 600; ms <= 6000; ms += 200) { System.Threading.Thread.Sleep(200); r.At(ms / 1000.0); r.B.OnHeartbeat(); }
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == heal), 1, "no heal re-sent in 6 s (the 2.5 s give-up re-sent one before): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("[Pace]") || l.Contains("[Buff")).Take(20)));
Check.True(r.Logged("Buff waits:") && r.Logged("nothing goes until the server answers"), "the hold is logged: " + string.Join(" | ", FakeHost.Logs.Take(30)));
}
finally { Done(); }
}
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 19, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public readonly RynthCore.PluginSdk.RynthCoreHost Host;
public int MacroStops;
public Rig(int healthPct = 20)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.TapJumpCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = (0x6347028Au, 100f, 100f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
var host = Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false, SpellCastIntervalMs = 100,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache
{
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
MaxMana = 100, CurrentMana = 100,
};
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
B.MacroStopForRecall = () => MacroStops++;
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.StuckCastMs = 0; // the pacer's own breaker off: only the failsafe jumps here
ActionPacer.NowMs = () => 50_000_000 + (long)(NowAt - T0).TotalMilliseconds;
MoveAudit.Reset();
MoveAudit.NowMs = ActionPacer.NowMs;
FakeHost.UseDone(0);
}
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));
/// <summary>Heartbeats every 100 ms from <paramref name="from"/> up to and including <paramref name="to"/>.</summary>
public void Run(double from, double to)
{
for (int ms = (int)Math.Round(from * 1000); ms <= (int)Math.Round(to * 1000); ms += 100)
{
At(ms / 1000.0);
B.OnHeartbeat();
}
}
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
}
private static void BreakThenRecall()
{
try
{
var r = new Rig(healthPct: 20);
r.Run(0, 7.4);
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(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.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");
}
finally { Done(); }
}
private static void HealLandingResets()
{
try
{
var r = new Rig(healthPct: 20);
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);
h.Run(0, 5.0);
h.V.CurrentHealth = 23; // +3: a heal landed
h.Run(5.1, 12.4);
Check.Eq(FakeHost.TapJumps, 0, "a heal landed at 5 s: no jump at 7.5 s, none by 12.4 s");
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);
o.Run(0, 5.0);
o.V.CurrentHealth = 31; // over Emergency Heal At 30
o.Run(5.1, 5.1);
o.V.CurrentHealth = 20;
o.Run(5.2, 12.6);
Check.Eq(FakeHost.TapJumps, 0, "over the line at 5.1 s: the count started again at 5.2 s");
Check.True(o.Logged("HP failsafe: health back to 31%"), "the end is logged");
}
finally { Done(); }
}
private static void RecallOffAndResends()
{
try
{
var r = new Rig(healthPct: 20);
r.S.HpFailsafeRecall = false;
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.True(r.Logged("HP Failsafe Recall is off"), "said once in the log");
var n = new Rig(healthPct: 20);
n.Run(0, 15.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");
}
finally { Done(); }
}
// A recall that never starts must not leave the macro stopped at low health.
private static void FailedRecallResumes()
{
try
{
var n = new Rig(healthPct: 20);
n.Run(0, 15.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");
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");
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.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");
}
finally { Done(); }
}
// Emergency Heal At 100 at full health is not an emergency.
private static void FullHealthAtHundred()
{
try
{
var r = new Rig(healthPct: 100);
r.S.EmergencyHealAt = 100;
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 0, "100% at Emergency Heal At 100: no break");
Check.True(r.S.IsMacroRunning, "no recall");
}
finally { Done(); }
}
// A pending recall is dropped on death: after the respawn it must not send /lifestone 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);
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");
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);
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");
Check.False(p.S.IsMacroRunning, "death hold: the macro stays off");
Check.True(p.Logged("the pending recall is dropped (death)"), "logged");
}
finally { Done(); }
}
// The failsafe's restart is a macro start like any other.
private static void VTankYieldRespected()
{
try
{
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");
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()
{
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");
}
finally { Done(); }
}
// Nothing counts in portal space.
private static void NothingInPortalSpace()
{
try
{
var r = new Rig(healthPct: 20);
FakeHost.Portaling = true;
r.Run(0, 20);
Check.Eq(FakeHost.TapJumps, 0, "portal space: no failsafe jump");
Check.True(r.S.IsMacroRunning, "no recall");
Check.Eq(r.B.HpFailsafeBreaks, 0, "nothing counted");
}
finally { FakeHost.Portaling = false; Done(); }
}
}

View file

@ -154,6 +154,9 @@ internal static class ManaReserveTests
// and mana regenerates meanwhile with attacks still held.
var u = new Rig(mana: 50);
BuffManager.ManaCostOverride = _ => 0;
// Mana Conversion untrained: the rest below. Trained, a recovery vital retries in 200 ms
// instead (RecoveryRetryTests).
FakeHost.Skills[(Player, 16)] = (10, 1);
Check.True(u.B.CheckVitals(), "50/383 under Get Mana At: Stamina to Mana goes");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
u.B.OnChatWindowText(NotEnoughMana, 0);

View file

@ -0,0 +1,335 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Bounds on the pacer's holds: the 0x1D latch must not throttle melee and missile (ACE sends no
// UseDone for a swing), StuckCastMs = 0 must not hold for ever, a teleport's gap must not break a
// cast by jump, the settle gate stands apart from the animation gate, and only 'too busy' answers
// count toward the refusal burst.
internal static class PacerEdgeTests
{
private const uint Player = 0x50000F21;
private const uint Monster = 0x80116791;
private const int DrainHealthOtherI = 1237;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("pacer edge: after a lone 'too busy' answer, attack repeats go (over 50 swings in 60 s); a cast with ours open is still held", AttackRepeatsPastLatch);
r.Add("pacer edge: a 'too busy' latch with no cast of ours open ends after LatchMaxMs (logged once)", LatchExpires);
r.Add("pacer edge: StuckCastMs 0 never deadlocks: a hung cast is dropped as stale by StaleCastMs (inside 120 s)", StuckCastZeroBounded);
r.Add("pacer edge: in portal space nothing is broken (no jump, ForceBreak refused); a cast sent before a 20 s gap is dropped, not jumped", PortalAndGap);
r.Add("pacer edge: 5 'too busy' answers in one second hold every start but a heal, attack repeats too, for the rest of that second", RefusalBurst);
r.Add("pacer edge: the settle gate holds a start with the animation gate off", SettleGateSplit);
r.Add("pacer edge: portal-enter and the death hold forget the open cast and the latch", PortalAndDeathForget);
r.Add("pacer edge: a client-refused forced jump with no cast open does not hold starts for good (latch expiry, probe)", RefusedForcedJumpNoDeadlock);
r.Add("pacer edge: the refusal burst counts 'too busy' only and never holds a heal", BurstCountsTooBusyAndSparesHeals);
}
private static long _t;
private static RynthCoreHost Setup()
{
FakeHost.Reset();
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.WeaponCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.TapJumpCalls = true;
FakeHost.CombatModeValue = ActionPacer.MagicMode;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = Me0;
FakeHost.Positions[Player] = Me0;
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z);
var host = FakeHost.Create(Player);
_t = 70_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _t;
MoveAudit.Reset();
MoveAudit.NowMs = () => _t;
ActionPacer.StuckCastMs = 8000;
FakeHost.UseDone(0);
ActionPacer.MayStart(host, "Setup", HealNeed.None, out _); // the UseDone observer's baseline
return host;
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
FakeHost.Portaling = false;
}
private static bool May(RynthCoreHost host) => ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _);
private static bool Swing(RynthCoreHost host, out string why) =>
ActionPacer.MayStart(host, "Combat", HealNeed.None, out why, animationGate: false, settleGate: false, attackRepeat: true);
private static void Cast(RynthCoreHost host) =>
Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", "Drain Health Other I"), "cast sent");
private static int Jumps() => FakeHost.TapJumps + FakeHost.Jumps;
private static void AttackRepeatsPastLatch()
{
var host = Setup();
try
{
FakeHost.CombatModeValue = 2; // melee
FakeHost.UseDone(ActionPacer.TooBusyErr); // a lone 0x1D (a pickup, a player command)
Check.False(May(host), "a gated start is held by the latch");
Check.True(ActionPacer.ServerBusy, "latched");
int swings = 0;
for (int i = 0; i < 60; i++)
{
_t += 1000;
if (Swing(host, out _)) { swings++; ActionPacer.NoteAttackSent(); }
}
Check.True(swings > 55, $"a swing a second for 60 s after the 0x1D (no UseDone ever comes for a swing): {swings}");
// Our cast open (hung past CastMaxMs) and another send refused 'too busy': a cast is still held.
var h2 = Setup();
ActionPacer.StuckCastMs = 0;
Cast(h2);
_t += ActionPacer.CastMaxMs + 100;
Check.False(May(h2), "our cast hung");
FakeHost.UseDone(ActionPacer.TooBusyErr);
bool any = false;
for (int i = 0; i < 50; i++) { _t += 100; any |= May(h2); }
Check.False(any, "a cast with ours open and refused: held");
}
finally { Done(); }
}
private static void LatchExpires()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host); // observed here: the latch starts
long t0 = _t;
while (_t + 100 < t0 + ActionPacer.LatchMaxMs) { _t += 100; May(host); }
Check.True(ActionPacer.ServerBusy, "still latched just under LatchMaxMs");
Check.Eq(ActionPacer.LatchExpiries, 0L, "no expiry yet");
_t = t0 + ActionPacer.LatchMaxMs;
Check.True(May(host), "at LatchMaxMs: free");
Check.False(ActionPacer.ServerBusy, "the latch is gone");
Check.Eq(ActionPacer.LatchExpiries, 1L, "one expiry");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no answer cleared the 'too busy' latch in")), 1, "logged once");
}
finally { Done(); }
}
private static void StuckCastZeroBounded()
{
var host = Setup();
ActionPacer.StuckCastMs = 0;
try
{
Cast(host);
long t0 = _t;
_t += ActionPacer.CastMaxMs + 100;
Check.False(May(host), "our cast hung");
FakeHost.UseDone(ActionPacer.TooBusyErr); // another send refused while it is open
long freeAt = -1;
while (_t < t0 + 120_000) { _t += 100; if (May(host)) { freeAt = _t - t0; break; } }
Check.True(freeAt > 0, "free within 120 s");
Check.True(freeAt >= ActionPacer.StaleCastMs - 100 && freeAt <= ActionPacer.StaleCastMs + 100, $"free at StaleCastMs ({ActionPacer.StaleCastMs}): {freeAt}");
Check.Eq(Jumps(), 0, "StuckCastMs 0: no jump");
Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("dropped, the server is taken as free")), "logged");
}
finally { Done(); }
}
private static void PortalAndGap()
{
var host = Setup();
try
{
Cast(host);
FakeHost.Portaling = true;
for (int i = 0; i < 150; i++) { _t += 100; May(host); } // 15 s in portal space
Check.Eq(Jumps(), 0, "portal space: no breaker jump");
Check.False(ActionPacer.ForceBreak(host, "test"), "portal space: ForceBreak refused");
Check.Eq(Jumps(), 0, "still no jump");
FakeHost.Portaling = false;
// A 20 s gap with no check (a freeze, a long portal with the macro off): stale, dropped.
// The tick's frame, then the cast 5 ms later in the same tick, then the freeze.
var g = Setup();
ActionPacer.NoteFrame();
_t += 5;
Cast(g);
_t += 20_000;
ActionPacer.NoteFrame(); // the first frame after the freeze
Check.True(May(g), "after the gap: the cast is dropped and starts go");
Check.Eq(Jumps(), 0, "no jump for a cast sent before the gap");
Check.Eq(ActionPacer.StaleDrops, 1L, "one stale drop");
Check.True(FakeHost.Logs.Any(l => l.Contains("is stale (") && l.Contains("ms gap with no check")), "the gap is in the line");
// Control: the same 20 s with frames every 100 ms is a stuck cast, broken by the jump.
var c = Setup();
Cast(c);
for (int i = 0; i < 200; i++) { _t += 100; ActionPacer.NoteFrame(); May(c); }
Check.True(Jumps() >= 1, "no gap: the stuck cast is broken (control)");
Check.Eq(ActionPacer.StaleDrops, 0L, "and not dropped");
}
finally { Done(); }
}
private static void RefusalBurst()
{
var host = Setup();
try
{
FakeHost.CombatModeValue = 2;
string why = "";
bool[] free = new bool[ActionPacer.RefusalBurstMax];
for (int i = 0; i < ActionPacer.RefusalBurstMax; i++)
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 50;
free[i] = Swing(host, out why);
}
Check.True(free.Take(ActionPacer.RefusalBurstMax - 1).All(b => b), "4 refusals: still free");
Check.False(free[^1], "the 5th refusal inside a second: held");
Check.True(why.Contains("refusals from the server in the last second"), "why: " + why);
Check.False(May(host), "a gated start too");
Check.True(ActionPacer.BurstHolds >= 1, "counted (the heal start above is held by the latch, not the burst)");
_t += 1000;
Check.True(Swing(host, out _), "a second later: free");
}
finally { Done(); }
}
private static void SettleGateSplit()
{
var host = Setup();
try
{
FakeHost.AutoRun = true;
host.SetAutoRunBy("Nav", true);
_t += 1000;
host.SetAutoRunBy("Nav", false); // the stop goes out this tick
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why, animationGate: false),
"animation gate off, settle gate on: held in the tick of the stop");
Check.True(why.Length > 0, "why: " + why);
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false, settleGate: false),
"both off: free (only attack repeats do this)");
_t += MoveAudit.MoveSettleMinMs;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _, animationGate: false), "settled: free");
}
finally { Done(); }
}
// ForceBreak with no cast open and the client refusing the jump must not leave the breaker stage
// at Landed for nothing, which would hold every start for good.
private static void RefusedForcedJumpNoDeadlock()
{
var host = Setup();
try
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host); // the latch starts here
long t0 = _t;
FakeHost.TapJumpRefuse = true;
Check.True(ActionPacer.ForceBreak(host, "test"), "the forced break is tried");
Check.Eq(FakeHost.TapJumps, 1, "the jump was sent (and refused)");
long firstFree = -1;
while (_t < t0 + ActionPacer.LatchMaxMs + 500) { _t += 100; if (May(host) && firstFree < 0) firstFree = _t - t0; }
Check.True(firstFree > 0 && firstFree <= ActionPacer.LatchMaxMs + 100, $"a start goes by LatchMaxMs (first at {firstFree} ms)");
Check.False(ActionPacer.ServerBusy, "the latch is gone by then");
Check.Eq(ActionPacer.LatchExpiries, 1L, "it expired");
}
finally { Done(); }
}
// 0x401 retries (5 a second by design) do not trip the burst, and the burst never holds a heal.
private static void BurstCountsTooBusyAndSparesHeals()
{
var host = Setup();
try
{
for (int i = 0; i < ActionPacer.RefusalBurstMax + 1; i++) { FakeHost.UseDone(0x401); _t += 50; May(host); }
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string w1), "6 'not enough mana' answers in a second: no burst hold (" + w1 + ")");
Check.Eq(ActionPacer.BurstHolds, 0L, "none counted");
var h = Setup();
for (int i = 0; i < ActionPacer.RefusalBurstMax; i++)
{
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 50;
ActionPacer.MayStart(h, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true);
}
FakeHost.UseDone(0); // the server answers: the latch is gone, the burst is not
_t += 50;
Check.False(ActionPacer.MayStart(h, "Buff", HealNeed.None, out string why), "inside the second: a buff is held by the burst");
Check.True(why.Contains("refusals from the server in the last second"), "why: " + why);
Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Emergency, out string hw), "an emergency heal is not (" + hw + ")");
Check.True(ActionPacer.MayStart(h, "Buff", HealNeed.Heal, out _), "nor a heal");
}
finally { Done(); }
}
internal static void SetHost(RynthAiPlugin p, RynthCoreHost host)
{
for (Type? t = p.GetType(); t != null; t = t.BaseType)
{
var prop = t.GetProperty("Host", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (prop?.SetMethod != null) { prop.SetValue(p, host); return; }
var f = t.GetField("<Host>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
?? t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).FirstOrDefault(x => x.FieldType == typeof(RynthCoreHost));
if (f != null) { f.SetValue(p, host); return; }
}
throw new InvalidOperationException("no Host to set on RynthAiPlugin");
}
private static void Call(object o, string name) =>
o.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(o, null);
private static void PortalAndDeathForget()
{
var host = Setup();
try
{
ActionPacer.StuckCastMs = 0;
var p = new RynthAiPlugin();
SetHost(p, host);
Cast(host);
_t += ActionPacer.CastMaxMs + 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host);
Check.True(ActionPacer.ServerBusy, "our cast hung, latched");
Call(p, "NotePortalForPacer");
Check.True(ActionPacer.ServerBusy, "not portaling: nothing forgotten");
FakeHost.Portaling = true;
Call(p, "NotePortalForPacer");
Check.False(ActionPacer.ServerBusy, "portal-enter: the latch is forgotten");
Check.True(May(host), "and starts go");
FakeHost.Portaling = false;
Call(p, "NotePortalForPacer");
Cast(host);
_t += ActionPacer.CastMaxMs + 100;
FakeHost.UseDone(ActionPacer.TooBusyErr);
May(host);
Check.True(ActionPacer.ServerBusy, "latched again");
FakeHost.Vitals = (0, 100, 0, 100, 0, 100);
Call(p, "HoldForDeath");
Check.False(ActionPacer.ServerBusy, "the death hold forgets the latch");
Check.True(May(host), "and starts go");
}
finally { Done(); }
}
}

View file

@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Recovery retry: Stamina to Mana at about 10 mana took a long time to get off. ACE rolls Mana
// Conversion on every attempt (Creature_Magic.GetManaCost, at least 1 mana when trained) before the
// windup, and a refusal (UseDone 0x401) costs nothing. RynthAi parked the family 15 s after each
// refusal. Recovery vitals now retry every RecoveryRetryMs (200), at most 5 a second and 20 refusals
// in a row; everything else keeps the old rest.
internal static class RecoveryRetryTests
{
private const uint Player = 0x50000B21;
private const uint STypeLife = 33;
private const uint STypeManaConversion = 16;
private const uint NotEnoughMana = 0x401;
private const string RefusalLine = "You don't have enough Mana to cast this spell.";
public static void Register(Runner r)
{
r.Add("recovery retry: with spell costs unknown, Stamina to Mana goes out at 1 mana and a refusal is retried", PrecheckAllowsBelowBaseCost);
r.Add("recovery retry: with spell costs known, the mana reserve holds Stamina to Mana under its cost (no cast, no episode); Heal Self still retries", CostKnownHoldsStaminaToMana);
r.Add("recovery retry: a mana refusal is retried after 200 ms, past Spell Interval; the episode line counts the tries", RetryCadence);
r.Add("recovery retry: 20 refusals in a row end it (the vital's 2 s rest); stamina too low ends it; untrained Mana Conversion never starts it", RetryCap);
r.Add("recovery retry: at most 5 recovery casts in any second (Heal Self and Stamina to Mana alternating)", RateCeiling);
r.Add("recovery retry: an episode with no refusal for RecoveryEpisodeStaleMs (7 s) ends; it no longer lets casts past Spell Interval", StaleEpisodeEnds);
r.Add("recovery retry: RecoveryRetryMs at its 5000 ms maximum keeps its episode between retries", SlowRetryKeepsEpisode);
}
// With RecoveryRetryMs at the slider's 5000 ms maximum the retry (plus a little pacing) must not
// come after the stale limit, or the episode would end itself between retries.
private static void SlowRetryKeepsEpisode()
{
var r = new Rig(manaPct: 10);
r.S.RecoveryRetryMs = 5000;
r.S.SpellCastIntervalMs = 0;
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
r.At(5.05); r.B.OnHeartbeat(); // the retry, 50 ms late
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "the retry at 5.05 s");
Check.True(r.B.RecoveryRetryOpen, "the episode is still open");
Check.False(r.Logged("stopped retrying"), "not ended between retries: " + r.B.LastRecoverySummary);
}
// The vital stops being needed (mana regenerated) and no refusal comes again: the open episode
// must end, or it would let every cast past Spell Interval for good.
private static void StaleEpisodeEnds()
{
var r = new Rig(manaPct: 10);
r.S.SpellCastIntervalMs = 60_000; // real clock: nothing else gets past it in this test
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
Check.True(r.B.RecoveryRetryOpen, "an episode opens");
r.V.CurrentMana = 100; // no longer needed
r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 0.1); r.B.OnHeartbeat();
Check.False(r.B.RecoveryRetryOpen, "no refusal for RecoveryEpisodeStaleMs: the episode ends");
Check.True(r.B.LastRecoverySummary.Contains("no refusal for 7 s"), "summary: " + r.B.LastRecoverySummary);
r.V.CurrentHealth = 40; // a heal is needed now
int before = FakeHost.Casts.Count;
r.At(BuffManager.RecoveryEpisodeStaleMs / 1000.0 + 1); r.B.OnHeartbeat();
Check.Eq(FakeHost.Casts.Count, before, "the heal waits for Spell Interval (the ended episode lets nothing past)");
}
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 18, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public Rig(int healthPct = 100, int manaPct = 10, bool manaConversion = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
FakeHost.Skills[(Player, STypeManaConversion)] = manaConversion ? (300, 2) : (10, 1);
var host = FakeHost.Create();
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache
{
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
MaxMana = 100, CurrentMana = (uint)manaPct,
};
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
}
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 int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
public string LastCastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
/// <summary>The server's answer to an unaffordable cast: UseDone 0x401, the client's chat line.</summary>
public void Refuse()
{
FakeHost.UseDone(NotEnoughMana);
B.OnChatWindowText(RefusalLine, 0);
}
}
private static int CastsOf(string baseName)
{
int cat = SpellTable.Named(baseName + " I").First().Category;
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
}
private static void PrecheckAllowsBelowBaseCost()
{
// This rig leaves spell costs unknown (FakeHost.Reset: ManaCostOverride 0, as with no
// portal.dat), so the mana reserve's cost check in AttemptVitalCast has nothing to hold on.
var r = new Rig(manaPct: 1);
Check.True(r.B.CheckVitals(), "1 mana: the vitals step acts");
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "costs unknown: Stamina to Mana is sent at 1 mana (the server rolls the cost)");
// Refused at 1 mana: the retry is allowed (the least a trained cast can cost is 1 mana).
r.Refuse();
Check.True(r.B.RecoveryRetryOpen, "a retry episode is open at 1 mana");
Check.True(r.Logged("retrying in 200 ms"), "and the refusal line says so");
// At 0 mana no cast can be afforded: the old rest.
var z = new Rig(manaPct: 0);
z.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "0 mana: the first try still goes (as before)");
z.Refuse();
Check.False(z.B.RecoveryRetryOpen, "0 mana: no retry episode");
Check.True(z.Logged("resting the family 2s") && z.Logged("(no mana at all)"), "the vital's 2 s rest, and why");
}
private static void CostKnownHoldsStaminaToMana()
{
// Costs known (level x 10 here, as ManaReserveTests): at 5 mana even Stamina to Mana I (10)
// is unaffordable, so AttemptVitalCast's reserve check sends nothing and no episode opens.
try
{
var r = new Rig(manaPct: 5);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
r.At(0); r.B.CheckVitals();
r.At(0.2); r.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 0, "under its cost: Stamina to Mana is not cast");
Check.False(r.B.RecoveryRetryOpen, "and no retry episode opens");
// Heal Self is tried below its cost (60 here) and a refusal is still retried.
var h = new Rig(healthPct: 40, manaPct: 5);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
h.At(0); h.B.CheckVitals();
Check.Eq(CastsOf("Heal Self"), 1, "Heal Self goes out under its cost");
h.Refuse();
Check.True(h.B.RecoveryRetryOpen, "refused for mana: a retry episode");
h.At(0.2); h.B.CheckVitals();
Check.Eq(CastsOf("Heal Self"), 2, "retried after 200 ms");
Check.Eq(CastsOf("Stamina to Mana Self"), 0, "Stamina to Mana still held under its cost");
}
finally { BuffManager.ManaCostOverride = _ => 0; }
}
private static void RetryCadence()
{
var r = new Rig(manaPct: 10);
r.At(0); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "Stamina to Mana goes out");
r.Refuse();
Check.False(r.Logged("resting the family"), "no family rest");
r.At(0.1); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "100 ms after the refusal: still waiting");
r.At(0.2); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "200 ms: tried again (Spell Interval 400 on the real clock does not hold it)");
r.Refuse();
r.At(0.3); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "300 ms: waiting");
r.At(0.4); r.B.OnHeartbeat();
Check.Eq(CastsOf("Stamina to Mana Self"), 3, "400 ms: the third try");
// A good roll: the result line ends the episode with its summary.
r.At(0.55);
r.B.OnChatWindowText($"You cast {r.LastCastName} on yourself and lose 35 points of stamina and also gain 47 points of mana", 0);
Check.False(r.B.RecoveryRetryOpen, "the result closes the episode");
Check.True(r.B.LastRecoverySummary.Contains("went through after 3 attempts (2 refused for mana") && r.B.LastRecoverySummary.Contains("in 550 ms"),
$"summary: {r.B.LastRecoverySummary}");
// The retry gap is a setting.
var s = new Rig(manaPct: 10);
s.S.RecoveryRetryMs = 1000;
s.At(0); s.B.CheckVitals(); s.Refuse();
s.At(0.9); s.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 1000: nothing at 900 ms");
s.At(1.0); s.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "RecoveryRetryMs 1000: the retry at 1 s");
// ...clamped to 200 at the bottom.
var c = new Rig(manaPct: 10);
c.S.RecoveryRetryMs = 50;
c.At(0); c.B.CheckVitals(); c.Refuse();
c.At(0.1); c.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 1, "RecoveryRetryMs 50 is clamped: nothing at 100 ms");
c.At(0.2); c.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 2, "...the retry at 200 ms");
}
private static void RetryCap()
{
var r = new Rig(manaPct: 10);
for (int i = 0; i < 25; i++)
{
r.At(i * 0.2);
int before = FakeHost.Casts.Count;
r.B.CheckVitals();
if (FakeHost.Casts.Count == before) break;
r.Refuse();
}
Check.Eq(CastsOf("Stamina to Mana Self"), 20, "20 tries, then it stops");
Check.True(r.B.LastRecoverySummary.Contains("after 20 mana refusals") && r.B.LastRecoverySummary.Contains("(20 refusals in a row)"),
$"summary: {r.B.LastRecoverySummary}");
Check.Eq(r.LogCount("resting the family 2s"), 1, "the 20th refusal rests the family 2 s, as before");
r.At(4.2); r.B.CheckVitals();
Check.Eq(CastsOf("Stamina to Mana Self"), 20, "no try inside the rest");
// Stamina too low to convert when the refusal comes: the old rest.
var st = new Rig(manaPct: 10);
st.V.CurrentStamina = 20;
st.B.CheckVitals();
st.V.CurrentStamina = 10;
st.Refuse();
Check.False(st.B.RecoveryRetryOpen, "stamina 10%: no retry");
Check.True(st.B.LastRecoverySummary.Contains("stamina 10% too low to convert") && st.Logged("resting the family 2s"),
$"summary: {st.B.LastRecoverySummary}");
// Mana Conversion untrained: the cost is never rolled, so no retry (the vital's 2 s rest).
var u = new Rig(manaPct: 10, manaConversion: false);
u.B.CheckVitals();
u.Refuse();
Check.False(u.B.RecoveryRetryOpen, "untrained: no retry");
Check.True(u.Logged("resting the family 2s") && u.B.LastRecoverySummary.Contains("Mana Conversion not trained"), "the old rest, and why");
}
private static void RateCeiling()
{
// 40% health and 2% mana: Heal Self and Stamina to Mana each retry every 200 ms, which would
// be 10 casts a second. Two vitals checks per 100 ms, every cast refused.
var r = new Rig(healthPct: 40, manaPct: 2);
var sentAt = new List<double>();
for (int step = 0; step < 30; step++)
{
double t = step * 0.1;
r.At(t);
for (int k = 0; k < 2; k++)
{
int before = FakeHost.Casts.Count;
r.B.CheckVitals();
if (FakeHost.Casts.Count == before) continue;
sentAt.Add(t);
r.Refuse();
}
}
Check.True(CastsOf("Heal Self") > 0 && CastsOf("Stamina to Mana Self") > 0, "both spells were tried");
int worst = 0;
foreach (double a in sentAt)
worst = Math.Max(worst, sentAt.Count(b => b >= a && b < a + 1.0 - 1e-9));
Check.True(worst <= BuffManager.RecoveryRetryMaxPerSecond, $"at most 5 in any second (worst {worst}, sent at {string.Join(",", sentAt.Select(x => x.ToString("0.0")))})");
Check.True(worst == BuffManager.RecoveryRetryMaxPerSecond, $"and the ceiling is reached, so it is what held them (worst {worst})");
Check.True(r.B.RecoveryRateHolds > 0, "the ceiling held some");
}
}

View file

@ -0,0 +1,364 @@
using System;
using System.Linq;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// In a client log, two casts were held open by ACE's fast-tick turn-to-cast wait (40.8 s and 37 s);
// every cast after them came back UseDone 0x1D and the vitals path re-sent a heal every 2.5 s. A
// client mode change ended the second. ActionPacer now holds every start after a 0x1D until the
// server answers, turns to face a held cast's target, breaks a stuck cast with a jump (then Peace
// mode), waits until landed, and holds starts until a movement change has settled.
internal static class StuckCastTests
{
private const uint Player = 0x50000F01;
private const uint Monster = 0x80116781;
private const int DrainHealthOtherI = 1237;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
public static void Register(Runner r)
{
r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy);
r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen);
r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump at cycle + 2 s; a normal 4 s cast trips neither", TurnThenJump);
r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump);
r.Add("stuck cast: a 'too busy' answer while our cast is open past 3 s breaks it at once; before 3 s it does not", RefusalWhileOpen);
r.Add("stuck cast: StuckCastMs 0 turns nothing and breaks nothing; no TapJump -> Peace mode", BreakerOffAndNoJump);
r.Add("move settle: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go", MoveSettle);
r.Add("stuck cast: the HP failsafe's forced break jumps once and holds starts until landed", ForcedBreak);
r.Add("stuck cast: a script's cast is not jumped before ScriptCastMinBreakMs (6 s): answered at 5.5 s, no jump; RynthAi's own is jumped at 5 s", ScriptCastGetsNudgeWindow);
}
private static long _t;
private static RynthCoreHost Setup(int mode = ActionPacer.MagicMode, bool tapJump = true)
{
FakeHost.Reset();
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.WeaponCalls = true; // GetCurrentCombatMode
FakeHost.CombatModeCalls = true; // ChangeCombatMode
FakeHost.TapJumpCalls = tapJump;
FakeHost.CombatModeValue = mode;
FakeHost.Names[Player] = "Mira";
FakeHost.PlayerPose = Me0;
FakeHost.Positions[Player] = Me0;
FakeHost.HeadingDeg = 0; // facing north
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); // due east: 90 deg off
var host = FakeHost.Create(Player);
_t = 90_000_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => _t;
MoveAudit.Reset();
MoveAudit.NowMs = () => _t;
ActionPacer.StuckCastMs = 8000;
FakeHost.UseDone(0); // an earlier action's answer: the observer's baseline
return host;
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
ActionPacer.StuckCastMs = 8000;
}
private static bool May(RynthCoreHost host, HealNeed heal = HealNeed.Heal) =>
ActionPacer.MayStart(host, "Buff", heal, out _);
private static void Cast(RynthCoreHost host, string label = "Drain Health Other I") =>
Check.True(host.CastSpellFor(Monster, DrainHealthOtherI, "Buff", label), "cast sent");
private static int JumpLines() => FakeHost.Logs.Count(l => l.Contains("stuck cast broken by jump after"));
private static void Run(RynthCoreHost host, long ms) { for (long s = 0; s < ms; s += 100) { _t += 100; May(host); } }
private static void ScriptCastGetsNudgeWindow()
{
// Control: RynthAi's own cast of a spell with no learned cycle (3 s) is jumped at cycle + 2 s.
var own = Setup();
try
{
Cast(own);
Run(own, 5500);
Check.Eq(JumpLines(), 1, "RynthAi's own cast: jumped by 5.5 s (at 5 s)");
}
finally { Done(); }
// The same cast chosen by a script, answered at 5.5 s: no jump.
var host = Setup();
try
{
Cast(host);
ActionPacer.MarkScriptCast(DrainHealthOtherI);
Run(host, 5500);
Check.Eq(JumpLines(), 0, "a script's cast: no jump in the first 5.5 s");
FakeHost.UseDone(0); // its answer
Run(host, 3000);
Check.Eq(JumpLines(), 0, "answered: never jumped");
}
finally { Done(); }
// A script's cast with no answer is still broken, once ScriptCastMinBreakMs has passed.
var held = Setup();
try
{
Cast(held);
ActionPacer.MarkScriptCast(DrainHealthOtherI);
Run(held, ActionPacer.ScriptCastMinBreakMs + 200);
Check.Eq(JumpLines(), 1, "unanswered: jumped after ScriptCastMinBreakMs");
}
finally { Done(); }
}
private static void NoResendAfterTooBusy()
{
var host = Setup();
ActionPacer.StuckCastMs = 0; // the hold alone (the breaker has its own tests)
try
{
Check.True(May(host), "free at first");
Cast(host); // the cast the server will hold open: no UseDone
_t += 500;
Check.False(May(host), "our cast is unanswered");
// Past CastMaxMs (7 s) the pacer used to "go on" and the heal went out into a busy server.
_t += ActionPacer.CastMaxMs - 500;
Check.False(May(host), "unanswered past CastMaxMs: still held (the cast is hung, the server is busy with it)");
Check.True(ActionPacer.ServerBusy, "the server is taken as busy");
// A cast the player sent by hand is refused: 0x1D. Still nothing goes for 13 s (no timer re-send).
FakeHost.UseDone(ActionPacer.TooBusyErr);
bool any = false;
for (int i = 0; i < 130; i++) { _t += 100; any |= May(host); }
Check.False(any, "nothing goes for 13 s after the 0x1D while our cast is hung");
Check.True(FakeHost.Logs.Any(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), "the hold is logged");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("Buff waits:") && l.Contains("has had no answer")), 1, "once");
// The server finally answers (the cast's own UseDone): everything goes again.
FakeHost.UseDone(0x402);
Check.True(May(host), "a UseDone with another error clears the hold");
Check.False(ActionPacer.ServerBusy, "not busy any more");
Check.True(FakeHost.Logs.Any(l => l.Contains("the server answered again (UseDone 0x402)")), "logged");
}
finally { Done(); }
}
private static void ProbeWhenNothingOpen()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup)
Check.False(May(host), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs - 1;
Check.False(May(host), "held until BusyProbeMs");
_t += 1;
Check.True(May(host), "one probe at BusyProbeMs");
Check.False(May(host), "only one");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
_t += ActionPacer.BusyProbeMs * 2 - 101;
Check.False(May(host), "the next probe waits twice as long");
_t += 1;
Check.True(May(host), "second probe at 2 x BusyProbeMs");
Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open");
Cast(host, "Heart Rend");
_t += 900;
FakeHost.UseDone(0);
Check.True(May(host), "a UseDone(0) clears it");
}
finally { Done(); }
}
private static void TurnThenJump()
{
var host = Setup();
try
{
// A normal 4 s cast: answered; it sets the spell's cycle (4 s) and trips nothing.
Check.True(May(host), "free");
Cast(host);
_t += 4000;
FakeHost.UseDone(0);
May(host); // the answer seen at 4000 ms
Run(host, 10_000);
Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "a normal 4 s cast: no turn, no jump, no mode change");
Check.Eq(ActionPacer.NormalCycleMs(DrainHealthOtherI), 4000L, "the cycle learned from it");
// The next one is held open: turn at 4 + 1 s, jump at 4 + 2 s.
Cast(host);
long sent = _t;
while (_t - sent < 4900) { _t += 100; May(host); }
Check.Eq(FakeHost.Turns, 0, "no turn before cycle + 1 s");
_t += 100; May(host);
Check.Eq(FakeHost.Turns, 1, "turned at cycle + 1 s");
Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "to face the target (east)");
Check.True(FakeHost.Logs.Any(l => l.Contains("held cast:") && l.Contains("turning 90 deg to face 0x80116781")), "logged");
while (_t - sent < 5900) { _t += 100; Check.False(May(host), "held"); }
Check.Eq(FakeHost.TapJumps, 0, "no jump before cycle + 2 s");
_t += 100; May(host);
Check.Eq(FakeHost.TapJumps, 1, "the breaker jump at cycle + 2 s");
Check.True(FakeHost.Logs.Any(l => l.Contains("[Pace] stuck cast broken by jump after 6000 ms")), "logged with the time");
Run(host, 2000);
Check.Eq(FakeHost.TapJumps, 1, "one jump");
Check.Eq(FakeHost.Turns, 1, "one turn");
// The fizzle (0x402): free again once landed.
FakeHost.UseDone(0x402);
Check.True(May(host), "free after the cast's UseDone");
}
finally { Done(); }
}
private static void AfterTheJump()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host);
long sent = _t;
while (FakeHost.TapJumps == 0 && _t - sent < 10_000) { _t += 100; May(host); }
Check.Eq(_t - sent, ActionPacer.DefaultCycleMs + ActionPacer.JumpAfterMs, "unknown spell cycle: the jump at 3 + 2 s");
long jumped = _t;
// In the air: even with the cast's UseDone in, nothing starts.
FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.6f);
FakeHost.UseDone(0x402);
_t += 200;
Check.False(May(host), "in the air: held even with the UseDone in");
Check.True(ActionPacer.BreakerAirborne, "airborne");
_t += 300;
Check.False(May(host), "still above the take-off height at 500 ms");
FakeHost.PlayerPose = Me0;
Check.True(May(host), "landed: free (the cast was answered)");
// A second hung cast: jump, land, no answer: Peace mode 3 s after landing, then going on 3 s later.
Cast(host);
sent = _t;
while (FakeHost.TapJumps < 2 && _t - sent < 10_000) { _t += 100; May(host); }
Check.Eq(FakeHost.TapJumps, 2, "jumped");
_t += ActionPacer.JumpLandMinMs; May(host); // landed (height unchanged)
long landed = _t;
while (_t - landed < ActionPacer.BreakerWaitMaxMs - 100) { _t += 100; Check.False(May(host), "held after landing, no answer"); }
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Peace yet");
_t += 100; May(host);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "Peace requested once, 3 s after landing");
Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by Peace mode after")), "logged");
FakeHost.CombatModeValue = ActionPacer.PeaceMode;
Run(host, ActionPacer.BreakerWaitMaxMs);
Check.True(FakeHost.Logs.Any(l => l.Contains("no UseDone after the stuck-cast break")), "going on, logged");
_t += ActionPacer.ModeSettleMs;
Check.True(May(host), "free after it");
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "one Peace request");
}
finally { Done(); }
}
private static void RefusalWhileOpen()
{
var host = Setup();
try
{
Check.True(May(host), "free");
Cast(host);
_t += 2000;
Cast(host, "Rushed Recovery"); // a heal let ahead of it: refused, 2 s in (a recoil refusal is normal)
FakeHost.UseDone(ActionPacer.TooBusyErr);
_t += 100; May(host);
Check.Eq(FakeHost.TapJumps, 0, "a 0x1D at 2 s: no jump");
_t += 900; May(host);
Check.Eq(FakeHost.TapJumps, 1, "past RefusalBreakMinMs with a 0x1D in: jump at once (before cycle + 2 s)");
Check.True(FakeHost.Logs.Any(l => l.Contains("was refused 'too busy' while it was open")), "the reason is logged");
}
finally { Done(); }
}
private static void BreakerOffAndNoJump()
{
var host = Setup();
try
{
ActionPacer.StuckCastMs = 0;
Check.True(May(host), "free");
Cast(host);
Run(host, 30_000);
Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "StuckCastMs 0: nothing");
}
finally { Done(); }
host = Setup(tapJump: false);
try
{
Check.True(May(host), "free");
Cast(host);
Run(host, 6000);
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), ActionPacer.PeaceMode.ToString(), "no TapJump: Peace mode at the jump time");
Check.True(FakeHost.Logs.Any(l => l.Contains("no TapJump on this engine")), "logged");
}
finally { Done(); }
}
private static void MoveSettle()
{
var host = Setup();
try
{
FakeHost.AutoRun = true;
Check.True(May(host), "free");
host.SetAutoRunBy("Nav", true);
_t += 1000;
host.SetAutoRunBy("Nav", false); // nav's stop goes out this tick
Check.False(May(host), "no cast in the tick of the stop");
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _, animationGate: false, settleGate: false, attackRepeat: true), "an attack repeat is not held");
_t += MoveAudit.MoveSettleMinMs - 1;
Check.False(May(host), "held under MoveSettleMinMs");
_t += 1;
FakeHost.CastBusy = 1; // the client still animates the stop
Check.False(May(host), "the motion queue still busy: held");
FakeHost.CastBusy = 0;
Check.True(May(host), "settled: free");
Check.True(FakeHost.Logs.Any(l => l.Contains("SetAutoRun(False) sent") && l.Contains("has not settled")), "logged");
host.TurnToHeadingBy("Nav", 45f);
FakeHost.CastBusy = 1;
_t += MoveAudit.MoveSettleMaxMs - 1;
Check.False(May(host), "busy queue: held under MoveSettleMaxMs");
_t += 1;
// The gesture gate itself would still hold a busy queue; the settle gate lets go at its max.
Check.True(!MoveAudit.SettleHolds(host, out _), "the settle gate lets go at MoveSettleMaxMs");
FakeHost.CastBusy = 0;
}
finally { Done(); }
}
private static void ForcedBreak()
{
var host = Setup();
try
{
Check.True(ActionPacer.ForceBreak(host, "HP failsafe"), "the forced break goes");
Check.Eq(FakeHost.TapJumps, 1, "one jump");
Check.False(ActionPacer.ForceBreak(host, "HP failsafe"), "not twice while in the air");
FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, Me0.Z + 0.5f);
_t += 300;
Check.False(May(host), "in the air: held");
FakeHost.PlayerPose = Me0;
_t += 200;
Check.True(May(host), "landed: free (nothing of ours was open)");
Check.True(FakeHost.Logs.Any(l => l.Contains("stuck cast broken by jump after 0 ms") && l.Contains("HP failsafe")), "logged");
}
finally { Done(); }
}
}

View file

@ -33,8 +33,24 @@ internal static unsafe class FakeCombat
private static long Now => Environment.TickCount64;
/// <summary>Per kind, as RynthAi's CombatHook: the taken cast in flight, and the most recent resolved one (Err -1 = no answer read).</summary>
private sealed class Cast { public uint Seq, Spell, Target; public long At; public int Err = -1; }
private static readonly Dictionary<uint, Cast> InFlight = new(), Resolved = new();
/// <summary>OlderRynthAi: a RynthAi from before the resolved/pending fields (writes none of them).</summary>
public static bool OlderRynthAi;
/// <summary>The server answers the cast in flight of <paramref name="kind"/> (err -1: no answer read).</summary>
public static void ResolveInFlight(uint kind, int err)
{
if (!InFlight.Remove(kind, out var c)) return;
c.Err = err;
Resolved[kind] = c;
}
public static void Reset()
{
InFlight.Clear(); Resolved.Clear();
OlderRynthAi = false;
Enabled = false;
Owner = "";
Kinds = 0;
@ -83,7 +99,7 @@ internal static unsafe class FakeCombat
StructSize = (uint)sizeof(CombatRequestV1), Seq = seq, Kind = kind, TargetId = targetId,
TargetHealth = kind == RynthAiCombat.KindAttack ? 0.5f : -1f, HealthPct = 80, StaminaPct = 70, ManaPct = 60,
HealLine = kind == RynthAiCombat.KindHeal ? 60 : 0, InCombat = 1, CombatMode = 8,
IssuedAtMs = Now, DeadlineMs = Now + timeoutMs,
IssuedAtMs = Now, DeadlineMs = Now + timeoutMs, ResolvedErr = -1,
};
if (Slots.TryGetValue(kind, out var old) && old.Decided)
{
@ -92,7 +108,14 @@ internal static unsafe class FakeCombat
r.LastSpell = d?.Spell ?? 0;
r.LastTarget = d?.Target ?? 0;
r.LastAtMs = Now;
if (r.LastSpell != 0)
{
ResolveInFlight(kind, -1); // the cast before it, still unanswered: no answer read
InFlight[kind] = new Cast { Seq = old.R.Seq, Spell = r.LastSpell, Target = r.LastTarget, At = Now };
}
}
if (Resolved.TryGetValue(kind, out var rc)) { r.ResolvedSeq = rc.Seq; r.ResolvedSpell = rc.Spell; r.ResolvedTarget = rc.Target; r.ResolvedAtMs = rc.At; r.ResolvedErr = rc.Err; }
if (InFlight.TryGetValue(kind, out var pc)) { r.PendingSeq = pc.Seq; r.PendingSpell = pc.Spell; r.PendingTarget = pc.Target; r.PendingAtMs = pc.At; }
Slots[kind] = new Req { R = r, Open = true };
return seq;
}
@ -126,6 +149,7 @@ internal static unsafe class FakeCombat
{
if (req == null || !Active(kind) || !Slots.TryGetValue(kind, out var s) || !s.Open || s.Decided || Now > s.R.DeadlineMs) return 0;
uint room = req->StructSize == 0 || req->StructSize > (uint)sizeof(CombatRequestV1) ? (uint)sizeof(CombatRequestV1) : req->StructSize;
if (OlderRynthAi) room = Math.Min(room, (uint)Marshal.OffsetOf<CombatRequestV1>(nameof(CombatRequestV1.ResolvedSeq))); // writes none of the appended fields
CombatRequestV1 r = s.R;
r.StructSize = room;
Buffer.MemoryCopy(&r, req, room, room);

View file

@ -229,6 +229,8 @@ internal static class Harness
// would, and read back what RynthLua claimed, decided and released.
Fn("combatTable", a => { FakeCombat.Enabled = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; });
Fn("combatOpen", a => DynValue.NewNumber(FakeCombat.Open((uint)Num(a, 0, 1), Id(a, 1), (long)Num(a, 2, 2000))));
Fn("combatResolve", a => { FakeCombat.ResolveInFlight(RynthCore.Plugin.Shared.RynthAiCombat.KindAttack, (int)Num(a, 0, -1)); return DynValue.Nil; });
Fn("combatOlderRynthAi", a => { FakeCombat.OlderRynthAi = a.Count > 0 && a[0].CastToBool(); return DynValue.Nil; });
Fn("combatScanned", a =>
{
FakeCombat.Scanned.Clear();

View file

@ -55,14 +55,48 @@ check(seen.deadline > seen.issuedAt, "ctx.deadline after ctx.issuedAt")
check(seen.deadline > clock(), "ctx.deadline is on clock()'s scale and still ahead")
eq(#seen.monsters, 2, "ctx.monsters")
eq(seen.monsters[1].distance, 3.5, "ctx.monsters[1].distance")
eq(seen.last.seq, 0, "no last decision yet")
eq(seen.last.seq, 0, "no resolved cast yet")
eq(seen.pending, nil, "nothing in flight yet")
-- The next request carries the last decision.
-- ctx.pending: the cast in flight; ctx.last: the most recent RESOLVED cast, err final.
local seq2 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(2), "second request answered")
eq(seen.last.seq, seq1, "ctx.last.seq")
eq(seen.pending.seq, seq1, "ctx.pending.seq: the first cast, no answer yet")
eq(seen.pending.spell, 1234, "ctx.pending.spell")
eq(seen.pending.target, 0x80000102, "ctx.pending.target")
eq(seen.last.seq, 0, "ctx.last: still no resolved cast")
eq(seen.last.err, nil, "ctx.last.err: nil before the first resolved cast")
harness.combatResolve(0x1D) -- the first cast's UseDone: 0x1D
local seqE = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(3), "third request answered")
eq(seen.last.seq, seq1, "ctx.last: the first cast, now resolved")
eq(seen.last.spell, 1234, "ctx.last.spell")
eq(seen.last.target, 0x80000102, "ctx.last.target")
eq(seen.last.err, 29, "ctx.last.err = 0x1D (refused 'too busy')")
eq(seen.pending.seq, seq2, "ctx.pending: the second cast")
-- No answer for the second before the third went out: resolved with no answer (nil).
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4), "fourth request answered")
eq(seen.last.seq, seq2, "ctx.last: the second cast")
eq(seen.last.err, nil, "no answer read for it: nil")
eq(seen.pending.seq, seqE, "ctx.pending: the third cast")
harness.combatResolve(0)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(5), "fifth request answered")
eq(seen.last.seq, seqE, "ctx.last: the third cast")
eq(seen.last.err, 0, "ctx.last.err = 0 (done)")
harness.combatResolve(0x1D)
harness.combatOlderRynthAi(true)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(6), "older RynthAi request answered")
eq(seen.last.err, nil, "an older RynthAi: no err")
eq(seen.pending, nil, "an older RynthAi: no pending")
check(seen.last.seq > seqE, "an older RynthAi: ctx.last is its last decision")
harness.combatOlderRynthAi(false)
-- 2. A yielding handler (the same script registering again replaces its handler), area flag.
ok = ai.SetAttackHandler(function(ctx)
@ -71,8 +105,8 @@ ok = ai.SetAttackHandler(function(ctx)
end)
eq(ok, true, "the same script replaces its handler")
local seq3 = harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(3), "the yielding handler still answers")
d = decisions()[3]
check(waitDecisions(7), "the yielding handler still answers")
d = decisions()[7]
eq(d.seq, seq3, "for its seq")
eq(d.spell, 55, "its spell")
eq(d.target, 0, "nil target = the request's target")
@ -82,16 +116,16 @@ eq(d.taken, true, "taken")
-- 3. nil declines.
ai.SetAttackHandler(function(ctx) return nil end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4), "a nil answer is still an answer")
eq(decisions()[4].spell, 0, "nil = decline (spell 0)")
check(waitDecisions(8), "a nil answer is still an answer")
eq(decisions()[8].spell, 0, "nil = decline (spell 0)")
-- 4. An error declines at once; three in a row unregister.
ai.SetAttackHandler(function(ctx) error("boom (expected)") end)
for i = 1, 3 do
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(4 + i), "error " .. i .. ": declined at once")
eq(decisions()[4 + i].spell, 0, "error " .. i .. ": spell 0")
eq(decisions()[4 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)")
check(waitDecisions(8 + i), "error " .. i .. ": declined at once")
eq(decisions()[8 + i].spell, 0, "error " .. i .. ": spell 0")
eq(decisions()[8 + i].taken, true, "error " .. i .. ": taken (no wait for the deadline)")
end
eq(ai.CombatHook.AttackOwner, nil, "three errors: the handler is removed")
check(waitfor(function() return harness.combatState().kinds == 0 end, 2000), "and the kind released in RynthAi")
@ -105,8 +139,8 @@ check(harness.scriptConsole("combathook"):find("combat attack handler:", 1, true
-- A bad answer counts as an error too (and declines).
ai.SetAttackHandler(function(ctx) return "fireball" end)
harness.combatOpen(ATTACK, 0x80000101)
check(waitDecisions(8), "a bad answer declines")
eq(decisions()[8].spell, 0, "spell 0")
check(waitDecisions(12), "a bad answer declines")
eq(decisions()[12].spell, 0, "spell 0")
check(harness.scriptConsole("combathook"):find("expected a spell id", 1, true) ~= nil, "and says what was wrong")
ai.ClearCombatHandlers()
eq(ai.CombatHook.AttackOwner, nil, "ClearCombatHandlers drops it")
@ -130,10 +164,10 @@ eq(harness.combatState().owner, "RynthLua/combathook+rival", "under both scripts
check(harness.scriptLoaded("rival"), "the rival's main chunk ended but its handler keeps it running")
local healSeq = harness.combatOpen(HEAL, 0)
check(waitDecisions(9), "heal answered")
eq(decisions()[9].seq, healSeq, "heal seq")
eq(decisions()[9].kind, HEAL, "heal kind")
eq(decisions()[9].spell, 2001, "heal spell")
check(waitDecisions(13), "heal answered")
eq(decisions()[13].seq, healSeq, "heal seq")
eq(decisions()[13].kind, HEAL, "heal kind")
eq(decisions()[13].spell, 2001, "heal spell")
local releasesBefore = harness.combatState().releases
check(harness.stopScript("rival"), "stop the rival")