diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 385140f..36146f5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -839,6 +839,7 @@ public partial class BuffManager : IDisposable get => _busyCount; set { + if (value > 0 && _busyCount <= 0) _busyRoseAt = Now; // heal grace counts from the rise (BusyHoldsHeal) _busyCount = value; _busyGate.NoteCount(value, UseDoneSeqNow()); } @@ -868,16 +869,32 @@ public partial class BuffManager : IDisposable { if (BusyCount <= 0) return false; bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow; - if (!_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) return true; + string why; + if (_busyGate.IsStale(BusyCount, _host.HasUseDoneSeq, UseDoneSeqNow(), gesture)) + why = "the server finished the action (UseDone)"; + else + { + // Heal grace (ActionPacer.HealGraceMs): a count up this long goes too, timed from its rise so + // it does not stack on top of the pacer's own hold. The count can't say what it is waiting for + // (a lost UseDone leaves it up until the 5 s force-clear), and the cast gate and the pacer still + // hold a gesture that is really animating. + double upMs = (Now - _busyRoseAt).TotalMilliseconds; + if (upMs < ActionPacer.HealGraceMs) return true; + why = $"the count has been up {upMs:0} ms (heal grace)"; + } int was = BusyCount; StaleBusyClears++; - _onStaleBusy?.Invoke($"vitals: health is under a heal line and the server finished the action (UseDone) — was {was}"); + _onStaleBusy?.Invoke($"vitals: health is under a heal line and {why} - was {was}"); if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0 _busyGate.Reset(); return false; } /// Times a heal found the busy count was a leftover and went ahead (tests, status). internal int StaleBusyClears { get; private set; } + // When the busy count last rose from 0 (heal grace, BusyHoldsHeal). + private DateTime _busyRoseAt = DateTime.MinValue; + // This tick's cast gate was opened by the heal grace only: CheckVitals does the health block, nothing after it. + private bool _gateGraceTick; /// /// Record-only diagnostic (D4): the reason the most recent buff-decision cycle @@ -1336,6 +1353,8 @@ public partial class BuffManager : IDisposable public void OnHeartbeat() { bool track = _settings.IsMacroRunning && _vitals.MaxHealth > 0; + _gateGraceTick = false; + NoteKitProgress(); _healHold = ""; _healHoldDetail = ""; _healWaitKind = ""; @@ -1742,10 +1761,16 @@ public partial 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. + // Heal grace (ActionPacer.HealGraceMs): with health under a heal line, a gate closed this long opens + // for the vitals step (CastGateWatchdog's own backstop is 4 s, for every cast). + bool healLine = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length > 0; bool gateOpen = _fastChainTick || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)); + bool gateGrace = !gateOpen && healLine && CastGateWatchdog.ClosedMs >= ActionPacer.HealGraceMs; + if (gateGrace) gateOpen = true; // the heal only: no mana, stamina or buff goes this tick + _gateGraceTick = gateGrace; 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()); + && (!healLine || BusyHoldsHeal()); if (!gateOpen || busyHolds) { LastBuffSkipReason = busyHolds ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)"; @@ -1759,6 +1784,11 @@ public partial class BuffManager : IDisposable if (_healHold.Length == 0) Hold(_healWaitKind.Length > 0 ? _healWaitKind : "vitals step busy", _vitalWhy); return; } + if (gateGrace) + { + Hold("cast gate (a gesture is animating)"); + return; + } // /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals. if (TickSwapTest()) @@ -2120,6 +2150,10 @@ public partial class BuffManager : IDisposable if (HealthUnderAnyLine(curHealthPct, curStamPct)) _healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs); + // The cast gate was opened for the heal only (heal grace, OnHeartbeat): the character may still + // be mid-gesture, so no mana or stamina action goes out on this tick. + if (_gateGraceTick) return false; + // Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina // to Mana (ManaUnderLine; see "Mana reserve" at the top). bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _); @@ -2753,10 +2787,44 @@ public partial class BuffManager : IDisposable // and used a second kit, every time (2026-10-03). After a kit, vitals wait for the // kit's own result line (heal, fail, movement disrupted, already at full), plus // KitLandGraceMs for the vitals to catch up, or KitResultTimeoutMs with no line at all. + // + // Heal grace ("stuck in Healing"): a kit that got no result line left the vitals waiting 8 s and + // more with the label reading Healing and nothing else healing, long enough for the character to die. + // VirindiTank re-sends a kit every 100 ms until the server plays the heal motion (3 s at most), + // then waits up to 3 s for the result line. Here (KitWaitVerdict): a kit the server shows no sign + // of having taken (no animation since the send, no UseDone, no line) is let go after + // ActionPacer.HealGraceMs and the next tick sends it again; a UseDone(0) with no line ends the + // wait after KitLandGraceMs (ACE sends the line before the UseDone, so none is coming); and a + // started kit is waited for KitResultTimeoutMs at most (3.5 s; a healthy kit answers in 2.5 s). private DateTime _kitUsedAt = DateTime.MinValue; private DateTime _kitLandedAt = DateTime.MinValue; - private const double KitResultTimeoutMs = 8000; + private DateTime _kitAnsweredAt = DateTime.MinValue; // a UseDone(0) since the send (no line yet) + private bool _kitSawAnimating; // the motion queue read busy since the send + // 3.5 s: the longest healthy kit answer is 2.5 s (ActionPacer's header). The same value as + // ActionPacer.ItemUseMaxMs today, but its own number: a change to the pacer's limit is not one here. + // Stamina kits share this wait (KitPending). + internal const double KitResultTimeoutMs = 3500; private const double KitLandGraceMs = 700; + /// Kits let go with no result (heal grace or the time limit) and sent again (tests, status). + internal int KitRetries { get; private set; } + + internal enum KitWaitEnd { Waiting, Landed, Answered, NotTaken, TimedOut } + + /// + /// The kit wait, from what has been seen since the send (pure; ms values below 0 = not seen): + /// the result line plus KitLandGraceMs; a UseDone(0) with no line plus KitLandGraceMs; nothing + /// at all from the server ( false) and not animating now after + /// ActionPacer.HealGraceMs; or KitResultTimeoutMs whatever happened. + /// + internal static KitWaitEnd KitWaitVerdict(double msSinceUse, double msSinceLanded, double msSinceAnswered, + bool serverTookIt, bool animatingNow) + { + if (msSinceLanded >= 0) return msSinceLanded >= KitLandGraceMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting; + if (msSinceAnswered >= KitLandGraceMs) return KitWaitEnd.Answered; + if (!serverTookIt && !animatingNow && msSinceUse >= ActionPacer.HealGraceMs) return KitWaitEnd.NotTaken; + if (msSinceUse >= KitResultTimeoutMs) return KitWaitEnd.TimedOut; + return KitWaitEnd.Waiting; + } // A refused kit (2026-10-05): ACE answers a kit used while the character is busy (a swing, a // cast still resolving), in the air, or on something it can't heal with a UseDone error and @@ -2777,10 +2845,36 @@ public partial class BuffManager : IDisposable { _kitUsedAt = RynthClock.Now; _kitLandedAt = DateTime.MinValue; + _kitAnsweredAt = DateTime.MinValue; + _kitSawAnimating = false; _kitIsStamina = stamina; _kitSeqAtUse = UseDoneSeqNow(); } + private bool MotionQueueBusy => _host.HasGetCastBusyState && !_host.CanCastNow; + + /// + /// The server has shown it took the kit in flight (its heal motion, or its UseDone(0)). An engine with + /// neither GetCastBusyState nor the UseDone sequence can show neither, so the kit counts as taken and + /// only KitResultTimeoutMs ends the wait (no retry at the heal grace for a kit that may be playing). + /// + private bool KitServerTookIt() => + (!_host.HasGetCastBusyState && !_host.HasUseDoneSeq) || _kitSawAnimating || _kitAnsweredAt != DateTime.MinValue; + + /// + /// Records what the server has done with the kit in flight: the heal motion playing (the client's + /// motion queue busy) or a UseDone(0). Every heartbeat (the vitals step is not reached while the + /// character animates) and from KitPending. + /// + private void NoteKitProgress() + { + if (_kitUsedAt == DateTime.MinValue || _kitLandedAt != DateTime.MinValue) return; + if (!_kitSawAnimating && MotionQueueBusy) _kitSawAnimating = true; + if (_kitAnsweredAt == DateTime.MinValue && _host.HasUseDoneSeq && _host.TryGetLastUseDone(out int seq, out uint err) + && seq == _kitSeqAtUse + 1 && err == 0) // the first UseDone after the send (as the pacer pairs a cast) + _kitAnsweredAt = RynthClock.Now; + } + internal bool KitPending() { if (_kitUsedAt == DateTime.MinValue) return false; @@ -2791,12 +2885,30 @@ public partial class BuffManager : IDisposable KitRefused($"UseDone error 0x{err:X}"); return false; } + NoteKitProgress(); DateTime now = RynthClock.Now; - bool done = _kitLandedAt != DateTime.MinValue - ? (now - _kitLandedAt).TotalMilliseconds >= KitLandGraceMs - : (now - _kitUsedAt).TotalMilliseconds >= KitResultTimeoutMs; - if (done) { _kitUsedAt = DateTime.MinValue; _kitLandedAt = DateTime.MinValue; } - return !done; + double sinceUse = (now - _kitUsedAt).TotalMilliseconds; + var end = KitWaitVerdict(sinceUse, + _kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds : -1, + _kitAnsweredAt != DateTime.MinValue ? (now - _kitAnsweredAt).TotalMilliseconds : -1, + KitServerTookIt(), MotionQueueBusy); + if (end == KitWaitEnd.Waiting) return true; + if (end != KitWaitEnd.Landed) + { + KitRetries++; + string what = end switch + { + KitWaitEnd.Answered => "was answered (UseDone) with no result line", + KitWaitEnd.NotTaken => "shows no sign the server took it (no motion, no UseDone, no result line)", + _ => "has no result line yet", + }; + _host.Log($"[RynthAi] Vitals: the {(_kitIsStamina ? "stamina" : "healing")} kit {what} {sinceUse:0} ms after use: " + + "vitals carry on (heal grace), the next tick may send it again."); + } + _kitUsedAt = DateTime.MinValue; + _kitLandedAt = DateTime.MinValue; + _kitAnsweredAt = DateTime.MinValue; + return false; } /// The kit in flight was refused: no result line will come, so stop waiting for one. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs index c57d8a6..3311c96 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastGateWatchdog.cs @@ -30,6 +30,10 @@ internal static class CastGateWatchdog private static DateTime _closedSince = DateTime.MinValue; private static bool _overriding; + /// How long the raw gate has read closed (0 = open), as of the last CanCastNow call. + /// A heal under a heal line goes past ActionPacer.HealGraceMs of it (BuffManager). + public static double ClosedMs => _closedSince == DateTime.MinValue ? 0 : (RynthClock.Now - _closedSince).TotalMilliseconds; + /// /// Effective "clear to cast": the raw engine gate plus a stuck backstop. /// Call with _host.CanCastNow; optionally pass a logger for the diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index fef99c6..6c0dd9a 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -147,6 +147,14 @@ internal static class ActionPacer public const long NoUseDoneFallbackMs = 600; /// The longest one ask for the player's turn holds RynthAi (RynthAiYieldApiV1.MaxHoldMs). public const long PlayerHoldMaxMs = 3000; + /// + /// Heal grace (the "stuck in Healing" report): the longest a heal under a heal line waits on + /// an item use nobody answered, on the character's animation, or on the 'too busy' probe. Past it the heal + /// goes (a refusal is an answer too, and the next heal retries), as VirindiTank does: it re-sends a kit + /// until the server starts it and never parks on the client's busy state. Corpse/door uses and our own + /// casts keep their rules (a server turn to stop; a cast the server would refuse). + /// + public const long HealGraceMs = 2000; private static readonly object Gate = new(); private static PacedAction? _cur; @@ -157,6 +165,7 @@ internal static class ActionPacer private static long _gestureHolds, _gestureLimits; private static long _gestureBusySince; // when the client's motion queue was first seen busy (0 = clear) private static bool _gestureOverride; // the hold limit passed: open until the queue reads clear + private static bool _gestureHealGrace; // the heal grace let a heal through this busy spell (logged once) private static readonly HashSet _gestureLogged = new(); private static long _maxWaitMs; private static string _maxWaitWhat = ""; @@ -195,6 +204,7 @@ internal static class ActionPacer _swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear(); _gestureBusySince = 0; _gestureOverride = false; + _gestureHealGrace = false; _gestureLogged.Clear(); _maxWaitMs = 0; _maxWaitWhat = ""; @@ -529,6 +539,15 @@ internal static class ActionPacer lock (Gate) _healsAhead++; return true; } + // An item use (a kit, a potion, a wield) still unanswered after HealGraceMs: the heal goes (see + // HealGraceMs). Its own pack has no server turn to stop; a lost or swallowed kit is re-sent here. + if (a.Kind == PacedKind.ItemUse && age >= HealGraceMs) + { + bool logAhead; + lock (Gate) { _healsAhead++; logAhead = a.LoggedWaits.Add(who + "/heal-grace"); } + if (logAhead) Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms, heal grace {HealGraceMs} ms)"); + return true; + } } why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet"; @@ -570,6 +589,7 @@ internal static class ActionPacer line = "[Pace] the character's animation queue reads clear again"; _gestureBusySince = 0; _gestureOverride = false; + _gestureHealGrace = false; _gestureLogged.Clear(); } else @@ -592,6 +612,17 @@ internal static class ActionPacer line = $"[Pace] {who}: emergency heal after {age} ms of animation - going on"; busy = false; } + else if (heal == HealNeed.Heal && age >= HealGraceMs) + { + // Once per busy spell: logged and counted when the grace first lets a heal through. + if (!_gestureHealGrace) + { + _gestureHealGrace = true; + _gestureLimits++; + line = $"[Pace] {who}: heal after {age} ms of animation (heal grace) - going on"; + } + busy = false; + } else { _gestureHolds++; @@ -915,8 +946,11 @@ internal static class ActionPacer // use would send first every time and the heal would see the next slot, up to BusyProbeMaxMs later). if (heal == HealNeed.Heal && _busySince != 0) _healWaitAt = now; bool healWaiting = heal != HealNeed.Heal && _healWaitAt != 0 && now - _healWaitAt < HealWaitFreshMs; + // A waiting heal's probe comes at least every HealGraceMs (the doubling would reach BusyProbeMaxMs). + long probeWait = Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs); + if (heal == HealNeed.Heal) probeWait = Math.Min(probeWait, HealGraceMs); if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting - && now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs)) + && now - Math.Max(_busySince, _lastProbeAt) >= probeWait) { probe = true; // spent in MayStart once the start passes its other checks (SpendTryAfterBusy) } diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 589dd0f..9b44e45 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -191,6 +191,7 @@ internal static class Program CommandReplyTests.Register(runner); MonsterStatsTests.Register(runner); MetaSaveTests.Register(runner); + HealGraceTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs new file mode 100644 index 0000000..fe84c5c --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs @@ -0,0 +1,360 @@ +using System; +using System.Linq; +using System.Reflection; +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; + +// Heal grace ("stuck in Healing"): a heal under a heal line waits on nothing pending for more than +// ActionPacer.HealGraceMs. A healing kit with no result line used to leave 8 s with nothing healing +// (the kit wait's old timeout), long enough to die. +// VirindiTank re-sends a kit until the server starts it, never parking on the busy state. +internal static class HealGraceTests +{ + private const uint Player = 0x50000E41; + private const uint Corpse = 0x80068AD1; + private const uint Kit = 0x8004BF01; + private const uint Pack = Player; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("heal grace: the kit wait ends on its line, a UseDone(0) with no line, 2 s with no sign the server took it, or 3.5 s", KitWaitVerdicts); + r.Add("heal grace: a heal goes ahead of an item use nobody answered after 2 s; a corpse use and a non-heal still wait", PacerItemUseGrace); + r.Add("heal grace: a plain heal waits at most 2 s on the character's animation; a non-heal still waits", PacerGestureGrace); + r.Add("heal grace: a live busy count holds a heal 2 s at most from its rise (not on top of the pacer's hold)", BusyCountGrace); + r.Add("heal grace: KitPending lets a kit with no sign from the server go at 2 s (a retry)", KitNoProgressRetried); + r.Add("heal grace: KitPending waits for a kit the server started up to 3.5 s", KitStartedWaitsToLimit); + r.Add("heal grace: with neither GetCastBusyState nor the UseDone sequence, a kit waits the 3.5 s limit (no retry at 2 s)", KitNoSignalsWaitsToLimit); + r.Add("heal grace: KitPending ends 700 ms after the kit's own UseDone(0) with no line; a later UseDone is not its answer", KitAnsweredNoLine); + r.Add("heal grace: the heartbeat heals once the cast gate has been closed 2 s", GateGraceHeals); + r.Add("heal grace: a gate opened for the heal sends no Stamina to Mana when nothing heals", GateGraceNoManaCast); + } + + private static void KitWaitVerdicts() + { + const double G = ActionPacer.HealGraceMs; + Check.Eq(BuffManager.KitWaitVerdict(500, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "500 ms, nothing yet: wait"); + Check.Eq(BuffManager.KitWaitVerdict(G - 1, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "just under the grace: wait"); + Check.Eq(BuffManager.KitWaitVerdict(G, -1, -1, false, false), BuffManager.KitWaitEnd.NotTaken, "the grace with no sign from the server: let go (sent again)"); + Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, false, true), BuffManager.KitWaitEnd.Waiting, "animating now: the kit may be playing, wait"); + Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, true, false), BuffManager.KitWaitEnd.Waiting, "the heal motion was seen: wait for its line"); + Check.Eq(BuffManager.KitWaitVerdict(3500, -1, -1, true, true), BuffManager.KitWaitEnd.TimedOut, "3.5 s whatever happened: let go"); + Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 699, true, false), BuffManager.KitWaitEnd.Waiting, "UseDone(0) 699 ms ago, no line: wait"); + Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, false), BuffManager.KitWaitEnd.Answered, "UseDone(0) 700 ms ago, no line: none is coming"); + Check.Eq(BuffManager.KitWaitVerdict(1200, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "line seen 300 ms ago: the vitals grace runs"); + Check.Eq(BuffManager.KitWaitVerdict(9000, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "a line seen: its grace runs out even past the limit"); + Check.Eq(BuffManager.KitWaitVerdict(1200, 700, -1, true, false), BuffManager.KitWaitEnd.Landed, "line seen 700 ms ago: done"); + } + + private static long _t; + + private static RynthCoreHost PacedWorld() + { + 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 = 2; + FakeHost.Names[Player] = "Tester"; + FakeHost.Names[Corpse] = "Corpse of Drumtaken Ursuin"; + FakeHost.Names[Kit] = "Treated Healing Kit"; + FakeHost.Bitfields[Corpse] = 0x2000; + FakeHost.Containers[Kit] = Pack; + _t = 20_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + UseAudit.Reset("RynthAi", () => true); + UseAudit.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!; + UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u }); + return FakeHost.Create(Player); + } + + 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; + FakeHost.CastBusy = 0; + } + + private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + + private static void PacerItemUseGrace() + { + try + { + var host = PacedWorld(); + host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"); + Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the kit is the outstanding action"); + _t += ActionPacer.HealGraceMs - 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: the heal waits for the kit's answer"); + _t += 1; + Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at the grace: a non-heal still waits"); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes (the kit is sent again)"); + Check.True(Logged("heal grace"), "logged"); + + // A corpse use keeps its rule: a plain heal waits for its answer (the server's turn to it). + host.UseFor(Corpse, "Loot", "open"); + _t += 3900; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a corpse use at 3.9 s: the plain heal still waits"); + FakeHost.UseDone(0); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes"); + } + finally { PaceOff(); } + } + + private static void PacerGestureGrace() + { + try + { + var host = PacedWorld(); + FakeHost.CastBusy = 1; // the client's motion queue reads busy + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "animating: the heal waits"); + _t += ActionPacer.HealGraceMs - 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: still waits"); + _t += 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "at the grace: a buff still waits (its limit is GestureHoldMaxMs)"); + long limitsBefore = ActionPacer.GestureLimits; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes"); + _t += 100; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "and on the next tick of the same busy spell"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("of animation (heal grace)", StringComparison.Ordinal)), 1, "logged once per busy spell"); + Check.Eq(ActionPacer.GestureLimits - limitsBefore, 1L, "counted once per busy spell"); + FakeHost.CastBusy = 0; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the queue reads clear: the spell ends"); + FakeHost.CastBusy = 1; + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a new busy spell: the heal waits again"); + _t += ActionPacer.HealGraceMs; + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "its grace: goes"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("of animation (heal grace)", StringComparison.Ordinal)), 2, "logged once for the new spell"); + } + finally { PaceOff(); } + } + + private static void BusyCountGrace() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false }; + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, v); + var t0 = new DateTime(2026, 1, 1, 12, 0, 0); + DateTime now = t0; + b.Clock = () => now; + var resets = new System.Collections.Generic.List(); + b.SetStaleBusyCallback(why => resets.Add(why)); + + FakeHost.UseDoneSeq = 5; + b.BusyCount = 1; // rises at t0: a count with no UseDone since, real as far as anyone can tell + Check.True(b.BusyHoldsHeal(), "t=0: the count holds the heal"); + // The pacer held the heal for 1.9 s meanwhile, so BusyHoldsHeal was not asked: the grace still + // counts from the rise, not from the first time the count held the heal. + now = t0.AddMilliseconds(ActionPacer.HealGraceMs - 1); + Check.True(b.BusyHoldsHeal(), "1 ms under the grace from the rise: held"); + now = t0.AddMilliseconds(ActionPacer.HealGraceMs); + Check.False(b.BusyHoldsHeal(), "2 s after the rise: the heal goes"); + Check.Eq(b.StaleBusyClears, 1, "cleared once"); + Check.Eq(b.BusyCount, 0, "the count is reset"); + Check.True(resets.Count == 1 && resets[0].Contains("heal grace", StringComparison.Ordinal), "through the stale-busy callback, saying why"); + + // First asked 1.9 s after the rise (the pacer's hold): the count holds it only 0.1 s more. + now = t0.AddMilliseconds(10_000); + b.BusyCount = 1; + now = t0.AddMilliseconds(11_900); + Check.True(b.BusyHoldsHeal(), "first asked 1.9 s after the rise: held"); + now = t0.AddMilliseconds(12_000); + Check.False(b.BusyHoldsHeal(), "2.0 s after the rise: goes (no 2 s more on top of the pacer's hold)"); + + // A count that only goes up further (1 -> 2) keeps its rise time. + now = t0.AddMilliseconds(20_000); + b.BusyCount = 1; + now = t0.AddMilliseconds(21_000); + b.BusyCount = 2; + now = t0.AddMilliseconds(22_000); + Check.False(b.BusyHoldsHeal(), "2 s after the first rise, 1 s after 1 -> 2: goes"); + } + + // -- KitPending, NoteKitProgress and the gate grace, driven through BuffManager (real time: + // the kit wait and CastGateWatchdog read RynthClock) ---------------------------------- + + private sealed class Rig + { + public readonly BuffManager B; + public readonly LegacyUiSettings S; + public readonly RynthCoreHost H; + public Rig(int healthPct = 40, int manaPct = 100, bool healSelfKnown = true, bool serverGates = true) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = serverGates; // GetCastBusyState and the UseDone sequence + FakeHost.LastUseDoneCalls = serverGates; + FakeHost.CombatModeValue = CombatMode.Magic; + int healCat = SpellTable.Named("Heal Self I").First().Category; + foreach (var row in SpellTable.Rows) + if (healSelfKnown || row.Category != healCat) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic + var host = FakeHost.Create(); + H = host; + S = new LegacyUiSettings + { + IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, 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); + var 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); + B.MarkLiveBuffsReadyForTests(); + CastGateWatchdog.CanCastNow(true); // the watchdog is static: start from an open gate + } + } + + private static int CastsOf(string firstLevelName) + { + int cat = SpellTable.Named(firstLevelName).First().Category; + return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat); + } + + private static void SleepUntil(System.Diagnostics.Stopwatch sw, long ms) + { + long left = ms - sw.ElapsedMilliseconds; + if (left > 0) System.Threading.Thread.Sleep((int)left); + } + + private static void KitNoProgressRetried() + { + var r = new Rig(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + Check.True(r.B.KitPending(), "kit just used: waiting"); + SleepUntil(sw, 1700); + Check.True(r.B.KitPending(), "1.7 s, nothing from the server: still waiting"); + SleepUntil(sw, (long)ActionPacer.HealGraceMs + 100); + Check.False(r.B.KitPending(), "past the heal grace with no motion, UseDone or line: let go"); + Check.Eq(r.B.KitRetries, 1, "counted as a retry"); + Check.True(FakeHost.Logs.Any(l => l.Contains("shows no sign the server took it", StringComparison.Ordinal)), "logged"); + } + + // An engine with neither GetCastBusyState nor the UseDone sequence can't show the server took a kit: + // no retry at the heal grace (the kit may be playing), only the 3.5 s limit. + private static void KitNoSignalsWaitsToLimit() + { + var r = new Rig(serverGates: false); + Check.False(r.H.HasGetCastBusyState || r.H.HasUseDoneSeq, "the rig: neither capability"); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + SleepUntil(sw, (long)ActionPacer.HealGraceMs + 300); + Check.True(r.B.KitPending(), "past the heal grace: still waiting (nothing could show the server took it)"); + Check.Eq(r.B.KitRetries, 0, "no retry at 2 s"); + SleepUntil(sw, 3500 + 150); + Check.False(r.B.KitPending(), "past 3.5 s: let go"); + } + + private static void KitStartedWaitsToLimit() + { + var r = new Rig(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + FakeHost.CastBusy = 1; // the heal motion plays + r.B.OnHeartbeat(); // the heartbeat records it (NoteKitProgress) + FakeHost.CastBusy = 0; + SleepUntil(sw, 3300); + Check.True(r.B.KitPending(), "the server took it: 3.3 s, still waiting for its line"); + SleepUntil(sw, 3500 + 150); // the 3.5 s limit, as a literal: the test must not follow the constant + Check.False(r.B.KitPending(), "past 3.5 s: let go"); + Check.Eq(r.B.KitRetries, 1, "counted"); + } + + private static void KitAnsweredNoLine() + { + var r = new Rig(); + FakeHost.UseDoneSeq = 10; + var sw = System.Diagnostics.Stopwatch.StartNew(); + r.B.MarkKitUsed(); + FakeHost.UseDone(0); // the kit's own answer (seq + 1), no result line + Check.True(r.B.KitPending(), "answered just now: the line could still be in flight"); + SleepUntil(sw, 550); + Check.True(r.B.KitPending(), "550 ms after the answer: waiting"); + SleepUntil(sw, 850); + Check.False(r.B.KitPending(), "700 ms after a UseDone(0) with no line: none is coming, let go"); + + // Not the kit's own answer: two UseDones since the send (another action's, then one more). + var o = new Rig(); + FakeHost.UseDoneSeq = 20; + var sw2 = System.Diagnostics.Stopwatch.StartNew(); + o.B.MarkKitUsed(); + FakeHost.UseDone(0); + FakeHost.UseDone(0); + Check.True(o.B.KitPending(), "seq + 2 is not the kit's answer"); + SleepUntil(sw2, 850); + Check.True(o.B.KitPending(), "850 ms: still waiting (not taken as answered)"); + } + + private static void GateGraceHeals() + { + var r = new Rig(healthPct: 40); + try + { + FakeHost.CastBusy = 1; // the client's gesture gate reads closed + r.B.OnHeartbeat(); + Check.Eq(CastsOf("Heal Self I"), 0, "gate just closed: no heal"); + System.Threading.Thread.Sleep((int)ActionPacer.HealGraceMs + 100); + r.B.OnHeartbeat(); + Check.Eq(CastsOf("Heal Self I"), 1, "gate closed past the heal grace: Heal Self goes"); + } + finally { FakeHost.CastBusy = 0; CastGateWatchdog.CanCastNow(true); } + } + + private static void GateGraceNoManaCast() + { + var r = new Rig(healthPct: 40, manaPct: 10, healSelfKnown: false); + r.S.GetManaAt = 50; r.S.TopOffMana = 50; + try + { + FakeHost.CastBusy = 1; + r.B.OnHeartbeat(); + System.Threading.Thread.Sleep((int)ActionPacer.HealGraceMs + 100); + r.B.OnHeartbeat(); + Check.Eq(CastsOf("Heal Self I"), 0, "no Heal Self known: nothing heals"); + Check.Eq(CastsOf("Stamina to Mana Self I"), 0, "the gate opened for the heal only: no Stamina to Mana mid-gesture"); + // Control: with the gate really open the same state does cast Stamina to Mana. + FakeHost.CastBusy = 0; + r.B.OnHeartbeat(); + Check.Eq(CastsOf("Stamina to Mana Self I"), 1, "control: gate open, Stamina to Mana goes"); + } + finally { FakeHost.CastBusy = 0; CastGateWatchdog.CanCastNow(true); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs index 80720d5..8352b97 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs @@ -375,31 +375,55 @@ internal static class StuckCastTests private static void ProbeWhenNothingOpen() { + // A start that is no heal: a waiting heal's probe is capped at ActionPacer.HealGraceMs (below). + bool Start(RynthCoreHost h) => MayAs(h, "Buff", HealNeed.None); var host = Setup(); try { - Check.True(May(host), "free"); + Check.True(Start(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"); + Check.False(Start(host), "held right after the 0x1D"); _t += ActionPacer.BusyProbeMs - 1; - Check.False(May(host), "held until BusyProbeMs"); + Check.False(Start(host), "held until BusyProbeMs"); _t += 1; - Check.True(May(host), "one probe at BusyProbeMs"); - Check.False(May(host), "only one"); + Check.True(Start(host), "one probe at BusyProbeMs"); + Check.False(Start(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"); + Check.False(Start(host), "the next probe waits twice as long"); _t += 1; - Check.True(May(host), "second probe at 2 x BusyProbeMs"); + Check.True(Start(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"); + Check.True(Start(host), "a UseDone(0) clears it"); + } + finally { Done(); } + + // Heal grace: a plain heal's probe comes at least every HealGraceMs, where the doubling would make it 3 s. + var heal = Setup(); + try + { + Check.True(May(heal), "free"); + Cast(heal, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); + Check.False(May(heal), "held right after the 0x1D"); + _t += ActionPacer.BusyProbeMs; + Check.True(May(heal), "the heal's first probe at BusyProbeMs"); + Cast(heal, "Heart Rend"); + _t += 100; + FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again + Check.False(May(heal), "held right after the second 0x1D"); + _t += ActionPacer.HealGraceMs - 101; + Check.False(May(heal), "1 ms under the heal grace: held"); + _t += 1; + Check.True(May(heal), "the heal's second probe at HealGraceMs, not 2 x BusyProbeMs"); } finally { Done(); } }