Chain buff casts on the server's UseDone instead of the recoil animation

In a buff pass every buff waited on the animation gate (ActionPacer.GestureHolds and
CastGateWatchdog, both the client's motion queue) after the server's UseDone for the
previous buff, about 550 ms per buff. ACE clears IsBusy just before that UseDone and
takes the next cast at once.

BuffCastChain lets the next buff skip only the animation gate when the last action
RynthAi sent was its own buff cast, the very next UseDone after it is UseDone(0) and
the last one, it was seen under 1.5 s ago, the character is in Magic stance and no
vital is under any line (the mana reserve included). A buff that would need Stamina
to Mana first (the reserve) drops the fast path, so Stamina to Mana goes out on a
gated tick. The pacer's outstanding-action gate, the pending cast, the
server-resolution wait, the busy count, the cast interval, the mana floor and the
too-busy backoff all stay. Buff items and rations wait for a gated tick.

Refusals during buffing are counted as running totals since load (client: CastSpell false;
server: an error in the buff's UseDone; too-busy lines), logged one line each, and
summed up at the end of each pass. Any refusal of a fast-path cast turns the fast
path off for the rest of that pass.

Setting FastBuffChain (Advanced settings, metas), default on.

Tests also cover the reserve: mana left under it, and mana over it but under it once
the next buff is paid, both wait for the recoil before Stamina to Mana goes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 15:08:52 -07:00
commit 1643835c7c
10 changed files with 629 additions and 14 deletions

View file

@ -0,0 +1,191 @@
// ============================================================================
// RynthSuite - Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs
// Buff cast chaining: the next buff of a pass goes out on the last buff's UseDone,
// without waiting for the client to finish playing the cast's recoil.
//
// Why: in a buff pass every buff waited on the animation gate (ActionPacer.GestureHolds
// and CastGateWatchdog.CanCastNow, both the client's CMotionInterp queue) after the
// server's UseDone for the previous buff: "[Pace] Buff waits: the character is still
// animating" after each UseDone, and the next buff ~550 ms later (UseDone to next buff:
// median 553 ms over 74 buffs, bimodal at ~50 and ~550 ms). On ACE the server clears
// IsBusy just before it sends that UseDone (Player_Magic.cs: IsBusy = false;
// SendUseDoneEvent()), and VerifyBusy only checks IsBusy, so it takes the next cast at
// once; the client is still showing the recoil the server already finished.
//
// The fast path (LegacyUiSettings.FastBuffChain, default on) opens ONLY the animation
// gate, and only when all of these hold:
// * the last action RynthAi sent was one of BuffManager's own buff casts
// (ActionPacer.Started and AttacksSent unchanged since it went out);
// * the very next UseDone after it is the last one (no other UseDone since) and its
// error is 0;
// * that UseDone was seen less than WindowMs ago;
// * no refusal has turned the fast path off for this buff pass.
// Every other gate stays: the pacer's outstanding-action gate, the pending cast, the
// server-resolution wait, the busy count, the cast interval, the stance (EnsureMagicMode),
// the mana floor, the too-busy backoff. BuffManager also takes the fast path only while
// no vital is under any of its lines (the mana reserve included), and drops it for a buff
// that would need Stamina to Mana first, so no kit, potion or vital cast rides it.
//
// Refusals (the crash this protects against: a tight retry loop on "You're too busy!"
// re-enters AC's AddTextToScroll -> AV 0x00460D1D, see BuffManager.OnChatWindowText and
// CastGateWatchdog): the throttle, the park and the escalating backoff are untouched, and
// any refusal of a buff cast that went out on the fast path (the client's CastSpell
// returning false, a "too busy" line for it, or an error in its UseDone) turns the fast
// path off for the rest of the pass, logged. Every refusal during buffing is counted for
// as a running total since load, logged one line each, and each pass ends with a summary line.
// ============================================================================
using System;
namespace RynthCore.Plugin.RynthAi;
internal sealed class BuffCastChain
{
/// <summary>The fast path is only taken this long after the last buff's UseDone was seen.</summary>
public const double WindowMs = 1500;
// The last buff cast BuffManager sent.
private int _spellId;
private string _name = "";
private int _seqAtSend;
private long _startedAfter;
private long _attacksAfter;
private bool _wasFast;
private bool _heldForAnimation; // the next buff goes through the animation gate (HoldForAnimation)
private bool _answerSeen; // the first UseDone after it was read
private bool _answerOk; // ... and it was UseDone(0), the next UseDone after the send
private DateTime _answerSeenAt = DateTime.MinValue;
// This pass.
private bool _inPass;
private bool _offThisPass;
private int _passCasts, _passFast, _passClient, _passServer, _passTooBusy;
// Running totals since load.
public int ClientRefusals { get; private set; }
public int ServerRefusals { get; private set; }
public int TooBusyLines { get; private set; }
public int FastCasts { get; private set; }
public int BuffCasts { get; private set; }
public int PassesSwitchedOff { get; private set; }
/// <summary>True when a refusal turned the fast path off for the rest of this pass.</summary>
public bool OffThisPass => _offThisPass;
public bool InPass => _inPass;
public void PassStart()
{
if (_inPass) return;
_inPass = true;
_offThisPass = false;
_passCasts = _passFast = _passClient = _passServer = _passTooBusy = 0;
}
/// <summary>The pass is over (complete or cancelled): one summary line.</summary>
public void PassEnd(string how, Action<string> log)
{
if (!_inPass) return;
_inPass = false;
log($"[BuffChain] buff pass {how}: {_passCasts} buff cast(s), {_passFast} on the fast path" +
$"{(_offThisPass ? " (fast path switched off by a refusal)" : "")}; refusals this pass: client {_passClient}, " +
$"server {_passServer}, too-busy lines {_passTooBusy}; totals: client {ClientRefusals}, server {ServerRefusals}, " +
$"too-busy lines {TooBusyLines}, {FastCasts} of {BuffCasts} buff casts on the fast path");
_offThisPass = false;
}
/// <summary>A buff cast went out. <paramref name="seqAtSend"/> is the UseDone count read before the send;
/// <paramref name="started"/> / <paramref name="attacks"/> are ActionPacer's counts read after it.</summary>
public void Sent(int spellId, string name, int seqAtSend, long started, long attacks, bool fast)
{
_spellId = spellId;
_name = name;
_seqAtSend = seqAtSend;
_startedAfter = started;
_attacksAfter = attacks;
_wasFast = fast;
_heldForAnimation = false;
_answerSeen = false;
_answerOk = false;
_answerSeenAt = DateTime.MinValue;
BuffCasts++;
_passCasts++;
if (fast) { FastCasts++; _passFast++; }
}
/// <summary>The client refused a buff cast (CastSpell returned false: nothing went out).</summary>
public void ClientRefused(int spellId, string name, bool fast, Action<string> log)
{
ClientRefusals++;
_passClient++;
log($"[BuffChain] refusal (client): CastSpell refused '{name}' (id {spellId}){(fast ? " on the fast path" : "")}" +
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (fast) SwitchOff("the client refused a fast-path cast", log);
_spellId = 0; // nothing went out: nothing to chain on
}
/// <summary>
/// Each tick: reads the first UseDone after the last buff cast. An error in it is a server refusal
/// (counted, logged; on the fast path the fast path is off for the pass).
/// </summary>
public void Observe(bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, Action<string> log)
{
if (_spellId == 0 || _answerSeen || !hasLast) return;
if (lastSeq <= _seqAtSend) return; // not answered yet
_answerSeen = true;
_answerSeenAt = now;
bool next = lastSeq == _seqAtSend + 1 && seqNow == lastSeq;
_answerOk = next && lastErr == 0;
if (next && lastErr != 0)
{
ServerRefusals++;
_passServer++;
log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for '{_name}'{(_wasFast ? " on the fast path" : "")}" +
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (_wasFast) SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
}
}
/// <summary>A "You're too busy!" line while <paramref name="pendingSpellId"/> (a buff of ours) waited for its result.</summary>
public void TooBusyLine(int pendingSpellId, Action<string> log)
{
if (!_inPass || pendingSpellId == 0) return;
TooBusyLines++;
_passTooBusy++;
bool ours = pendingSpellId == _spellId;
log($"[BuffChain] refusal (too-busy line) while '{(ours ? _name : $"spell {pendingSpellId}")}' was pending" +
$"{(ours && _wasFast ? " (sent on the fast path)" : "")} - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (ours && _wasFast) SwitchOff("a fast-path cast drew 'You're too busy!'", log);
}
/// <summary>The next buff needs another cast first (Stamina to Mana for the mana reserve): no fast
/// path until the next buff cast goes out.</summary>
public void HoldForAnimation() => _heldForAnimation = true;
private void SwitchOff(string why, Action<string> log)
{
if (_offThisPass) return;
_offThisPass = true;
PassesSwitchedOff++;
log($"[BuffChain] {why}: the next buffs of this pass wait for the animation again");
}
/// <summary>
/// May the next buff skip the animation gate? <paramref name="why"/> says why it may (for the log).
/// The caller has checked the setting, the pacing and the vitals.
/// </summary>
public bool Eligible(long started, long attacks, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
{
why = "";
if (_offThisPass || _heldForAnimation || _spellId == 0 || !_answerSeen || !_answerOk) return false;
if (started != _startedAfter || attacks != _attacksAfter) return false; // something else went out since
if (!hasLast || lastSeq != _seqAtSend + 1 || seqNow != lastSeq || lastErr != 0) return false; // another UseDone since
double age = (now - _answerSeenAt).TotalMilliseconds;
if (age > WindowMs) return false;
why = $"'{_name}' answered UseDone(0) {age:0} ms ago";
return true;
}
public string Describe() =>
$"Buff chain: {FastCasts} of {BuffCasts} buff casts on the fast path; refusals client {ClientRefusals}, " +
$"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}";
}

View file

@ -262,6 +262,14 @@ public class BuffManager : IDisposable
internal Func<DateTime> Clock { get => _cast.Clock; set => _cast.Clock = value; }
private DateTime Now => _cast.Now;
// Buff cast chaining (Combat/BuffCastChain.cs): the next buff of a pass goes out
// on the last buff's UseDone(0) without waiting for the recoil animation; refusals counted.
private readonly BuffCastChain _chain = new();
internal BuffCastChain Chain => _chain;
/// <summary>This tick skipped the animation gate (the fast path): only a buff cast may go out.</summary>
private bool _fastChainTick;
private string _fastChainWhy = "";
// Held-cast nudge (2026-10-05): a cast the server holds open (incantation, no result) is
// only let go by a movement packet; StopCompletely from a standing character may send none.
// Once per held cast: autorun on and straight off again, then no cast for this long.
@ -477,13 +485,8 @@ public class BuffManager : IDisposable
/// </summary>
internal bool BuffWaitsForMana(int spellId, string buffName)
{
if (_vitals.MaxMana == 0) return false;
int reserve = ManaReserve();
int cost = SpellManaCost(spellId);
if (!BuffNeedsManaFirst(spellId, out bool cantPay, out int cost)) return false;
uint cur = _vitals.CurrentMana;
bool cantPay = cost > 0 && cur < cost;
bool underReserveAfter = reserve > 0 && (long)cur - Math.Max(cost, 0) < reserve;
if (!cantPay && !underReserveAfter) return false;
_vitalWhy = "";
if ((StaminaAllowsStaminaToMana() && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion"))
@ -502,6 +505,21 @@ public class BuffManager : IDisposable
return true;
}
/// <summary>The reserve test BuffWaitsForMana acts on, with no side effect: true when mana can't
/// pay for the buff (<paramref name="cantPay"/>) or would be under the reserve after it.</summary>
private bool BuffNeedsManaFirst(int spellId, out bool cantPay, out int cost)
{
cantPay = false;
cost = 0;
if (_vitals.MaxMana == 0) return false;
int reserve = ManaReserve();
cost = SpellManaCost(spellId);
uint cur = _vitals.CurrentMana;
cantPay = cost > 0 && cur < cost;
bool underReserveAfter = reserve > 0 && (long)cur - Math.Max(cost, 0) < reserve;
return cantPay || underReserveAfter;
}
private readonly Dictionary<int, DateTime> _castIssuedAtByFamily = new();
private readonly Dictionary<int, DateTime> _expiryAtCastByFamily = new();
private const double AuditSettleMs = 15_000.0;
@ -855,6 +873,7 @@ public class BuffManager : IDisposable
_pendingSpellId = 0;
_lastCastAttempt = DateTime.MinValue;
SaveBuffTimers();
_chain.PassStart();
_host.WriteToChat("[RynthAi] Starting Force Rebuff...", 5);
var list = BuildDynamicBuffList();
@ -870,6 +889,7 @@ public class BuffManager : IDisposable
_isRechargingStamina = false;
_isHealingSelf = false;
_pendingSpellId = 0;
_chain.PassEnd("cancelled", s => _host.Log(s));
_host.WriteToChat("[RynthAi] Sequence cancelled.", 5);
}
@ -1115,6 +1135,8 @@ public class BuffManager : IDisposable
// Close casts the server reports finished, and say once when one is being held open.
PollCastTracker();
ObserveBuffChain();
_fastChainTick = false;
// A Magic stance we asked for: watch the client's mode every tick (see ObserveStance).
ObserveStance();
@ -1379,7 +1401,11 @@ public class BuffManager : IDisposable
// a buff's enchantment lands before that). Heals keep their priority (ActionPacer's heal
// rules). And not while RynthAi still has the character running: the arbiter's stop goes
// out this tick, the cast the next one (a stop mid-windup disturbs the cast).
if (!PacerAllows(out string paceWhy))
// Buff cast chaining (BuffCastChain): right after the server's UseDone(0) for our own last
// buff, the next buff skips the animation gate only (the pacer's gesture hold and the
// engine's cast gate below). Every other gate stays.
_fastChainTick = FastChainNow();
if (!PacerAllows(out string paceWhy, gestureGate: !_fastChainTick))
{
LastBuffSkipReason = "server answering the last action: " + paceWhy;
Hold("server answering the last action", paceWhy);
@ -1402,7 +1428,7 @@ public class BuffManager : IDisposable
// NeedsAnyBuff and is the sole writer of the "Buffing" string.
// A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal);
// everything else still waits for the count to drop.
bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
bool gateOpen = _fastChainTick || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
bool busyHolds = BusyCount > 0
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
@ -1502,8 +1528,11 @@ public class BuffManager : IDisposable
// only on the local gesture, so their UseObject landed while a buff was still
// resolving server-side; the "You're too busy!" that drew cleared that buff's
// pending state. When one of them acts, no buff cast follows in the same tick.
// Not on a fast-path tick (the animation gate was skipped for a buff cast only): they
// get their turn on the next tick that waited for the animation.
DateTime beforeItems = _lastCastAttempt;
try { TryUseBuffItems(); TryMakeRations(); } catch { }
if (!_fastChainTick)
try { TryUseBuffItems(); TryMakeRations(); } catch { }
if (_lastCastAttempt != beforeItems) return;
if (_settings.EnableBuffing)
@ -1523,6 +1552,7 @@ public class BuffManager : IDisposable
// populated — it is what the audit iterates.
AuditBatchSatisfied();
_forceRebuffCastFamilies.Clear();
_chain.PassEnd("complete", s => _host.Log(s));
_host.WriteToChat(wasAutoBatch ? "[RynthAi] Rebuff complete." : "[RynthAi] Force Rebuff Complete.", 1);
}
}
@ -2442,6 +2472,7 @@ public class BuffManager : IDisposable
_isForceRebuffing = true;
_isAutoBatchRebuff = true;
_forceRebuffCastFamilies.Clear();
_chain.PassStart();
}
List<string> desiredBuffs = BuildDynamicBuffList();
@ -2509,6 +2540,16 @@ public class BuffManager : IDisposable
// spent mana spell by spell down to 6%, under Stamina to Mana's cost, and he stood there
// until regen reached it). A buff that would leave mana under the reserve waits for
// Stamina to Mana first; when even that can't be paid for, buffing waits for regen.
// On the fast path (no animation gate) nothing but the buff may go out: when the reserve
// would send Stamina to Mana instead, the fast path is dropped for this buff and the next
// tick goes through the animation gate, where BuffWaitsForMana sends it.
if (_fastChainTick && BuffNeedsManaFirst(spellId, out _, out _))
{
_fastChainTick = false;
_chain.HoldForAnimation();
LastBuffSkipReason = "mana reserve before " + buffBaseName + ": Stamina to Mana waits for the animation";
return true;
}
if (BuffWaitsForMana(spellId, buffBaseName))
return true;
@ -2530,9 +2571,21 @@ public class BuffManager : IDisposable
// buffed when it wasn't and never retried the known tier.
if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)");
bool fast = _fastChainTick;
if (fast)
_host.Log($"[BuffChain] '{spellInfo?.Name ?? buffBaseName}' goes without waiting for the animation: {_fastChainWhy}");
int seqAtSend = UseDoneSeqNow();
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName);
_lastCastAttempt = DateTime.Now;
if (castOk) NoteCastIssued(spellId);
if (castOk)
{
NoteCastIssued(spellId);
_chain.Sent(spellId, spellInfo?.Name ?? buffBaseName, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, fast);
}
else
{
_chain.ClientRefused(spellId, spellInfo?.Name ?? buffBaseName, fast, s => _host.Log(s));
}
if (castOk && buffFamily != 0 && spellInfo != null)
{
// Highest tier cast per family this session: IsBuffActive's landed-tier cap only
@ -3592,6 +3645,8 @@ public class BuffManager : IDisposable
SaveBuffTimers();
}
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
if (_pendingSpellId != _pendingVitalSpellId)
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
}
if (!pendingRunning) _pendingSpellId = 0;
@ -3829,7 +3884,49 @@ public class BuffManager : IDisposable
/// </summary>
private bool _pacerLetHealAhead;
private bool PacerAllows(out string why)
/// <summary>Each tick: the first UseDone after our last buff cast (a server refusal is counted there).</summary>
private void ObserveBuffChain()
{
if (!_host.HasUseDoneSeq) return;
bool hasLast = _host.TryGetLastUseDone(out int lastSeq, out uint lastErr);
_chain.Observe(hasLast, lastSeq, lastErr, _host.GetUseDoneSeq(), Now, s => _host.Log(s));
}
/// <summary>
/// The buff cast chain's fast path for this tick (see BuffCastChain): the setting is on, the
/// pacing is on, the character is in Magic stance, no vital is under any of its lines (so the
/// vitals step has nothing to send on a tick that skips the animation gate), and the last
/// action was our own buff cast answered by UseDone(0) moments ago.
/// </summary>
private bool FastChainNow()
{
_fastChainWhy = "";
if (!_settings.FastBuffChain || !_settings.EnableBuffing || !ActionPacer.Enabled) return false;
if (!_host.HasUseDoneSeq || CurrentCombatMode != CombatMode.Magic) return false;
if (!VitalsClearOfEveryLine()) return false;
bool hasLast = _host.TryGetLastUseDone(out int lastSeq, out uint lastErr);
return _chain.Eligible(ActionPacer.Started, ActionPacer.AttacksSent, hasLast, lastSeq, lastErr,
_host.GetUseDoneSeq(), Now, out _fastChainWhy);
}
/// <summary>True when health, stamina and mana are at or over every line the vitals step acts on
/// (combat and idle, emergency included), and no kit or stamina run is in progress.</summary>
private bool VitalsClearOfEveryLine()
{
if (_vitals.MaxHealth == 0) return false;
if (KitPending() || _restamRun) return false;
int hp = _vitals.HealthPct, st = _vitals.StaminaPct, mp = _vitals.ManaPct;
if (HealthUnderAnyLine(hp, st)) return false;
if (hp < Math.Max(_settings.HealAt, _settings.TopOffHP)) return false;
if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) return false;
if (_settings.StaminaToHealthAt > 0 && hp <= _settings.StaminaToHealthAt) return false;
if (mp < Math.Max(_settings.GetManaAt, _settings.TopOffMana)) return false;
if (ManaUnderLine(true, out _) || ManaUnderLine(false, out _)) return false; // the mana reserve too
if (st < Math.Max(_settings.RestamAt, _settings.TopOffStam)) return false;
return true;
}
private bool PacerAllows(out string why, bool gestureGate = true)
{
why = "";
_pacerLetHealAhead = false;
@ -3842,7 +3939,7 @@ public class BuffManager : IDisposable
}
HealNeed need = HealNeedNow();
bool outstanding = ActionPacer.Current(_host) != null;
if (ActionPacer.MayStart(_host, "Buff", need, out why))
if (ActionPacer.MayStart(_host, "Buff", need, out why, gestureGate))
{
// A heal let ahead of an unanswered action: the busy count still counts that action,
// so the busy gate below must not hold the heal again.

View file

@ -756,6 +756,14 @@ internal sealed class LegacyAdvancedSettingsUi
"For servers with buff augments, where your own cast is stronger or\n" +
"lasts longer. On by default: on retail it costs a few extra casts.");
ImGui.Checkbox("Chain buffs on the server's answer", ref _settings.FastBuffChain);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Send the next buff as soon as the server finishes the last one,\n" +
"without waiting for the cast's recoil animation to end.\n" +
"A refused cast turns it off for the rest of that buff pass.\n" +
"On by default. Off = every buff waits for the animation.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Protections and Banes");

View file

@ -1713,6 +1713,7 @@ internal sealed class LegacyDashboardRenderer
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;

View file

@ -260,6 +260,14 @@ public sealed class LegacyUiSettings
/// </summary>
public bool CastBuffsOverItemBuffs = true;
/// <summary>
/// In a buff pass, send the next buff as soon as the server answers the last one with
/// UseDone(0), without waiting for the client to finish the cast's recoil animation
/// (Combat/BuffCastChain.cs). Every other gate stays, and a refusal turns it off for the
/// rest of the pass. On by default; off = every buff waits for the animation (the
/// behaviour without the chain). A profile saved before this setting existed loads it as on.
/// </summary>
public bool FastBuffChain = true;
/// <summary>
/// Buff base names the player unticked in Buffing settings (the Protections and Banes grid,
/// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and
/// never waited on. Empty = every buff on, which is also what a profile saved before this

View file

@ -3596,6 +3596,7 @@ internal sealed class ExpressionEngine
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),

View file

@ -443,11 +443,16 @@ internal static class ActionPacer
private static readonly HashSet<string> _swingLogged = new();
public static long SwingHoldCount => _swingHolds;
/// <summary>Attacks CombatManager reported (NoteAttackSent): a caller that remembers the count can
/// tell whether a swing went out since (BuffCastChain). Not reset, only compared.</summary>
public static long AttacksSent { get; private set; }
/// <summary>CombatManager sent a melee or missile attack.</summary>
public static void NoteAttackSent()
{
lock (Gate)
{
AttacksSent++;
_swingSentMs = NowMs();
_swingSeenBusy = false;
_swingLogged.Clear();

View file

@ -90,6 +90,10 @@ internal static unsafe class FakeHost
public static int TapJumps;
public static int Turns;
public static readonly List<(uint Target, int SpellId)> Casts = new();
/// <summary>True: CastSpell returns false (the client refused it; nothing is recorded in <see cref="Casts"/>).</summary>
public static bool CastRefused;
/// <summary>CastSpell calls refused while <see cref="CastRefused"/> was set.</summary>
public static int CastsRefused;
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
public static bool GiveCalls;
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
@ -209,7 +213,7 @@ internal static unsafe class FakeHost
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;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; 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;
@ -654,7 +658,7 @@ internal static unsafe class FakeHost
private static int TapJump() { TapJumps++; return 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) { if (CastRefused) { CastsRefused++; return 0; } Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -99,6 +99,7 @@ internal static class Program
CastNoDamageTests.Register(runner);
ManaReserveTests.Register(runner);
DamageRowsTests.Register(runner);
BuffChainTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,299 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Buff cast chaining (Combat/BuffCastChain.cs). In a buff pass the next buff waited
// ~550 ms after the server's UseDone for the last one, held by the animation gate while the client
// played the recoil ("[Pace] Buff waits: the character is still animating"). On ACE the server
// takes the next cast right after that UseDone. The fast path skips the animation gate only, only
// right after our own buff's UseDone(0), and a refusal turns it off for the rest of the pass.
// FakeHost.CastBusy = 1 stands for "the client is still animating the recoil".
internal static class BuffChainTests
{
private const uint Player = 0x50000C01;
private const uint Corpse = 0x80068ACF;
private const uint STypeLife = 33;
private const uint TooBusy = 0x1D;
public static void Register(Runner r)
{
r.Add("buff chain: the next buff goes on the last buff's UseDone(0) while the recoil animates; setting off = waits", NextBuffOnUseDone);
r.Add("buff chain: the animation gate is kept after a non-cast action, after a UseDone error, and past the window", GateKept);
r.Add("buff chain: a refused fast-path cast turns it off for the rest of the pass; refusals counted and summed up", RefusalFallsBack);
r.Add("buff chain: FastBuffChain defaults on, loads on from an old profile and copies", SettingDefaults);
r.Add("buff chain: no Stamina to Mana for the mana reserve on the fast path; it waits for the animation, then goes", ManaReserveWaitsForAnimation);
}
// The fast path skips the animation gate, so only the buff may ride it. Mana spent by the last
// buff can leave the next one under the mana reserve (BuffWaitsForMana): Stamina to Mana is then
// cast first, and it must wait for the recoil like any vital cast.
// 50/300: under the reserve itself (the vitals check keeps the fast path off);
// 120/300: over the reserve, but under it once the next buff's 60 is paid (the cast site drops
// the fast path for that buff).
private static void ManaReserveWaitsForAnimation() => Paced(() =>
{
foreach (uint after in new uint[] { 50, 120 })
{
var r = new Rig(staminaToMana: true);
BuffManager.ManaCostOverride = id => (SpellTableStub.GetById(id)?.Level ?? 0) * 10; // after Reset: level x 10
r.S.GetManaAt = 10; r.S.TopOffMana = 10;
r.V.MaxMana = 300; r.V.CurrentMana = 300;
int reserve = r.B.ManaReserve();
Check.Eq(reserve, 90, "the reserve (1.5 x Stamina to Mana VI's 60)");
r.Tick(0);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}: the first buff goes at 300/300");
Check.True(!r.LastCast.StartsWith("Stamina to Mana", StringComparison.Ordinal), $"{after}: and it is a buff ({r.LastCast})");
r.V.CurrentMana = after; // what the buffs so far left
r.ServerRuns(0); // CastBusy = 1: the recoil still animating
r.Tick(1.55);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}/300, 50 ms after the UseDone: nothing goes during the recoil");
Check.Eq(r.B.Chain.FastCasts, 0, $"{after}: nothing on the fast path");
r.Tick(1.65);
Check.Eq(FakeHost.Casts.Count, 1, $"{after}: still nothing while it animates");
FakeHost.CastBusy = 0;
r.Tick(1.75);
Check.Eq(FakeHost.Casts.Count, 2, $"{after}: the animation over, one cast");
Check.True(r.LastCast.StartsWith("Stamina to Mana", StringComparison.Ordinal), $"{after}: it is Stamina to Mana ({r.LastCast})");
}
});
private static long _t;
private sealed class Rig
{
public DateTime T0 = new(2026, 10, 10, 14, 0, 0);
public DateTime NowAt;
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly RynthCoreHost Host;
public readonly PlayerVitalsCache V;
public Rig(bool fast = true, bool staminaToMana = false)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.SalvageCalls = true;
FakeHost.ServerGates = true;
FakeHost.LastUseDoneCalls = true;
FakeHost.UseOnCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.StopCalls = true;
FakeHost.BusyCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Corpse] = "Corpse of Drudge Skulker";
FakeHost.Bitfields[Corpse] = 0x2000;
foreach (string n in new[] { "Fire Protection Self VI", "Cold Protection Self VI", "Acid Protection Self VI" })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
if (staminaToMana)
foreach (var row in SpellTable.Rows.Where(x => x.Name.StartsWith("Stamina to Mana Self", StringComparison.Ordinal)))
FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (300, 2);
Host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, EnableBuffing = true, FastBuffChain = fast, SpellCastIntervalMs = 0,
};
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 = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
B = new BuffManager(Host, S, sm, V);
B.SetCharacterSkills(skills);
NowAt = T0;
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
FakeHost.ServerTime = 100_000;
_t = 10_000_000;
ActionPacer.NowMs = () => _t + (long)(NowAt - T0).TotalMilliseconds;
MoveAudit.NowMs = ActionPacer.NowMs;
}
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
public void Tick(double seconds) { At(seconds); B.OnHeartbeat(); }
public string LastCast => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
/// <summary>The server runs the last cast: incantation, result line, then (on ACE) the
/// recoil, then UseDone(err). The client is still animating when the UseDone arrives.</summary>
public void ServerRuns(double sentAt, uint err = 0)
{
string name = LastCast;
At(sentAt + 0.1); B.OnChatWindowText("You say, \"Zojak Tugeth\"", 17);
FakeHost.CastBusy = 1;
At(sentAt + 1.0); B.OnChatWindowText($"You cast {name} on yourself", 7);
At(sentAt + 1.5);
FakeHost.UseDone(err);
}
}
private static void PaceOn()
{
ActionPacer.Reset();
ActionPacer.Enabled = true;
UseAudit.Reset("RynthAi", () => true);
MoveAudit.Reset();
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!;
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
}
private static void PaceOff()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
UseAudit.Reset("?", null);
UseAudit.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
}
private static void Paced(Action body)
{
PaceOn();
try { body(); }
finally { PaceOff(); }
}
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
/// <summary>First buff of a pass on a quiet client: it goes on the first tick.</summary>
private static Rig FirstBuffOut(bool fast = true)
{
var r = new Rig(fast);
r.Tick(0);
Check.Eq(FakeHost.Casts.Count, 1, "the first buff of the pass goes out");
return r;
}
private static void NextBuffOnUseDone() => Paced(() =>
{
var r = FirstBuffOut();
string first = r.LastCast;
r.ServerRuns(0);
r.Tick(1.55); // 50 ms after the UseDone, the recoil still animating
Check.Eq(FakeHost.Casts.Count, 2, "the next buff goes on the UseDone(0), the recoil still animating");
Check.True(r.LastCast != first, $"and it is the next buff ({first} then {r.LastCast})");
Check.True(Logged("[BuffChain] '" + r.LastCast + "' goes without waiting for the animation"), "the fast path is logged");
Check.Eq(r.B.Chain.FastCasts, 1, "one buff on the fast path");
// The same sequence with the setting off: the buff waits for the animation, as before.
var q = FirstBuffOut(fast: false);
q.ServerRuns(0);
for (double s = 1.55; s < 2.05; s += 0.1) q.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "setting off: no buff while the recoil animates");
Check.True(Logged("[Pace] Buff waits: the character is still animating"), "held by the animation gate, as in the log");
FakeHost.CastBusy = 0;
q.Tick(2.1);
Check.Eq(FakeHost.Casts.Count, 2, "setting off: the buff goes once the animation is over");
Check.Eq(q.B.Chain.FastCasts, 0, "nothing on the fast path");
});
private static void GateKept() => Paced(() =>
{
// A corpse use went out after the buff (a non-cast action) and was answered: the next buff
// is the first after a non-cast action, so it waits for the animation.
// The buff's UseDone(0) is read on a tick the busy count holds (nothing goes), then the corpse
// use goes out and is answered.
var r = FirstBuffOut();
r.ServerRuns(0);
r.B.BusyCount = 1;
r.Tick(1.52);
Check.Eq(FakeHost.Casts.Count, 1, "the busy count holds this tick");
r.B.BusyCount = 0;
Check.True(r.Host.UseFor(Corpse, "Loot", "open the claimed corpse"), "a corpse use goes out");
FakeHost.UseDone(0);
for (double s = 1.6; s < 2.1; s += 0.1) r.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a non-cast action: the buff waits for the animation");
FakeHost.CastBusy = 0;
r.Tick(2.2);
Check.Eq(FakeHost.Casts.Count, 2, "and goes when the animation is over");
// A swing went out after the buff's UseDone(0) (no UseDone of its own): the gate is kept.
var a = FirstBuffOut();
a.ServerRuns(0);
a.B.BusyCount = 1;
a.Tick(1.52);
a.B.BusyCount = 0;
ActionPacer.NoteAttackSent();
for (double s = 1.6; s < 2.1; s += 0.1) a.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a swing: the buff waits for the animation");
// A UseDone with an error for the buff: no fast path (and a server refusal counted).
var e = FirstBuffOut();
e.ServerRuns(0, err: TooBusy);
for (double s = 1.55; s < 2.05; s += 0.1) e.Tick(s);
Check.Eq(FakeHost.Casts.Count, 1, "after a UseDone error: the buff waits for the animation");
Check.Eq(e.B.Chain.ServerRefusals, 1, "the error is counted as a server refusal");
Check.True(Logged("[BuffChain] refusal (server): UseDone error 0x1D"), "and logged");
// The UseDone(0) was read, but the client still reads busy past the window: not the recoil.
var w = FirstBuffOut();
w.ServerRuns(0);
w.B.BusyCount = 1; // something else holds the busy count meanwhile: the busy gate holds
w.Tick(1.52);
Check.Eq(FakeHost.Casts.Count, 1, "the busy gate is kept on the fast path");
w.B.BusyCount = 0;
w.Tick(1.52 + BuffCastChain.WindowMs / 1000.0 + 0.1);
Check.Eq(FakeHost.Casts.Count, 1, "past the window after the UseDone: the animation gate again");
});
private static void RefusalFallsBack() => Paced(() =>
{
var r = FirstBuffOut();
r.ServerRuns(0);
// The client refuses the fast-path cast: nothing goes out.
FakeHost.CastRefused = true;
r.Tick(1.55);
Check.Eq(FakeHost.CastsRefused, 1, "the fast-path cast was tried and the client refused it");
Check.Eq(r.B.Chain.ClientRefusals, 1, "counted as a client refusal");
Check.True(Logged("[BuffChain] refusal (client): CastSpell refused"), "logged");
Check.True(r.B.Chain.OffThisPass, "the fast path is off for the rest of the pass");
Check.True(Logged("the next buffs of this pass wait for the animation again"), "and that is logged");
FakeHost.CastRefused = false;
// The next buff waits for the animation, even right after a buff's UseDone(0).
FakeHost.CastBusy = 0;
r.Tick(1.7);
Check.Eq(FakeHost.Casts.Count, 2, "gate open: the buff goes");
double sent = 1.7;
r.ServerRuns(sent);
for (double s = sent + 1.55; s < sent + 2.05; s += 0.1) r.Tick(s);
Check.Eq(FakeHost.Casts.Count, 2, "after the refusal: the next buff waits for the animation");
FakeHost.CastBusy = 0;
r.Tick(sent + 2.1);
Check.Eq(FakeHost.Casts.Count, 3, "and goes when it ends");
// The pass ends: one summary line with this pass's refusals.
r.ServerRuns(sent + 2.1);
FakeHost.CastBusy = 0;
for (double s = sent + 3.7; s < sent + 6; s += 0.2) r.Tick(s);
Check.True(Logged("[BuffChain] buff pass complete:"), "a summary line at the end of the pass");
Check.True(Logged("refusals this pass: client 1, server 0"), "with its refusals: " +
(FakeHost.Logs.LastOrDefault(l => l.Contains("[BuffChain] buff pass")) ?? "(none)"));
});
private static void SettingDefaults()
{
Check.True(new LegacyUiSettings().FastBuffChain, "a new profile: on");
var old = System.Text.Json.JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(old != null && old.FastBuffChain, "a profile saved before the setting: on");
var off = System.Text.Json.JsonSerializer.Deserialize(
System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { FastBuffChain = false }, RynthAiJsonContext.Default.LegacyUiSettings),
RynthAiJsonContext.Default.LegacyUiSettings);
Check.True(off != null && !off.FastBuffChain, "off is saved and loaded");
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!;
var dst = new LegacyUiSettings();
copy.Invoke(null, new object[] { new LegacyUiSettings { FastBuffChain = false }, dst });
Check.False(dst.FastBuffChain, "a profile with it off loads off");
}
}