diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index a0bc785..8d10537 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -1423,7 +1423,7 @@ public class BuffManager : IDisposable
bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
- int stamThreshold = inCombat ? _settings.RestamAt : _settings.TopOffStam;
+ int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
// A flag is set only when something was actually done about the vital.
// WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so
@@ -1479,16 +1479,54 @@ public class BuffManager : IDisposable
}
// Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits
// and cast Revitalize/Robustification instead, because stamina never looked for a kit.
- if (curStamPct < stamThreshold && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self")
- || AttemptPotion("StaminaPotion", "Stamina")))
+ // Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon
+ // for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina
+ // potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize
+ // on top of it. In Magic stance (a caster) Revitalize stays first.
+ bool potionFirst = CurrentCombatMode != CombatMode.Magic;
+ if (curStamPct < stamThreshold)
{
- _isRechargingStamina = true;
- return true;
+ bool potionJustDrunk = potionFirst && _settings.UsePotions
+ && (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500
+ && HasListedPotion("StaminaPotion", "Stamina");
+ if (!potionJustDrunk
+ && (AttemptStaminaKitUse()
+ || (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
+ || AttemptVitalCast("Revitalize Self")
+ || AttemptPotion("StaminaPotion", "Stamina")))
+ {
+ _isRechargingStamina = true;
+ if (_restamRun) _restamRunCasts++;
+ return true;
+ }
}
return false;
}
+ // Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina
+ // reaches Re-stam To; one Revitalize often doesn't get far. Capped so a recharge that
+ // never gains can't loop: it ends after RestamRunMaxCasts.
+ private bool _restamRun;
+ private int _restamRunCasts;
+ internal const int RestamRunMaxCasts = 4;
+
+ /// The stamina % to recharge under now (see the fields above).
+ internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts)
+ {
+ if (!inCombat) { run = false; return s.TopOffStam; }
+ if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; }
+ if (stamPct < s.RestamAt)
+ {
+ if (!run) { run = true; casts = 0; }
+ }
+ else if (stamPct >= s.RestamTo || casts >= RestamRunMaxCasts)
+ {
+ run = false;
+ }
+ return run ? s.RestamTo : s.RestamAt;
+ }
+
/// True when Stamina To Health At / Min Stamina allow Stamina to Health Self now.
internal static bool StaminaToHealthAllowed(LegacyUiSettings s, int healthPct, int staminaPct)
=> s.StaminaToHealthAt > 0 && healthPct <= s.StaminaToHealthAt && staminaPct > s.StaminaToHealthMinStamina;
@@ -1644,7 +1682,21 @@ public class BuffManager : IDisposable
/// Drinks the first potion of from the Items panel.
/// "Stamina" is the older name for stamina potions. Off with UsePotions.
///
- private bool AttemptPotion(params string[] types)
+ private bool AttemptPotion(params string[] types) => AttemptPotion(false, types);
+
+ /// A potion of one of listed in Consumables and in the pack.
+ private bool HasListedPotion(params string[] types)
+ {
+ if (_worldObjectCache == null) return false;
+ foreach (var rule in _settings.ConsumableRules)
+ if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) >= 0
+ && _worldObjectCache[rule.Id] != null)
+ return true;
+ return false;
+ }
+
+ /// : only the Consumables list, not any potion in the pack.
+ private bool AttemptPotion(bool listedOnly, params string[] types)
{
if (!_settings.UsePotions || _worldObjectCache == null) return VitalNo("Use Potions is off");
if ((DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago");
@@ -1660,6 +1712,7 @@ public class BuffManager : IDisposable
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
return true;
}
+ if (listedOnly) return VitalNo("none listed in Consumables");
// Nothing on the Items panel: anything in the pack of that kind (Field Rations
// weren't used unless someone added them by hand, 2026-09-29).
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index 9e23a11..8d17476 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -922,6 +922,7 @@ public partial class CombatManager : IDisposable
{
int id = (int)objectId;
_recentlyKilled.Remove(id);
+ _hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId)
@@ -1201,21 +1202,37 @@ public partial class CombatManager : IDisposable
bool critLine = text.IndexOf("critical", StringComparison.OrdinalIgnoreCase) >= 0;
if (critLine) _lastCritChatAt = now;
- if (!TryParseOutgoingDamage(text, out int amount)) return;
+ if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return;
bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS;
- // Attribute to the current fight; if it's already cleared (we one-shot and
- // moved on before the damage line landed), fall back to the last-fight
- // snapshot — same wcid as the bolt, so the crit/non-crit average is right.
- bool cur = _fightTargetWcid != 0;
- uint wcid = cur ? _fightTargetWcid : _lastFightWcid;
+ // Which monster the line is about. One spell can hurt several (rings, walls, blasts,
+ // chain spells): each sends its own line naming its victim, and only the selected target
+ // gets health from the server. A line naming the fight target is the fight's; any other
+ // goes to the monster it names (CreditHitToOther), never to the fight target.
+ int victimId = ResolveHitVictim(victim, now);
+ bool cur = _fightTargetWcid != 0;
+ bool onFight = cur && (victimId != 0
+ ? victimId == _fightTargetId
+ : victim.Equals(_fightTargetName, StringComparison.OrdinalIgnoreCase));
+ // Fight already cleared (we one-shot and moved on before the line landed): the line
+ // belongs to the last fight when it names it.
+ bool onLastFight = !onFight && !cur && _lastFightWcid != 0
+ && victim.Equals(_lastFightName, StringComparison.OrdinalIgnoreCase);
if (_dmgDbgCount < 15)
{
_dmgDbgCount++;
- _host.Log($"[DmgDbg] amt={amount} crit={crit} wcid={wcid} mode={CurrentCombatMode} text='{text}'");
+ _host.Log($"[DmgDbg] amt={amount} crit={crit} victim='{victim}' id=0x{(uint)victimId:X8} fight={(onFight ? 1 : onLastFight ? 2 : 0)} mode={CurrentCombatMode} text='{text}'");
}
+ if (!onFight && !onLastFight)
+ {
+ CreditHitToOther(victimId, victim, amount, crit);
+ return;
+ }
+
+ uint wcid = onFight ? _fightTargetWcid : _lastFightWcid;
+
// MAGIC-ONLY: melee/missile get the structured 0x01B1 event (OnCombatDamage),
// so parsing chat for them too would double-count.
if (CurrentCombatMode != CombatMode.Magic || wcid == 0) return;
@@ -1224,16 +1241,147 @@ public partial class CombatManager : IDisposable
// line is the ONLY damage signal for casters — without accumulating it,
// _fightDamage stayed 0: EvaluateKillShot path B always saw a full-HP
// target and RecordKill(totalDamage:0) never learned HP pools.
- if (cur)
+ if (onFight)
_fightDamage += amount;
- uint weapon = cur ? _lastCastWeaponId : _lastFightWeaponId;
- string nm = cur ? _fightTargetName : _lastFightName;
- string elem = cur ? _lastCastElement : _lastFightElement;
- int tier = cur ? _lastCastTier : _lastFightTier;
+ uint weapon = onFight ? _lastCastWeaponId : _lastFightWeaponId;
+ string nm = onFight ? _fightTargetName : _lastFightName;
+ string elem = onFight ? _lastCastElement : _lastFightElement;
+ int tier = onFight ? _lastCastTier : _lastFightTier;
_damageStore.RecordHit(weapon, wcid, nm, elem, tier, amount, crit);
}
+ // ── Hits on monsters other than the fight target ─────────────────────────
+ // A ring, wall, blast or chain spell hurts several monsters with one cast; each gets a
+ // damage line naming it. Same-named monsters (a swarm) are told apart by order: within one
+ // volley (lines no more than VolleyWindowMs apart) a monster is hit once, so the fight
+ // target takes the first line with its name and every further one goes to the nearest
+ // other monster of that name not yet hit in the volley.
+ private readonly Dictionary _hitAt = new(); // last line credited to each id
+ private const double VolleyWindowMs = 800;
+ private const double HitMemoryMs = 15000; // hits older than this are forgotten
+ private const double KillMatchRecentHitMs = 5000; // a kill notice is matched to hits this recent
+
+ ///
+ /// The object a damage line naming is about, or 0 when no live monster
+ /// of that name is known. Stamps the hit so the next same-named line of the volley goes elsewhere.
+ ///
+ internal int ResolveHitVictim(string name, DateTime now)
+ {
+ if (string.IsNullOrEmpty(name)) return 0;
+ PruneHits(now);
+ int fight = _fightTargetId;
+ if (fight != 0 && !HitInVolley(fight, now)
+ && string.Equals(_worldFilter[fight]?.Name, name, StringComparison.OrdinalIgnoreCase))
+ {
+ _hitAt[fight] = now;
+ return fight;
+ }
+
+ int anchor = fight != 0 ? fight : unchecked((int)_playerId);
+ int best = 0, any = 0;
+ double bestD = double.MaxValue, anyD = double.MaxValue;
+ foreach (var wo in _worldFilter.GetLandscape())
+ {
+ if (wo.ObjectClass != AcObjectClass.Monster) continue;
+ if (!string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase)) continue;
+ if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; // the server said dead
+ double d = anchor != 0 ? _worldFilter.Distance(anchor, wo.Id) : 0.0;
+ if (any == 0 || d < anyD) { any = wo.Id; anyD = d; }
+ if (wo.Id == fight || HitInVolley(wo.Id, now)) continue;
+ if (best == 0 || d < bestD) { best = wo.Id; bestD = d; }
+ }
+ int id = best != 0 ? best : any;
+ if (id != 0) _hitAt[id] = now;
+ return id;
+ }
+
+ private bool HitInVolley(int id, DateTime now)
+ => _hitAt.TryGetValue(id, out DateTime t) && (now - t).TotalMilliseconds <= VolleyWindowMs;
+
+ private readonly List _hitPruneScratch = new();
+ private void PruneHits(DateTime now)
+ {
+ if (_hitAt.Count < 64) return;
+ _hitPruneScratch.Clear();
+ foreach (var kv in _hitAt)
+ if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _hitPruneScratch.Add(kv.Key);
+ foreach (int id in _hitPruneScratch) _hitAt.Remove(id);
+ }
+
+ ///
+ /// A hit on a monster that isn't the fight target (another target of a ring, wall or chain
+ /// spell): lower its health estimate (the server sends it none), count it as damage for the
+ /// blacklist, and learn the hit against its own monster type.
+ ///
+ private void CreditHitToOther(int victimId, string victim, int amount, bool crit)
+ {
+ uint wcid = 0;
+ if (victimId != 0)
+ {
+ if (_host.HasGetObjectWcid) _host.TryGetObjectWcid(unchecked((uint)victimId), out wcid);
+ double maxHp = ResolveMaxHpFor(victimId, wcid, victim);
+ _worldFilter.ApplyDamageEstimate(victimId, maxHp > 0 ? amount / maxHp : 0.0);
+ ReportDamageOnTarget(victimId);
+ }
+ if (wcid == 0) wcid = WcidForName(victim);
+ if (_damageStore != null && wcid != 0 && CurrentCombatMode == CombatMode.Magic)
+ _damageStore.RecordHit(_lastCastWeaponId, wcid, victim, _lastCastElement, _lastCastTier, amount, crit);
+ }
+
+ /// A monster's max health from what we know: the manual override, the engine's vitals,
+ /// the shared creature profiles, the learned damage-to-kill. 0 when none says.
+ private double ResolveMaxHpFor(int id, uint wcid, string name)
+ {
+ if (_damageStore != null && wcid != 0)
+ {
+ double manual = _damageStore.GetManualHp(wcid);
+ if (manual > 0) return manual;
+ }
+ if (_host.HasGetTargetVitals
+ && _host.TryGetTargetVitals(unchecked((uint)id), out _, out uint maxHealth, out _, out _, out _, out _)
+ && maxHealth > 0)
+ return maxHealth;
+ if (_creatureStore != null && !string.IsNullOrEmpty(name))
+ {
+ CreatureProfile? prof = null;
+ bool found = wcid != 0 ? _creatureStore.TryGet(name, wcid, out prof) : _creatureStore.TryGetByName(name, out prof);
+ if (found && prof != null && prof.MaxHealth > 0) return prof.MaxHealth;
+ }
+ if (_damageStore != null && wcid != 0)
+ {
+ double hp = _damageStore.GetLearnedHp(wcid);
+ if (hp > 0) return hp;
+ }
+ return 0;
+ }
+
+ ///
+ /// The monster a kill notice is about, among those we hit in the last few seconds (other than
+ /// ): the longest name the message contains, then the most hurt,
+ /// then the most recently hit. 0 when none fits.
+ ///
+ private int FindRecentlyHitVictim(string deathMessage, int exclude, DateTime now)
+ {
+ int best = 0, bestLen = 0;
+ float bestHp = 2f;
+ DateTime bestAt = DateTime.MinValue;
+ foreach (var kv in _hitAt)
+ {
+ if (kv.Key == exclude || (now - kv.Value).TotalMilliseconds > KillMatchRecentHitMs) continue;
+ if (_recentlyKilled.ContainsKey(kv.Key)) continue;
+ string n = _worldFilter[kv.Key]?.Name ?? "";
+ if (n.Length == 0 || deathMessage.IndexOf(n, StringComparison.OrdinalIgnoreCase) < 0) continue;
+ float hp = _worldFilter.GetHealthRatio(kv.Key);
+ if (hp < 0f) hp = 1f;
+ bool better = n.Length > bestLen
+ || (n.Length == bestLen && (hp < bestHp || (hp == bestHp && kv.Value > bestAt)));
+ if (!better) continue;
+ best = kv.Key; bestLen = n.Length; bestHp = hp; bestAt = kv.Value;
+ }
+ return best;
+ }
+
///
/// Extract our outgoing damage amount from a combat-log line. Two wordings reach us:
/// • Retail combat log: "You blast X for 153 points of fire damage!"
@@ -1241,56 +1389,13 @@ public partial class CombatManager : IDisposable
/// (ACEmulator's SpellProjectile.DamageTarget emits "for {amount} points with
/// {Spell.Name}" — NOT "points of damage" — so the old retail-only
/// parser matched nothing on ACE and the Crit/NonCrit columns stayed empty.)
- /// Returns false for incoming ("... you for N points ...") and non-damage
- /// "points of <vital>" lines (heals / mana / stamina drains). Allocation-free (hot path).
+ /// Returns false for incoming lines ("... you for N points ...", "... your lower leg for ..."):
+ /// the sentence must start with "You" after any "Critical hit!"-style prefix. Also false for
+ /// non-damage "points of <vital>" lines (heals / mana / stamina drains).
+ /// Shared with RynthTracker (Plugins/Shared/CombatText.cs), which also reads the victim's name.
///
internal static bool TryParseOutgoingDamage(string text, out int amount)
- {
- amount = 0;
-
- // Anchor on the word "points" (shared by both wordings). The number is the run
- // of digits immediately before it; the word right AFTER it disambiguates:
- // "points with ..." → ACE damage cast (only the projectile msg uses this)
- // "points of ... damage" → retail damage
- // "points of mana/stamina/..." → vital drain/heal (no "damage") → reject
- int pts = text.IndexOf("points", StringComparison.OrdinalIgnoreCase);
- if (pts < 0) return false;
-
- int w = pts + 6; // first char after "points"
- while (w < text.Length && text[w] == ' ') w++;
- bool nextWith = WordAt(text, w, "with");
- bool nextOf = WordAt(text, w, "of");
- bool isDamage = nextWith
- || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0);
- if (!isDamage) return false;
-
- // Incoming (we got hit) lines read "... you for N points ..." — not our damage.
- if (text.IndexOf("you for", StringComparison.OrdinalIgnoreCase) >= 0) return false;
-
- int i = pts - 1;
- while (i >= 0 && text[i] == ' ') i--;
- long val = 0, mult = 1; bool any = false;
- while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ','))
- {
- if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; }
- i--;
- }
- if (!any || val <= 0 || val > 1_000_000) return false;
- amount = (int)val;
- return true;
- }
-
- /// Case-insensitive whole-word match of (passed lowercase)
- /// at in , bounded by end-of-string or a
- /// non-letter. Allocation-free.
- private static bool WordAt(string text, int pos, string word)
- {
- if (pos < 0 || pos + word.Length > text.Length) return false;
- for (int k = 0; k < word.Length; k++)
- if (char.ToLowerInvariant(text[pos + k]) != word[k]) return false;
- int end = pos + word.Length;
- return end >= text.Length || !char.IsLetter(text[end]);
- }
+ => CombatText.TryParseOutgoingHit(text, out _, out amount);
public void HandleChatForDebuffs(string text)
{
@@ -1882,12 +1987,26 @@ public partial class CombatManager : IDisposable
// a late death notice killed a neighbour. Dropping it also hid it from the scan for
// 4 s, and with no other mob in range the bot went to peace mid-fight.
bool noticeForSwappedMob = pendingKillId != 0 && pendingKillId != tid;
- bool curAttacked = _fightTargetId != tid || _fightCastCount > 0 || _pendingOffensiveTargetId == tid;
- if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked))
+ // A damage line naming the target (ResolveHitVictim stamped it) is an attack too.
+ bool curAttacked = _fightTargetId != tid || _fightCastCount > 0 || _pendingOffensiveTargetId == tid
+ || (tid != 0 && _hitAt.ContainsKey(tid));
+ // A ring, wall or chain spell kills neighbours too. The server's health for the fight
+ // target lands before its kill notice (ACE sends the 0 with the lethal hit), so a fight
+ // target the server still says is alive didn't die: the notice is a same-named
+ // neighbour's we hit in the last few seconds.
+ int otherVictim = (!curMatches || noticeForSwappedMob) ? 0 : FindRecentlyHitVictim(deathMessage, tid, nowKill);
+ float curHp = tid != 0 ? _worldFilter.GetHealthRatio(tid) : -1f;
+ bool curServerAlive = curHp > 0f && !_worldFilter.IsHealthEstimated(tid);
+ bool noticeForNeighbour = otherVictim != 0 && curServerAlive;
+ if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked || noticeForNeighbour))
{
_host.Log($"[RynthAi] Kill notice names 0x{tid:X8} '{curName}' but " +
- (noticeForSwappedMob ? $"belongs to predicted kill 0x{pendingKillId:X8}" : "it hasn't been attacked yet") +
+ (noticeForSwappedMob ? $"belongs to predicted kill 0x{pendingKillId:X8}"
+ : noticeForNeighbour ? $"it is alive ({curHp:0.00}); a neighbour we hit died (0x{otherVictim:X8})"
+ : "it hasn't been attacked yet") +
" — keeping the target");
+ if (noticeForNeighbour)
+ _recentlyKilled[otherVictim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS);
}
else if (tid != 0 && curMatches)
{
@@ -1895,8 +2014,27 @@ public partial class CombatManager : IDisposable
ForgetScanned(tid);
DropTarget("killed (KillerNotification)");
}
+ else if (pendingKillId == 0)
+ {
+ // Another monster died, not the fight target: one we hit with a ring, wall or chain.
+ // Keep the scan off it while its corpse forms.
+ int victim = FindRecentlyHitVictim(deathMessage, tid, nowKill);
+ if (victim != 0)
+ _recentlyKilled[victim] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS);
+ }
}
+ /// Test seam: engage as the fight target, as a target lock does.
+ internal void EngageForTest(int targetId)
+ {
+ activeTargetId = targetId;
+ _lockedTargetId = targetId;
+ BeginFight(targetId);
+ }
+
+ /// Test seam: true while the scan is kept off after a kill.
+ internal bool IsKillSuppressed(int id) => _recentlyKilled.ContainsKey(id);
+
/// Record the just-stamped _lastFight* context into the recent-fights ring,
/// keyed by the live object id (refreshed per hit, capped, TTL-pruned). Lets a kill that
/// lands after we've advanced past the dying mob still be credited by name (tier 4).
@@ -2443,7 +2581,12 @@ public partial class CombatManager : IDisposable
// wield, attack or cast while the server is still answering the last action (a kit, a corpse
// use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk
// and fails a cast in progress; that interleaving began every stuck-use stall on record.
- if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _))
+ // Melee/missile attack repeats skip the animation gate (gestureGate false): the server swings
+ // on its own timers, a swing can't land inside a use's server turn because the use above holds
+ // every attack until it is answered, and waiting for each swing animation would cost DPS. A
+ // stance change still waits (ChangeCombatModeFor), and so does everything in peace/magic.
+ bool attackRepeat = CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile;
+ if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, gestureGate: !attackRepeat))
{
LastCombatSkipReason = "server-answering"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Busy;
@@ -4698,6 +4841,7 @@ public partial class CombatManager : IDisposable
else
_host.MeleeAttack(targetId, acHeight, power);
+ RynthCore.Plugin.Shared.ActionPacer.NoteAttackSent(); // nothing else starts before this swing plays
_serverAttackTargetId = activeTargetId;
LastCombatSkipReason = "attack"; // D4 record-only: physical attack sent this tick
return true;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
index e0fb827..115b6d3 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
@@ -43,6 +43,12 @@ public class WorldObjectCache
private readonly HashSet _landscape = new(); // has physics position
private readonly HashSet _inventory = new(); // no physics position
private readonly Dictionary _healthRatios = new(); // last known health ratio per object (0-1)
+ // Ids whose ratio is an estimate from our own damage lines (a ring, wall or chain spell's other
+ // targets: the server sends health only for the selected target). A real health update replaces
+ // the estimate and takes the id out of this set.
+ private readonly HashSet _estimatedHealth = new();
+ /// The lowest an estimate goes: 0 means dead to every reader, and only the server says that.
+ internal const float EstimatedHealthFloor = 0.01f;
// OnCreateObject IDs pending classification
private readonly Queue _pending = new();
@@ -199,6 +205,7 @@ public class WorldObjectCache
_creatures.Remove(sid);
_landscape.Remove(sid);
_healthRatios.Remove(sid);
+ _estimatedHealth.Remove(sid);
_classifyRetry.Remove(id);
_slowRetry.Remove(id);
_reclassifySkipState.Remove(id);
@@ -234,6 +241,37 @@ public class WorldObjectCache
return _healthRatios.TryGetValue(id, out float v) ? v : -1f;
}
+ ///
+ /// Lowers a creature's health by our own hit when the server sends it no health of its own: the
+ /// other targets of a ring, wall or chain spell (ACE pushes health only for the selected target).
+ /// is damage / max health, or 0 when the max is unknown, which only
+ /// marks the creature as hurt (0.99). Never goes to 0 (dead is the server's call: the kill
+ /// notice, a health update or the corpse) and never raises a known value. A real health update
+ /// overwrites the estimate.
+ ///
+ public void ApplyDamageEstimate(int id, double fraction)
+ {
+ lock (_gate)
+ {
+ if (_playerId != 0 && unchecked((uint)id) == _playerId) return;
+ float cur = _healthRatios.TryGetValue(id, out float v) ? v : 1f;
+ if (cur <= 0f) return;
+ float next = fraction > 0
+ ? (float)Math.Max(EstimatedHealthFloor, cur - fraction)
+ : Math.Min(cur, 0.99f);
+ if (next >= cur && _healthRatios.ContainsKey(id)) return;
+ _healthRatios[id] = next;
+ _estimatedHealth.Add(id);
+ }
+ }
+
+ /// True when 's health ratio is our estimate rather than the server's.
+ public bool IsHealthEstimated(int id)
+ {
+ lock (_gate)
+ return _estimatedHealth.Contains(id);
+ }
+
public void OnUpdateHealth(uint id, float healthRatio)
{
lock (_gate)
@@ -243,6 +281,7 @@ public class WorldObjectCache
int sid = (int)id;
_healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f);
+ _estimatedHealth.Remove(sid); // the server's number replaces any estimate
if (!_creatures.Add(sid))
return; // creature already known — ratio updated above, nothing more to do
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
index efab96a..9678880 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
@@ -97,6 +97,8 @@ public sealed partial class RynthAiPlugin
private bool _currentLootItemMovePending;
private bool _corpseAutorunActive;
private int _currentLootItemMoveAttempts;
+ private long _currentLootItemStillSince;
+ private long _pickupAnimSince;
private string _currentLootItemActionLabel = string.Empty;
private string _currentLootItemName = string.Empty;
private bool _currentLootItemIsSalvage;
@@ -400,6 +402,11 @@ public sealed partial class RynthAiPlugin
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
_lootWedgeAnnounced = false;
+ if (_useCheckJumpAt != 0)
+ {
+ Log($"[RynthAi] Use check: 0x{objectId:X8} opened {CorpseNowMs - _useCheckJumpAt} ms after the use check's jump - the jump cleared the server's stuck turn.");
+ _useCheckJumpAt = 0;
+ }
ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs);
if (switchedTarget)
LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}.");
@@ -1376,6 +1383,11 @@ public sealed partial class RynthAiPlugin
return;
}
+ // The last pickup's bend-down still plays: the engine holds a move sent now until
+ // it ends, so wait and send it then.
+ if (PickupAnimating(CorpseNowMs))
+ return;
+
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
_currentLootItemId = firstMatchId;
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId));
@@ -1448,6 +1460,28 @@ public sealed partial class RynthAiPlugin
}
}
+ /// Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s).
+ internal const long PickupAnimMaxMs = 3000;
+
+ ///
+ /// The character still has motions queued (the engine's cast gate, GetCastBusyState):
+ /// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a
+ /// stuck queue can't stop looting, and on an engine without the gate.
+ ///
+ private bool PickupAnimating(long now)
+ {
+ bool busy;
+ try { busy = Host.HasGetCastBusyState && Host.GetCastBusyState() != 0; } catch { busy = false; }
+ if (!busy)
+ {
+ _pickupAnimSince = 0;
+ return false;
+ }
+ if (_pickupAnimSince == 0)
+ _pickupAnimSince = now;
+ return now - _pickupAnimSince < PickupAnimMaxMs;
+ }
+
private void TickPendingCorpsePickup(LegacyUiSettings settings)
{
if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0)
@@ -1475,9 +1509,20 @@ public sealed partial class RynthAiPlugin
return;
}
- // Item still on corpse — wait before retrying the UseObject.
+ // Item still on corpse — wait before retrying the UseObject. The window counts from
+ // when the character is still: while a pickup animation plays the engine holds the
+ // move, and a retry timed from the send gave up on items whose move had not gone
+ // out yet (2026-10-07: moves ran ~2.2 s late, 3 tries at 0.5 s skipped the item).
+ if (PickupAnimating(now))
+ {
+ _currentLootItemStillSince = 0;
+ return;
+ }
+ if (_currentLootItemStillSince == 0)
+ _currentLootItemStillSince = now;
long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs);
- if (now - _currentLootItemMoveRequestedAt < verifyWindowMs)
+ long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince);
+ if (now - windowStart < verifyWindowMs)
return;
if (_currentLootItemMoveAttempts >= 3)
@@ -2293,6 +2338,7 @@ public sealed partial class RynthAiPlugin
_currentLootItemMovePending = false;
_currentLootItemMoveRequestedAt = 0;
_currentLootItemMoveAttempts = 0;
+ _currentLootItemStillSince = 0;
_currentLootItemActionLabel = string.Empty;
_currentLootItemName = string.Empty;
_currentLootItemIsSalvage = false;
@@ -2394,6 +2440,16 @@ public sealed partial class RynthAiPlugin
ApplyUseRefusalVerdict(verdict, now);
return false;
}
+
+ // The back-off is over and this is the probe: jump first (clears the server's stuck
+ // animation queue, see UseRefusalWatch), send the probe after the pause.
+ if (_useRefusals.TakeProbeJump(now) && TryUseCheckJump(now, "before the probe"))
+ {
+ _lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
+ _lastCorpseOpenAttemptAt = 0;
+ _corpseTargetSince = now;
+ return false;
+ }
}
_lastOpenAttemptCorpseId = corpseId;
@@ -2429,17 +2485,20 @@ public sealed partial class RynthAiPlugin
case UseRefusalWatch.Verdict.CleanStopAndRetry:
{
FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened");
- Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try.");
+ Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a jump, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try.");
Host.SetAutoRunBy("Loot/UseCheck", false);
if (Host.HasStopCompletely)
Host.StopCompletelyBy("Loot/UseCheck");
_corpseAutorunActive = false;
_corpseApproachTurnsActive = false;
- // Face the corpse for the retry. Since 2026-10-04 the bot leaves the turn to the
- // server; if the server can't turn the character any more, a corpse already in
- // front may still open (mid-stall, 06:28:19, a use by hand with the macro off
+ // The jump is the fix (see UseRefusalWatch): it empties the server's animation
+ // queues and cancels the stuck turn; the retry then gets a fresh server turn.
+ bool jumped = TryUseCheckJump(now, "for the retry");
+ // Without a jump: face the corpse for the retry. Since 2026-10-04 the bot leaves the
+ // turn to the server; if the server can't turn the character any more, a corpse already
+ // in front may still open (mid-stall, 06:28:19, a use by hand with the macro off
// opened one - the only open in those 13 minutes; whether it was faced isn't logged).
- if (_targetCorpseId != 0 && Host.HasTurnToHeading
+ if (!jumped && _targetCorpseId != 0 && Host.HasTurnToHeading
&& TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _)
&& faceErr > 2.0)
{
@@ -2465,7 +2524,8 @@ public sealed partial class RynthAiPlugin
case UseRefusalWatch.Verdict.Stuck:
{
FlightRecorderSignal.Dump(Host, "use check: server refuses every use");
- Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again.");
+ Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}.");
+ _useCheckJumpAt = 0;
if (!_useStuckAnnounced)
{
_useStuckAnnounced = true;
@@ -2475,7 +2535,8 @@ public sealed partial class RynthAiPlugin
break;
}
case UseRefusalWatch.Verdict.StillStuck:
- Log($"[RynthAi] Use check: still refused - next try in {_useRefusals.BackoffMs / 60_000} min.");
+ Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 60_000} min.");
+ _useCheckJumpAt = 0;
ResetCorpseTarget();
break;
case UseRefusalWatch.Verdict.Recovered:
@@ -2487,6 +2548,35 @@ public sealed partial class RynthAiPlugin
}
}
+ /// When the use check last jumped (0 = not since the last open).
+ private long _useCheckJumpAt;
+
+ ///
+ /// One jump in place for the use check. On ACE the jump (0xF61B, the keyboard path: TapJump)
+ /// is the only in-world action that empties the server's animation queues for the character
+ /// (Player.HandleActionJump: RemoveLinkAnimations drains MotionTableManager.PendingAnimations,
+ /// MotionInterp.PendingMotions.Clear(), IsAnimating = false) and it cancels the stuck walk/turn
+ /// (GameActionJump -> StopExistingMoveToChains2). JumpNonAutonomous (0xF7C9) is not used: ACE
+ /// has no handler for it. Not while the pacer has an action out (a jump in Magic stance fails a
+ /// cast on the server).
+ ///
+ private bool TryUseCheckJump(long now, string why)
+ {
+ if (!Host.HasTapJump)
+ return false;
+ if (ActionPacer.Outstanding(Host, out var pending) && pending != null)
+ {
+ Log($"[RynthAi] Use check: no jump {why} - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)}.");
+ return false;
+ }
+ Host.SetAutoRunBy("Loot/UseCheck", false);
+ bool ok = Host.TapJump();
+ if (ok)
+ _useCheckJumpAt = now;
+ Log($"[RynthAi] Use check: jump {why} (clears the server's stuck animation queue; a relog was the only other fix) ok={ok}.");
+ return ok;
+ }
+
private string RefusedList() =>
string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}"));
@@ -2511,6 +2601,7 @@ public sealed partial class RynthAiPlugin
private void ResetUseRefusalState()
{
_useRefusals.Reset();
+ _useCheckJumpAt = 0;
_useStuckAnnounced = false;
_lootWedgeAnnounced = false;
_consecutiveLootTimeouts = 0;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
index e5dd363..0da3631 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
@@ -396,6 +396,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100);
ImGui.SetNextItemWidth(120);
+ ImGui.SliderInt("Re-stam To", ref _settings.RestamTo, 0, 100);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before.");
+ ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100);
ImGui.Spacing();
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index 5f71cfd..f023612 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -965,6 +965,7 @@ internal sealed class LegacyDashboardRenderer
StopLootingWhenPackFull = s.StopLootingWhenPackFull,
StopMacroWhenPackFull = s.StopMacroWhenPackFull,
RestamAt = s.RestamAt,
+ RestamTo = s.RestamTo,
GetManaAt = s.GetManaAt,
TopOffHP = s.TopOffHP,
TopOffStam = s.TopOffStam,
@@ -1172,6 +1173,7 @@ internal sealed class LegacyDashboardRenderer
s.StopLootingWhenPackFull = p.StopLootingWhenPackFull;
s.StopMacroWhenPackFull = p.StopMacroWhenPackFull;
s.RestamAt = p.RestamAt;
+ s.RestamTo = p.RestamTo ?? 0;
s.GetManaAt = p.GetManaAt;
s.TopOffHP = p.TopOffHP;
s.TopOffStam = p.TopOffStam;
@@ -1630,6 +1632,7 @@ internal sealed class LegacyDashboardRenderer
dst.StopLootingWhenPackFull = tmp.StopLootingWhenPackFull;
dst.StopMacroWhenPackFull = tmp.StopMacroWhenPackFull;
dst.RestamAt = tmp.RestamAt;
+ dst.RestamTo = tmp.RestamTo;
dst.GetManaAt = tmp.GetManaAt;
dst.TopOffHP = tmp.TopOffHP;
dst.TopOffStam = tmp.TopOffStam;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index bc0cf78..110d5f1 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -131,6 +131,11 @@ public sealed class LegacyUiSettings
public bool StopLootingWhenPackFull = true;
public bool StopMacroWhenPackFull = false;
public int RestamAt = 30;
+ ///
+ /// In combat, once stamina drops under Re-stam At, keep recharging until it reaches this %
+ /// (one Revitalize often doesn't get far). 0, or not above Re-stam At = one recharge, as before.
+ ///
+ public int RestamTo = 0;
public int GetManaAt = 40;
public int TopOffHP = 95;
public int TopOffStam = 95;
@@ -796,6 +801,7 @@ public sealed class SettingsBridgePayload
public bool StopLootingWhenPackFull { get; set; }
public bool StopMacroWhenPackFull { get; set; }
public int RestamAt { get; set; }
+ public int? RestamTo { get; set; }
public int GetManaAt { get; set; }
public int TopOffHP { get; set; }
public int TopOffStam { get; set; }
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
index 6614aa9..1f84f44 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
@@ -27,6 +27,16 @@
// A UseDone with an error (0x1D "too busy", ...) says nothing either way, and
// an open the server never answers is left to the corpse timeout as before.
// No game calls here: the controller acts on the verdicts.
+//
+// The jump (2026-10-06 afternoon): the stuck state is the server's animation
+// bookkeeping for the character (ACE: MotionInterp.PendingMotions/IsAnimating
+// and the MotionTableManager queue never drain, so the server's turn to the
+// corpse never starts and the use's callback never runs). Besides leaving the
+// world, the only thing on ACE that empties those queues is the player's jump
+// (Player.HandleActionJump: RemoveLinkAnimations drains the motion table queue,
+// PendingMotions.Clear, IsAnimating = false; the jump also cancels the pending
+// walk/turn). So the controller jumps at the clean stop, and once more before
+// each probe after a back-off (TakeProbeJump).
// ============================================================================
using System;
@@ -73,6 +83,7 @@ internal sealed class UseRefusalWatch
public int LastRefusedCorpse { get; private set; }
private readonly HashSet _refused = new();
+ private bool _probeJumpTaken;
private bool _pending;
private int _pendingId;
private long _sentAt;
@@ -82,6 +93,16 @@ internal sealed class UseRefusalWatch
/// While Stuck: no opens until the back-off ends (then one probe).
public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil;
+ /// The back-off is over and the probe is next: true once per back-off, meaning
+ /// "jump first, then send the probe after the pause".
+ public bool TakeProbeJump(long now)
+ {
+ if (State != Phase.Stuck || now < BackoffUntil || _probeJumpTaken)
+ return false;
+ _probeJumpTaken = true;
+ return true;
+ }
+
/// Call before sending the next open: the previous one, answered with nothing opened,
/// counts as refused now (the next attempt came before its grace ran out). A verdict other than
/// None means: act on it and don't send this open.
@@ -154,6 +175,7 @@ internal sealed class UseRefusalWatch
BackoffMs = 0;
LastRefusedCorpse = 0;
_refused.Clear();
+ _probeJumpTaken = false;
_pending = false;
_answeredAt = 0;
}
@@ -178,11 +200,13 @@ internal sealed class UseRefusalWatch
State = Phase.Stuck;
BackoffMs = FirstBackoffMs;
BackoffUntil = now + BackoffMs;
+ _probeJumpTaken = false;
return Verdict.Stuck;
default: // Stuck: a probe after the back-off
BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2));
BackoffUntil = now + BackoffMs;
+ _probeJumpTaken = false;
return Verdict.StillStuck;
}
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
index a1ca0f3..e6157a2 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
@@ -3340,6 +3340,7 @@ internal sealed class ExpressionEngine
["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }),
["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }),
["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }),
+ ["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }),
["GetManaAt"] = (() => I(s.GetManaAt), v => { if (int.TryParse(v, out int i)) s.GetManaAt = i; }),
["TopOffHP"] = (() => I(s.TopOffHP), v => { if (int.TryParse(v, out int i)) s.TopOffHP = i; }),
["TopOffStam"] = (() => I(s.TopOffStam), v => { if (int.TryParse(v, out int i)) s.TopOffStam = i; }),
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
index daf3f27..fd7c8bf 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
@@ -51,7 +51,9 @@ public sealed partial class RynthAiPlugin
get
{
int busy = _busyCount;
- if (ActionPacer.Enabled && ActionPacer.Current(Host) != null) busy++;
+ if (ActionPacer.Enabled
+ && (ActionPacer.Current(Host) != null || ActionPacer.GestureHolds(Host, "Items", HealNeed.None, out _)))
+ busy++; // an unanswered server action, or the character still animating (a pack move of a wielded item, a stone, a summon would start on top)
return busy;
}
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
index ad0768c..7b556ad 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
@@ -871,7 +871,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100),
- ["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
+ ["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100),
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj
index e3740c0..c805add 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj
@@ -35,6 +35,8 @@
+
+
diff --git a/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs b/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs
new file mode 100644
index 0000000..0e0c496
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthTracker/KillCounter.cs
@@ -0,0 +1,188 @@
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Plugin.RynthTracker;
+
+///
+/// Counts your kills, including the extra monsters a ring, wall, blast or chain spell kills.
+///
+/// Two ways a kill is counted:
+/// 1. The server's killer notification (it goes only to whoever landed the killing blow).
+/// One notification is one kill, as before.
+/// 2. A corpse ("Corpse of X") with no notification for it, when you hit an X with a
+/// multi-target spell in the last . Some servers send no
+/// notification for the extra monsters a spell kills (chain spells on Conquest), and on
+/// ACE a killing blow sends no damage line either, so the corpse is the one sign left.
+///
+/// "Multi-target" is read from the combat log: one cast's damage lines (and kill notices)
+/// arrive together, so lines no more than apart are one volley, and
+/// a volley with two or more of them hit several monsters. Each name hit in such a volley may
+/// be counted from its corpse as many times as that volley hit it (tokens). A single-target
+/// hit never makes a corpse count: a monster you hit once that someone else then finished
+/// isn't yours, the same as before.
+///
+/// A notification is matched to its corpse later (the corpse forms after the death animation),
+/// so a kill counted by its notification isn't counted again by its corpse.
+///
+/// Pure logic, no host: the plugin passes every event with its time, so tests can drive it.
+///
+internal sealed class KillCounter
+{
+ /// Damage lines and kill notices this close together belong to one cast.
+ public const double VolleyGapMs = 800;
+ /// How long after a multi-target hit a monster's corpse still counts as your kill.
+ public const double TokenLifeMs = 15000;
+ /// How long a kill notice waits for its corpse.
+ public const double NoticeLifeMs = 20000;
+ /// How long a single-target hit is remembered (only to explain an uncounted corpse in the log).
+ public const double HitMemoryMs = 15000;
+
+ public int Kills { get; private set; }
+ public int NoticeKills { get; private set; }
+ public int CorpseKills { get; private set; }
+
+ private readonly List<(string Message, DateTime At)> _notices = new();
+ private readonly Dictionary _tokens = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary _lastHit = new(StringComparer.OrdinalIgnoreCase);
+
+ // The volley in progress: hits per name, and how many members (lines + notices) it has.
+ private readonly Dictionary _volley = new(StringComparer.OrdinalIgnoreCase);
+ private int _volleyMembers;
+ private DateTime _volleyLast = DateTime.MinValue;
+
+ /// The server's killer notification: always one kill.
+ public void OnKillNotice(string? message, DateTime now)
+ {
+ Kills++;
+ NoticeKills++;
+ Prune(now);
+ _notices.Add((message ?? "", now));
+ JoinVolley(now);
+ // A notice is one of the volley's monsters too (the killing blow sends no damage line),
+ // under the name of a monster we hit that the message contains.
+ string? name = LongestRecentHitIn(message ?? "", now);
+ if (name != null) _volley[name] = _volley.TryGetValue(name, out int n) ? n + 1 : 1;
+ GrantTokens(now);
+ }
+
+ private string? LongestRecentHitIn(string message, DateTime now)
+ {
+ string? best = null;
+ foreach (var kv in _lastHit)
+ {
+ if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) continue;
+ if (message.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) < 0) continue;
+ if (best == null || kv.Key.Length > best.Length) best = kv.Key;
+ }
+ return best;
+ }
+
+ /// One of your damage lines, naming the monster it hurt.
+ public void OnHit(string victim, DateTime now)
+ {
+ if (string.IsNullOrEmpty(victim)) return;
+ JoinVolley(now);
+ _volley[victim] = _volley.TryGetValue(victim, out int n) ? n + 1 : 1;
+ _lastHit[victim] = now;
+ GrantTokens(now);
+ }
+
+ /// What a corpse turned out to be.
+ public enum CorpseResult
+ {
+ /// Its kill notice already counted it.
+ Notified,
+ /// No notice, but you hit it with a multi-target spell: counted now.
+ Counted,
+ /// You hit a monster of that name, but only single-target: not counted (someone else's kill?).
+ HitNotCounted,
+ /// Nothing of yours.
+ NotOurs,
+ }
+
+ /// A corpse appeared; is the X of "Corpse of X".
+ public CorpseResult OnCorpse(string monsterName, DateTime now)
+ {
+ if (string.IsNullOrEmpty(monsterName)) return CorpseResult.NotOurs;
+ Prune(now);
+
+ // The oldest notice that names this monster.
+ int match = -1;
+ for (int i = 0; i < _notices.Count; i++)
+ if (_notices[i].Message.IndexOf(monsterName, StringComparison.OrdinalIgnoreCase) >= 0) { match = i; break; }
+ if (match >= 0)
+ {
+ _notices.RemoveAt(match);
+ // It was one of the monsters a multi-target volley hit: it no longer vouches for another.
+ if (_tokens.TryGetValue(monsterName, out var used) && used.Count > 0)
+ _tokens[monsterName] = (used.Count - 1, used.Until);
+ return CorpseResult.Notified;
+ }
+
+ if (_tokens.TryGetValue(monsterName, out var t) && t.Count > 0 && t.Until >= now)
+ {
+ _tokens[monsterName] = (t.Count - 1, t.Until);
+ Kills++;
+ CorpseKills++;
+ return CorpseResult.Counted;
+ }
+
+ return _lastHit.TryGetValue(monsterName, out DateTime h) && (now - h).TotalMilliseconds <= HitMemoryMs
+ ? CorpseResult.HitNotCounted
+ : CorpseResult.NotOurs;
+ }
+
+ public void Reset()
+ {
+ Kills = NoticeKills = CorpseKills = 0;
+ _notices.Clear();
+ _tokens.Clear();
+ _lastHit.Clear();
+ _volley.Clear();
+ _volleyMembers = 0;
+ _volleyLast = DateTime.MinValue;
+ }
+
+ private void JoinVolley(DateTime now)
+ {
+ if ((now - _volleyLast).TotalMilliseconds > VolleyGapMs)
+ {
+ _volley.Clear();
+ _volleyMembers = 0;
+ }
+ _volleyMembers++;
+ _volleyLast = now;
+ }
+
+ // A volley that hit several monsters makes each name it hit countable from its corpse, as
+ // many times as the volley hit that name. Max, not sum: the next cast hits the same monsters
+ // again, and two casts at two monsters are still two monsters.
+ private void GrantTokens(DateTime now)
+ {
+ if (_volleyMembers < 2) return;
+ DateTime until = now.AddMilliseconds(TokenLifeMs);
+ foreach (var kv in _volley)
+ {
+ int have = _tokens.TryGetValue(kv.Key, out var t) && t.Until >= now ? t.Count : 0;
+ _tokens[kv.Key] = (Math.Max(have, kv.Value), until);
+ }
+ }
+
+ private readonly List _pruneScratch = new();
+ private void Prune(DateTime now)
+ {
+ _notices.RemoveAll(n => (now - n.At).TotalMilliseconds > NoticeLifeMs);
+ if (_tokens.Count > 32)
+ {
+ _pruneScratch.Clear();
+ foreach (var kv in _tokens) if (kv.Value.Until < now) _pruneScratch.Add(kv.Key);
+ foreach (string k in _pruneScratch) _tokens.Remove(k);
+ }
+ if (_lastHit.Count > 64)
+ {
+ _pruneScratch.Clear();
+ foreach (var kv in _lastHit) if ((now - kv.Value).TotalMilliseconds > HitMemoryMs) _pruneScratch.Add(kv.Key);
+ foreach (string k in _pruneScratch) _lastHit.Remove(k);
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs
index 62a6e8e..98a8b7a 100644
--- a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs
+++ b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs
@@ -40,6 +40,10 @@ public static unsafe class PluginExports
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
=> Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
+ // Corpses (0.3.0): a kill a ring, wall or chain spell made without a kill notice is found by its corpse.
+ [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
+ public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
+
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj
index 87e9c13..4fc8d89 100644
--- a/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj
+++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthCore.Plugin.RynthTracker.csproj
@@ -21,6 +21,11 @@
Kills, experience and luminance per hour for each session.
+
+
+
+
+
diff --git a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs
index b1bba92..7ef7775 100644
--- a/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
+using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthTracker;
@@ -8,7 +9,7 @@ namespace RynthCore.Plugin.RynthTracker;
public sealed class RynthTrackerPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthTracker");
- internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.1");
+ internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
private uint _playerId;
private bool _loginComplete;
@@ -24,12 +25,28 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
// blow: a fellow's kill, a summon's kill or a mob someone else finished never counts,
// and neither does the XP they bring (damage share, fellowship share, quests). That XP
// still counts toward the totals and XP/hour.
+ //
+ // 0.3.0: plus the extra monsters a ring, wall, blast or chain spell kills when the
+ // server sends no notification for them (chain spells on Conquest): their corpse counts
+ // when you hit that monster with a multi-target spell just before (KillCounter.cs).
private long _killXp;
private int _xpKills; // kills that closed their window (the per-kill divisor)
private int _openKills; // kills whose window is still open
private DateTime _killWindowUntil; // XP rises seen until then belong to those kills
private const double KillWindowSec = 2.5;
+ // Kill notices, our damage lines and corpses, for the kills a notice doesn't cover.
+ private readonly KillCounter _killCounter = new();
+ // Corpses waiting for their name (the client may not have it on the create tick).
+ private readonly List<(uint Id, DateTime Seen)> _pendingCorpses = new();
+ private const double CorpseNameWaitSec = 3.0;
+ private const int MaxPendingCorpses = 256;
+ // XP that landed outside any kill window: a kill found by its corpse (seconds after the
+ // death animation) takes the XP of the few seconds before it.
+ private readonly List<(DateTime At, long Xp)> _unattributedXp = new();
+ private const double CorpseXpLookbackSec = 8.0;
+ private int _corpseLogCount;
+
private int _tickCounter;
// Everything comes from the player's own properties, never from chat text:
@@ -126,6 +143,76 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
_killsTotal++;
_openKills++;
_killWindowUntil = DateTime.UtcNow.AddSeconds(KillWindowSec);
+ _killCounter.OnKillNotice(deathMessage, DateTime.UtcNow);
+ }
+
+ // Our damage lines name each monster a spell hurt (one line per monster for rings, walls,
+ // blasts and chain spells): that is how a multi-target hit is recognised.
+ public override void OnChatWindowText(string? text, int chatType, ref int eat)
+ {
+ if (!_loginComplete) return;
+ if (CombatText.TryParseOutgoingHit(text, out string victim, out _))
+ _killCounter.OnHit(victim, DateTime.UtcNow);
+ }
+
+ // Corpses are read on the tick (their name may not be readable yet on the create).
+ public override void OnCreateObject(uint objectId)
+ {
+ if (!_loginComplete || objectId == 0) return;
+ if (_pendingCorpses.Count >= MaxPendingCorpses) _pendingCorpses.RemoveAt(0);
+ _pendingCorpses.Add((objectId, DateTime.UtcNow));
+ }
+
+ public override void OnDeleteObject(uint objectId)
+ {
+ for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
+ if (_pendingCorpses[i].Id == objectId) _pendingCorpses.RemoveAt(i);
+ }
+
+ /// Reads the names of newly created objects; a "Corpse of X" goes to the kill counter.
+ private void CheckPendingCorpses()
+ {
+ if (_pendingCorpses.Count == 0) return;
+ if (!Host.HasGetObjectName) { _pendingCorpses.Clear(); return; }
+ DateTime now = DateTime.UtcNow;
+ for (int i = _pendingCorpses.Count - 1; i >= 0; i--)
+ {
+ var (id, seen) = _pendingCorpses[i];
+ if (!Host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name))
+ {
+ if ((now - seen).TotalSeconds > CorpseNameWaitSec) _pendingCorpses.RemoveAt(i);
+ continue;
+ }
+ _pendingCorpses.RemoveAt(i);
+ string? monster = CombatText.CorpseOwnerName(name);
+ if (monster == null) continue;
+ var result = _killCounter.OnCorpse(monster, now);
+ if (result == KillCounter.CorpseResult.Counted)
+ CountCorpseKill(now);
+ if ((result == KillCounter.CorpseResult.Counted || result == KillCounter.CorpseResult.HitNotCounted)
+ && _corpseLogCount < 40)
+ {
+ _corpseLogCount++;
+ Host.Log(result == KillCounter.CorpseResult.Counted
+ ? $"[RynthTracker] Kill counted from its corpse (no kill notice): '{name}' 0x{id:X8}, hit by a multi-target spell. Kills {_killsTotal}."
+ : $"[RynthTracker] Not counted: '{name}' 0x{id:X8} - you hit it, single-target, and got no kill notice (someone else's kill?).");
+ }
+ }
+ }
+
+ /// A kill found by its corpse: one more kill, and the XP of the seconds before it.
+ private void CountCorpseKill(DateTime now)
+ {
+ _killsTotal++;
+ bool inKillWindow = _openKills > 0 && now <= _killWindowUntil;
+ if (inKillWindow) _openKills++; // closes with the window, its XP already in it
+ else _xpKills++;
+ for (int i = _unattributedXp.Count - 1; i >= 0; i--)
+ {
+ if ((now - _unattributedXp[i].At).TotalSeconds > CorpseXpLookbackSec) continue;
+ _killXp += _unattributedXp[i].Xp;
+ _unattributedXp.RemoveAt(i);
+ }
}
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
@@ -148,6 +235,8 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
Host.Log("[RynthTracker] Session reset.");
}
+ if (_loginComplete) CheckPendingCorpses();
+
if (++_tickCounter < 30) return; // rebuild every ~0.5s at 60Hz
_tickCounter = 0;
if (_loginComplete) PollExperience();
@@ -171,6 +260,12 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
long gained = _xpRise.Take(xp);
_xpTotal += gained;
if (inKillWindow) _killXp += gained;
+ else if (gained > 0)
+ {
+ DateTime now = DateTime.UtcNow;
+ _unattributedXp.RemoveAll(e => (now - e.At).TotalSeconds > CorpseXpLookbackSec);
+ _unattributedXp.Add((now, gained));
+ }
// Capped only when past retail's 275 total AND kills keep bringing nothing: an
// awakened character's cap is higher (Aelrynth), so the total alone can't say.
_maxLevel = xp >= MaxLevelXp && _xpKills >= 3 && _xpTotal == 0;
@@ -213,6 +308,9 @@ public sealed class RynthTrackerPlugin : RynthPluginBase
_xpKills = 0;
_openKills = 0;
_radTotal = 0;
+ _killCounter.Reset();
+ _pendingCorpses.Clear();
+ _unattributedXp.Clear();
// The next read of each is the new baseline.
_xpRise.Clear(); _lumRise.Clear(); _radRise.Clear(); _bankedRise.Clear(); _drawnRise.Clear();
_snapshot = EmptySnapshot;
diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs
index 725b3e5..8fd513e 100644
--- a/Plugins/Shared/ActionPacer.cs
+++ b/Plugins/Shared/ActionPacer.cs
@@ -25,10 +25,30 @@
// * While one is outstanding, RynthAi starts no other one (MayStart; mode changes
// are refused right at ChangeCombatModeFor) and moves or turns the character
// only to stop real movement (MoveAudit asks HoldsMovement).
-// * Heals keep their priority: a heal may go ahead of a corpse/door use the server
-// hasn't answered after HealAfterWorldUseMs (EmergencyAfterWorldUseMs at
-// Emergency Heal At), and one heal may follow a cast whose result is already in
-// (the server queues one cast behind the recoil).
+// * Heals keep some priority: at Emergency Heal At a heal may go ahead of a corpse/door
+// use the server hasn't answered after EmergencyAfterWorldUseMs, and one heal may
+// follow a cast whose result is already in (the server queues one cast behind the
+// recoil). A heal under the plain Heal line waits for the use's answer (2026-10-06,
+// below: an action during the use's server turn stops that turn for good).
+// * And nothing starts while the character is still animating: the client's own motion
+// queue (CMotionInterp pending motions, the engine's cast gate: GetCastBusyState) must
+// be empty, for uses, kits, potions, casts, stance changes, wields and the item
+// managers' moves (GestureHolds). Melee/missile attack repeats are exempt (MayStart
+// with gestureGate false). Time limit GestureHoldMaxMs (GestureEmergencyMaxMs for an
+// emergency heal), logged, like Combat/CastGateWatchdog for casts.
+//
+// Why the animation gate (2026-10-06 afternoon, ops/overnight/2026-10-06-turnto-stall.md,
+// replayed through ACE's own physics code): on ACE a use in reach is finished by the
+// server's MoveToManager turning the character (TurnRight on the server's copy of the
+// motion state). Every server motion for the character (a swing, a kit, a cast gesture,
+// a stance) is applied with MotionInterp.apply_raw_movement, which rewrites the
+// interpreted TurnCommand from the raw state (none) and so stops that TurnRight; the
+// MoveToManager is never told (its FailProgressCount is counted but never acted on) and
+// stays Initialized, which keeps the player "moving or animating", so Player_Tick never
+// runs the use's callback either. The use is answered only when the next use fails it:
+// "UseDone with no error, nothing opens", the stall's signature. Starting nothing while
+// the character animates, and nothing while a use's turn is unanswered, keeps every
+// server motion out of every server turn.
//
// Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before.
// Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend.
@@ -98,9 +118,14 @@ internal static class ActionPacer
public const long ModeSettleMs = 800;
/// A wield that reads done: a short settle for the wield motion.
public const long WieldSettleMs = 150;
- /// A heal may go ahead of a door/corpse use unanswered this long (the server cancels the walk cleanly).
- public const long HealAfterWorldUseMs = 1000;
+ /// At Emergency Heal At a heal may go ahead of a door/corpse use unanswered this long. It stops
+ /// the server's walk/turn to that object (the use is then answered by the next one); a plain heal waits.
public const long EmergencyAfterWorldUseMs = 300;
+ /// The client's motion queue reading busy this long is taken as stuck: the action goes (logged).
+ /// Same backstop as Combat/CastGateWatchdog (no real gesture, stance or swing lasts this long).
+ public const long GestureHoldMaxMs = 4000;
+ /// An emergency heal waits for the character's animation at most this long.
+ public const long GestureEmergencyMaxMs = 1500;
/// A heal behind a stance change: once the client has read the new mode this long.
public const long HealAfterModeReadMs = 300;
/// An engine without UseDone: an action counts as answered after this (no real pacing).
@@ -112,6 +137,10 @@ internal static class ActionPacer
// Counters for /ra pace and the periodic summary.
private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped;
private static long _heldStarts, _heldMoves, _healsAhead;
+ 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 readonly HashSet _gestureLogged = new();
private static long _maxWaitMs;
private static string _maxWaitWhat = "";
private static readonly Dictionary _holdsByWho = new();
@@ -126,6 +155,8 @@ internal static class ActionPacer
public static long HeldStarts => _heldStarts;
public static long HeldMoves => _heldMoves;
public static long HealsAhead => _healsAhead;
+ public static long GestureHoldCount => _gestureHolds;
+ public static long GestureLimits => _gestureLimits;
/// Back to a fresh load (Init, logout, tests). Enabled is left as it is.
public static void Reset()
@@ -135,6 +166,11 @@ internal static class ActionPacer
_cur = null;
_started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0;
_heldStarts = _heldMoves = _healsAhead = 0;
+ _gestureHolds = _gestureLimits = 0;
+ _swingSentMs = 0; _swingSeenBusy = false; _swingHolds = 0; _swingLogged.Clear();
+ _gestureBusySince = 0;
+ _gestureOverride = false;
+ _gestureLogged.Clear();
_maxWaitMs = 0;
_maxWaitWhat = "";
_holdsByWho.Clear();
@@ -279,10 +315,20 @@ internal static class ActionPacer
///
/// May send a use, a cast or a mode change now? False (with why) while
- /// another action waits for the server, except the heal rules in the file header. One log
- /// line per outstanding action and subsystem.
+ /// another action waits for the server, except the heal rules in the file header, and while
+ /// the character is still animating (; skipped with
+ /// false: melee/missile attack repeats). One log line per
+ /// outstanding action (or animation) and subsystem.
///
- public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why)
+ public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why, bool gestureGate = true)
+ {
+ if (!Enabled) { why = ""; return true; }
+ if (!OutstandingAllows(host, who, heal, out why)) return false;
+ if (gestureGate && GestureHolds(host, who, heal, out why)) return false;
+ return true;
+ }
+
+ private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why)
{
why = "";
PacedAction? a = Current(host);
@@ -291,8 +337,7 @@ internal static class ActionPacer
if (heal != HealNeed.None)
{
- if (a.Kind == PacedKind.WorldUse
- && age >= (heal == HealNeed.Emergency ? EmergencyAfterWorldUseMs : HealAfterWorldUseMs))
+ if (a.Kind == PacedKind.WorldUse && heal == HealNeed.Emergency && age >= EmergencyAfterWorldUseMs)
{
lock (Gate) _healsAhead++;
Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)");
@@ -324,6 +369,117 @@ internal static class ActionPacer
return false;
}
+ ///
+ /// True (with why) while the character is still animating: the client's own motion queue
+ /// (CMotionInterp pending motions, read by the engine as GetCastBusyState) is not empty.
+ /// The client animates exactly the motions the server sends for the character, a moment
+ /// after the server applies them, so an empty queue means the server's copy is done too.
+ /// Past GestureHoldMaxMs (GestureEmergencyMaxMs for an emergency heal) the action goes,
+ /// logged once per busy spell. No opinion (false) on an engine without the gate.
+ ///
+ public static bool GestureHolds(RynthCoreHost host, string who, HealNeed heal, out string why)
+ {
+ why = "";
+ if (!Enabled) return false;
+ bool busy;
+ try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; }
+ long now = NowMs();
+ if (SwingHolds(host, who, heal, busy, now, out why)) return true;
+ string? line = null;
+ lock (Gate)
+ {
+ if (!busy)
+ {
+ if (_gestureOverride)
+ line = "[Pace] the character's animation queue reads clear again";
+ _gestureBusySince = 0;
+ _gestureOverride = false;
+ _gestureLogged.Clear();
+ }
+ else
+ {
+ if (_gestureBusySince == 0) _gestureBusySince = now;
+ long age = now - _gestureBusySince;
+ if (!_gestureOverride && age >= GestureHoldMaxMs)
+ {
+ _gestureOverride = true;
+ _gestureLimits++;
+ line = $"[Pace] {who}: the character's animation queue has read busy for {age} ms - taken as stuck, going on";
+ }
+ if (_gestureOverride)
+ {
+ busy = false;
+ }
+ else if (heal == HealNeed.Emergency && age >= GestureEmergencyMaxMs)
+ {
+ _gestureLimits++;
+ line = $"[Pace] {who}: emergency heal after {age} ms of animation - going on";
+ busy = false;
+ }
+ else
+ {
+ _gestureHolds++;
+ _holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1;
+ why = $"the character is still animating ({age} ms)";
+ if (_gestureLogged.Add(who))
+ line = $"[Pace] {who} waits: {why}";
+ }
+ }
+ }
+ if (line != null) Log(host, line);
+ return busy;
+ }
+
+ // A swing sent but not animating yet (Drakkon 2026-10-06 16:45:37): the wand's use went 110 ms
+ // after a MeleeAttack, before the swing showed in the client's motion queue, so the motion gate
+ // let it through; the switch landed on the swing the server was starting and the next cast was
+ // held open. After CombatManager sends an attack, nothing else starts until the client's motion
+ // queue has read busy and then clear (the swing played), or SwingStartMaxMs passes.
+ public const long SwingStartMaxMs = 1500;
+ public const long SwingEmergencyMaxMs = 500;
+ private static long _swingSentMs;
+ private static bool _swingSeenBusy;
+ private static long _swingHolds;
+ private static readonly HashSet _swingLogged = new();
+ public static long SwingHoldCount => _swingHolds;
+
+ /// CombatManager sent a melee or missile attack.
+ public static void NoteAttackSent()
+ {
+ lock (Gate)
+ {
+ _swingSentMs = NowMs();
+ _swingSeenBusy = false;
+ _swingLogged.Clear();
+ }
+ }
+
+ private static bool SwingHolds(RynthCoreHost host, string who, HealNeed heal, bool busy, long now, out string why)
+ {
+ why = "";
+ string? line = null;
+ bool hold = false;
+ lock (Gate)
+ {
+ if (_swingSentMs == 0) return false;
+ long age = now - _swingSentMs;
+ if (busy) _swingSeenBusy = true;
+ if ((_swingSeenBusy && !busy) || age >= SwingStartMaxMs)
+ {
+ _swingSentMs = 0;
+ }
+ else if (!_swingSeenBusy && !(heal == HealNeed.Emergency && age >= SwingEmergencyMaxMs))
+ {
+ hold = true;
+ _swingHolds++;
+ why = $"a swing sent {age} ms ago hasn't started animating yet";
+ if (_swingLogged.Add(who)) line = $"[Pace] {who} waits: {why}";
+ }
+ }
+ if (line != null) Log(host, line);
+ return hold;
+ }
+
///
/// True while the outstanding action is one the server animates (all of them: the walk/turn
/// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds
@@ -403,6 +559,7 @@ internal static class ActionPacer
lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}");
lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}");
lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}");
+ lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}");
if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})");
if (_holdsByWho.Count > 0)
{
@@ -462,6 +619,11 @@ internal static class ActionPacer
Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)");
return false;
}
+ if (GestureHolds(host, "mode:" + who, HealNeed.None, out _))
+ {
+ lock (Gate) _modeRefused++;
+ return false;
+ }
}
int seq = UseDoneSeqNow(host);
if (host.ChangeCombatMode(mode))
diff --git a/Plugins/Shared/CombatText.cs b/Plugins/Shared/CombatText.cs
new file mode 100644
index 0000000..63a883f
--- /dev/null
+++ b/Plugins/Shared/CombatText.cs
@@ -0,0 +1,127 @@
+// ============================================================================
+// RynthSuite - Plugins/Shared/CombatText.cs
+// Reading YOUR hits out of the combat log: who was hit and for how much.
+// Compiled into RynthAi and RynthTracker (linked source), so both read the
+// same lines the same way.
+//
+// A spell that hits several monsters (a ring, a wall, a blast, or a chain
+// spell on servers that have them) sends one line per monster it hurt, each
+// naming that monster:
+// ACE: "You blast Drudge Skulker for 153 points with Whirling Blade VII."
+// retail: "You scorch Mosswart Worshipper for 1,234 points of fire damage!"
+// with optional prefixes ("Critical hit! ", "Sneak Attack! ", "Overpower! ").
+// The victim's name is what tells the lines apart; nothing else in them does.
+//
+// Note (ACE SpellProjectile.DamageTarget): the line is sent only while the
+// target is still alive. The killing blow sends the killer notification
+// instead, so a monster killed by its first hit has no damage line at all.
+// ============================================================================
+using System;
+
+namespace RynthCore.Plugin.Shared;
+
+internal static class CombatText
+{
+ ///
+ /// Reads one of OUR damage lines. True with the victim's name (no leading "the") and the
+ /// amount; false for anything else: a monster hitting us (or our body part), drains and
+ /// heals ("points of mana"), experience, evades. Allocation-light: one Substring for the name.
+ ///
+ public static bool TryParseOutgoingHit(string? text, out string victim, out int amount)
+ {
+ victim = "";
+ amount = 0;
+ if (string.IsNullOrEmpty(text)) return false;
+
+ int start = SkipPrefixes(text);
+ if (!StartsWithWord(text, start, "You")) return false;
+ int verbStart = start + 3;
+ while (verbStart < text.Length && text[verbStart] == ' ') verbStart++;
+ // The verb is one word ("blast", "gore", "scorch", "slash"...).
+ int verbEnd = verbStart;
+ while (verbEnd < text.Length && char.IsLetter(text[verbEnd])) verbEnd++;
+ if (verbEnd == verbStart || verbEnd >= text.Length || text[verbEnd] != ' ') return false;
+
+ int pts = text.IndexOf(" points", verbEnd, StringComparison.OrdinalIgnoreCase);
+ if (pts < 0) return false;
+
+ // What follows "points" decides whether it is damage.
+ int w = pts + 7;
+ while (w < text.Length && text[w] == ' ') w++;
+ bool nextWith = WordAt(text, w, "with");
+ bool nextOf = WordAt(text, w, "of");
+ bool isDamage = nextWith || (nextOf && text.IndexOf("damage", w, StringComparison.OrdinalIgnoreCase) >= 0);
+ if (!isDamage) return false;
+
+ // The number right before " points".
+ int i = pts - 1;
+ long val = 0, mult = 1;
+ bool any = false;
+ while (i >= 0 && (char.IsDigit(text[i]) || text[i] == ','))
+ {
+ if (text[i] != ',') { val += (text[i] - '0') * mult; mult *= 10; any = true; }
+ i--;
+ }
+ if (!any || val <= 0 || val > 1_000_000) return false;
+
+ // "... for ": the victim runs from after the verb to " for ".
+ const string forWord = " for ";
+ int forAt = i - forWord.Length + 1;
+ if (forAt <= verbEnd || string.CompareOrdinal(text, forAt, forWord, 0, forWord.Length) != 0) return false;
+ int nameStart = verbEnd + 1;
+ if (StartsWithWord(text, nameStart, "the")) nameStart += 4;
+ if (forAt <= nameStart) return false;
+ string name = text.Substring(nameStart, forAt - nameStart).Trim();
+ // "You ... yourself", "your ..." are not monsters.
+ if (name.Length == 0 || name.Equals("yourself", StringComparison.OrdinalIgnoreCase)
+ || name.StartsWith("your ", StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ victim = name;
+ amount = (int)val;
+ return true;
+ }
+
+ /// The monster's name out of a corpse's name ("Corpse of Drudge Skulker"), else null.
+ public static string? CorpseOwnerName(string? corpseName)
+ {
+ const string prefix = "Corpse of ";
+ if (string.IsNullOrEmpty(corpseName) || !corpseName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
+ return null;
+ string n = corpseName.Substring(prefix.Length).Trim();
+ return n.Length == 0 ? null : n;
+ }
+
+ // "Critical hit! ", "Sneak Attack! ", "Overpower! " (any order, any number): a short run
+ // of words ending in '!' before the sentence proper.
+ private static int SkipPrefixes(string text)
+ {
+ int p = 0;
+ for (int guard = 0; guard < 4; guard++)
+ {
+ while (p < text.Length && text[p] == ' ') p++;
+ int bang = text.IndexOf('!', p);
+ if (bang < 0 || bang - p > 24) break;
+ bool words = true;
+ for (int k = p; k < bang; k++)
+ if (!(char.IsLetter(text[k]) || text[k] == ' ')) { words = false; break; }
+ if (!words || bang == p) break;
+ // A sentence that itself ends in '!' ("You scorch X for 5 points of fire damage!") is
+ // not a prefix: prefixes never contain "You ".
+ if (StartsWithWord(text, p, "You")) break;
+ p = bang + 1;
+ }
+ while (p < text.Length && text[p] == ' ') p++;
+ return p;
+ }
+
+ private static bool StartsWithWord(string text, int pos, string word)
+ {
+ if (pos < 0 || pos + word.Length > text.Length) return false;
+ if (string.Compare(text, pos, word, 0, word.Length, StringComparison.OrdinalIgnoreCase) != 0) return false;
+ int end = pos + word.Length;
+ return end >= text.Length || !char.IsLetter(text[end]);
+ }
+
+ private static bool WordAt(string text, int pos, string word) => StartsWithWord(text, pos, word);
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs
index d1cec55..b12bc04 100644
--- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs
@@ -82,6 +82,9 @@ internal static unsafe class FakeHost
public static readonly List AutoRunCalls = new();
public static bool AutoRun;
public static int Jumps;
+ /// Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in .
+ public static bool TapJumpCalls;
+ public static int TapJumps;
public static int Turns;
public static readonly List<(uint Target, int SpellId)> Casts = new();
/// Opt-in: wires GiveObjectTo (AC's give action); every call lands in .
@@ -193,7 +196,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; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
+ AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
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;
@@ -245,6 +248,8 @@ internal static unsafe class FakeHost
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun;
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading;
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous;
+ if (TapJumpCalls)
+ api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl])&TapJump;
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl])&CastSpell;
if (StopCalls)
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely;
@@ -614,6 +619,9 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int JumpNonAutonomous(float extent) { Jumps++; return 1; }
+ [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
+ private static int TapJump() { TapJumps++; return 1; }
+
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs
index 313385a..320a21b 100644
--- a/Tools/RynthCore.RynthAiHostTests/Program.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Program.cs
@@ -64,6 +64,7 @@ internal static class Program
OwnCorpseTests.Register(runner);
UseRefusalTests.Register(runner);
VitalsTests.Register(runner);
+ MultiTargetTests.Register(runner);
CastSafetyTests.Register(runner);
HealLatencyTests.Register(runner);
BlastTests.Register(runner);
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
index 05f1905..8a2cc81 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
@@ -49,14 +49,22 @@ internal static class ActionPacingTests
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
- r.Add("pacing: heals keep their priority (1 s behind a corpse use, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
+ r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
- r.Add("pacing (vitals): a heal goes 1 s behind an unanswered corpse use; the emergency stance settle is unchanged", HealLatencyKept);
+ r.Add("pacing (vitals): a heal waits for an unanswered corpse use's answer, then goes at once; the emergency stance settle is unchanged", HealLatencyKept);
r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer);
r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected);
r.Add("pacing (combat): the idle peace swap waits while a kit is unanswered", CombatPeaceWaitsForKit);
r.Add("pacing (arbiter): the activity-change StopCompletely only when RynthAi itself has the character moving", ArbiterStopOnlyWhenMoving);
r.Add("busy mirror: follows the engine's count (1.5 s), never reset while the engine says busy; old engines: the mirror only; never a force-clear", MirrorResetOnly);
+ r.Add("motion gate (14:29): a kit waits for the swing's animation; the corpse open waits for the kit's answer and then its animation", MotionGate1429);
+ r.Add("pacing (motion): after a swing is sent, nothing else starts until it has played (16:45 wand on a swing)", SwingNotStarted);
+ r.Add("motion gate (13:58): wand wield -> the cast and the Magic stance wait until the wield's animation is over", MotionGate1358);
+ r.Add("motion gate (morning): corpse use -> the idle peace swap waits for the UseDone and then the turn's animation", MotionGateMorning);
+ r.Add("motion gate: 4 s of 'animating' is taken as stuck (logged once, open until it reads clear); an emergency heal waits 1.5 s at most", MotionGateLimits);
+ r.Add("motion gate: melee/missile attack repeats are not held by the animation, peace/magic combat starts are; off with the pacing", MotionGateAttackExempt);
+ r.Add("motion gate (looting): a corpse open waits while the character animates, then goes", MotionGateLooting);
+ r.Add("motion gate (items): the item managers' busy count includes the animation", MotionGateItems);
}
// ── Pacer rig ───────────────────────────────────────────────────────────────
@@ -239,14 +247,18 @@ internal static class ActionPacingTests
host.UseFor(Corpse, "Loot", "open");
_t += 900;
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a heal 900 ms behind an unanswered corpse use waits");
- _t += 100;
- Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at 1 s it goes ahead (the server cancels the walk cleanly)");
- Check.True(Logged("the heal goes ahead of the use of"), "logged");
-
+ _t += 3000;
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _),
+ "a plain heal still waits at 3.9 s: on ACE any motion during the server's turn to the corpse stops that turn for good");
FakeHost.UseDone(0);
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the use is answered: the heal goes");
+
host.UseFor(Corpse, "Loot", "open");
- _t += 300;
+ _t += 299;
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: not before 300 ms");
+ _t += 1;
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: 300 ms");
+ Check.True(Logged("the heal goes ahead of the use of"), "logged");
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything else still waits");
FakeHost.UseDone(0);
@@ -356,17 +368,20 @@ internal static class ActionPacingTests
PaceOn();
try
{
- // A heal behind a corpse use the server walks to: it waits 1 s, not the whole walk.
+ // A heal behind a corpse use the server walks/turns to: it waits for the use's answer (a cast
+ // during the server's turn stops the turn for good on ACE), then goes at once.
var r = new BuffRig();
r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0;
r.V.CurrentHealth = 50; r.V.CurrentMana = 100;
r.At(0);
r.Host.UseFor(Corpse, "Loot", "open the claimed corpse");
r.B.BusyCount = 1; // the open's +1 on the client's count, as the engine reports it
- for (double s = 0; s < 0.95; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
- Check.Eq(FakeHost.Casts.Count, 0, "under 1 s behind the unanswered open: no heal yet");
- r.At(1.0); r.B.OnHeartbeat();
- Check.Eq(FakeHost.Casts.Count, 1, "at 1 s the heal goes (the open's busy count doesn't hold it again)");
+ for (double s = 0; s < 1.45; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
+ Check.Eq(FakeHost.Casts.Count, 0, "behind the unanswered open: no heal");
+ FakeHost.UseDone(0);
+ r.B.BusyCount = 0; // the engine's UseDone decrement
+ r.At(1.5); r.B.OnHeartbeat();
+ Check.Eq(FakeHost.Casts.Count, 1, "the open is answered: the heal goes on the next heartbeat");
string healName = SpellTable.ById(FakeHost.Casts[0].SpellId)?.Name ?? "";
Check.True(healName.StartsWith("Heal Self") || healName == "Adja's Intervention", "and it is the heal spell: " + healName);
@@ -619,4 +634,199 @@ internal static class ActionPacingTests
Check.True(Logged("resetting the mirror only"), "and the line says so");
});
}
+
+ // ── The motion gate (2026-10-06 afternoon, ops\overnight\2026-10-06-turnto-stall.md) ──────────
+ // Nothing starts while the character is still animating (the client's motion queue, the engine's
+ // GetCastBusyState); FakeHost.CastBusy = 1 stands for "animating".
+
+ // 16:45:37: the wand's use went 110 ms after a MeleeAttack, before the swing animated.
+ private static void SwingNotStarted() => Paced(() =>
+ {
+ var host = World();
+ FakeHost.CastBusy = 0;
+ ActionPacer.NoteAttackSent();
+ _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");
+ _t += 200;
+ FakeHost.CastBusy = 1;
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "swinging: still waits");
+ _t += 700;
+ FakeHost.CastBusy = 0;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the swing played: the wand goes");
+
+ ActionPacer.NoteAttackSent();
+ _t += 600;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits at most 500 ms");
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "anything else still waits");
+ _t += 1000;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a swing that never animates holds at most 1.5 s");
+ Check.True(ActionPacer.SwingHoldCount >= 2, "holds counted");
+ });
+
+ private static void MotionGate1429() => Paced(() =>
+ {
+ var host = World();
+ // 14:29:21.435 the swing; 22.380 AttackDone (the attack sequence is over, the swing still plays).
+ FakeHost.CastBusy = 1;
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out string why), "22.41: the kit waits for the swing's animation");
+ Check.True(why.Contains("still animating"), "why says so: " + why);
+ Check.True(Logged("[Pace] Buff waits: the character is still animating"), "logged once");
+ _t += 300;
+ FakeHost.CastBusy = 0;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the swing is over: the kit goes");
+ host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
+ FakeHost.CastBusy = 1; // the kit's SkillHealSelf
+ _t += 2400;
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "the corpse open waits for the kit's answer");
+ FakeHost.UseDone(0); // 24.794 the kit's UseDone; the client still plays the kit's last frames
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out why), "answered, but still animating: the open waits");
+ Check.True(why.Contains("still animating"), "why: " + why);
+ _t += 120;
+ FakeHost.CastBusy = 0;
+ Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at rest: the corpse open goes");
+ Check.True(ActionPacer.GestureHoldCount >= 2, "holds counted");
+ });
+
+ private static void MotionGate1358() => Paced(() =>
+ {
+ var host = World(combatMode: 2);
+ // 13:58:54.210 the wand is wielded in melee stance (its use is an item use, answered by wielding).
+ host.UseFor(Wand, "Buff", "buffing: switch to the wand");
+ FakeHost.CastBusy = 1; // the unwield/wield and stance motion
+ FakeHost.Wielded[Wand] = 0x01000000;
+ _t += 50;
+ ActionPacer.Current(host); // the wield is first seen done
+ _t += 200;
+ Check.True(ActionPacer.Current(host) == null, "the wield reads done: answered");
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the cast waits: still animating");
+ Check.False(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "the Magic stance waits too");
+ Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode request sent");
+ Check.True(Logged("[Pace] mode:Buff waits: the character is still animating"), "logged");
+ _t += 900;
+ FakeHost.CastBusy = 0;
+ Check.True(host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"), "at rest: Magic mode");
+ Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "sent");
+ FakeHost.CombatModeValue = 8;
+ FakeHost.CastBusy = 1; // the stance animation
+ _t += ActionPacer.ModeSettleMs;
+ Check.True(ActionPacer.Current(host) == null, "the stance is read and settled");
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "but the client still animates it: the cast waits");
+ FakeHost.CastBusy = 0;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "at rest: the cast goes");
+ });
+
+ private static void MotionGateMorning() => Paced(() =>
+ {
+ var host = World(combatMode: 2);
+ FakeHost.Positions[Player] = Me0;
+ FakeHost.PlayerPose = Me0;
+ var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
+ var cache = new WorldObjectCache(host);
+ cache.SetPlayerId(Player);
+ var combat = new CombatManager(host, s, cache);
+ combat.SetPlayerId(Player);
+
+ // 06:18:44.549 the corpse use in melee stance; the idle peace swap came 3 ms later.
+ host.UseFor(Corpse, "Loot", "open the claimed corpse");
+ _t += 3;
+ combat.Think();
+ Check.Eq(FakeHost.CombatModeRequests.Count, 0, "3 ms later: no peace swap (the use is unanswered)");
+ FakeHost.CastBusy = 1; // the turn to the corpse
+ _t += 400;
+ FakeHost.UseDone(0);
+ typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
+ combat.Think();
+ Check.Eq(FakeHost.CombatModeRequests.Count, 0, "answered, but the character still animates: no peace swap");
+ _t += 200;
+ FakeHost.CastBusy = 0;
+ typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
+ combat.Think();
+ Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "at rest: the idle swap goes out");
+ });
+
+ private static void MotionGateLimits() => Paced(() =>
+ {
+ var host = World();
+ FakeHost.CastBusy = 1;
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "animating: held");
+ _t += 1499;
+ Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal waits up to 1.5 s");
+ _t += 1;
+ Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at 1.5 s the emergency heal goes");
+ Check.True(Logged("emergency heal after 1500 ms of animation - going on"), "logged");
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "anything else still waits");
+ _t += ActionPacer.GestureHoldMaxMs - 1500;
+ Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "4 s: taken as stuck, the action goes");
+ Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "logged once");
+ _t += 5000;
+ Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "still open while it reads busy");
+ Check.Eq(FakeHost.Logs.Count(l => l.Contains("taken as stuck, going on")), 1, "not logged again");
+ Check.Eq(ActionPacer.GestureLimits, 2L, "two limits counted");
+ FakeHost.CastBusy = 0;
+ Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "clear");
+ Check.True(Logged("animation queue reads clear again"), "the recovery is logged");
+ FakeHost.CastBusy = 1;
+ Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "a new animation: held again (a fresh 4 s)");
+ });
+
+ private static void MotionGateAttackExempt() => Paced(() =>
+ {
+ 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.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)");
+ FakeHost.UseDone(0);
+ Check.True(ActionPacer.Current(host) == null, "the use is answered");
+ ActionPacer.Enabled = false;
+ Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "pacing off: no gate");
+ Check.False(ActionPacer.GestureHolds(host, "Loot", HealNeed.None, out _), "pacing off: no animation hold");
+ ActionPacer.Enabled = true;
+ FakeHost.ServerGates = false;
+ var old = FakeHost.Create(Player);
+ Check.True(ActionPacer.MayStart(old, "Loot", HealNeed.None, out _), "an engine without the gate: no opinion");
+ });
+
+ private static void MotionGateLooting()
+ {
+ LootWorld();
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ PaceOn();
+ try
+ {
+ WithClock((now, advance) =>
+ {
+ FakeHost.CastBusy = 1;
+ for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); }
+ Check.Eq(FakeHost.Uses.Count, 0, "no open while the character animates");
+ Check.True(Logged("[Pace] Loot waits: the character is still animating"), "logged");
+ FakeHost.CastBusy = 0;
+ for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); }
+ Check.Eq(FakeHost.Uses.Count, 1, "at rest: the open goes");
+ });
+ }
+ finally { PaceOff(); }
+ }
+
+ private static void MotionGateItems()
+ {
+ LootWorld();
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ PaceOn();
+ try
+ {
+ int Busy() => (int)typeof(RynthAiPlugin).GetProperty("PacedBusy", Any)!.GetValue(bot.P)!;
+ Check.Eq(Busy(), 0, "at rest, nothing outstanding: 0");
+ FakeHost.CastBusy = 1;
+ Check.Eq(Busy(), 1, "animating: +1 (a pack move of a wielded item, a stone, a summon waits)");
+ FakeHost.CastBusy = 0;
+ Check.Eq(Busy(), 0, "at rest again: 0");
+ }
+ finally { PaceOff(); }
+ }
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs
index 8e441de..82bf1b7 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatMathTests.cs
@@ -35,9 +35,7 @@ internal static class CombatMathTests
r.Add("target range: closest first, then the one in front", ScanOrder);
r.Add("target range: dead, unattackable, never-attack and spell projectiles are skipped", ScanFilters);
- r.KnownFailure("damage text: a monster hitting our body part isn't our damage",
- "TryParseOutgoingDamage only rejects \"you for\"; a hit like 'Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!' is counted as a hit by us while casting, which skews the Damage tab averages and the kill-shot prediction (not fixed on any branch)",
- BodyPartHitIsNotOurs);
+ r.Add("damage text: a monster hitting our body part isn't our damage", BodyPartHitIsNotOurs); // was a known failure; fixed by feature/warchain-fix (the line must start with "You")
r.Add("weapon choice: a weapon the character no longer has is skipped", WeaponMissingSkipped); // was a known failure; fixed by 996b2a5
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
index c58f90f..87f2a00 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootCorpseTests.cs
@@ -50,6 +50,7 @@ internal static class LootCorpseTests
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
+ r.Add("loot pacing: a pickup waits for the last bend-down, and no retry is timed while it plays", PickupWaitsForAnimation);
}
// ── World set-up ──────────────────────────────────────────────────────────
@@ -440,4 +441,58 @@ internal static class LootCorpseTests
bot.Call("CloseOpenCorpseOnMacroStop");
Check.Eq(FakeHost.Closes.Count, 1, "a stop with no corpse open closes nothing");
}
+
+ // 2026-10-07, Drakkon: picking up an item plays a bend-down, and the engine holds queued
+ // moves until it ends (about 2.2 s). RynthAi retried every 0.5 s from the send and gave up
+ // after 3 tries, so items were skipped while their first move had not even gone out.
+ private static void PickupWaitsForAnimation()
+ {
+ BaseWorld(corpsePositioned: true);
+ FakeHost.ServerGates = true; // GetCastBusyState
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ bot.Cache.OnCreateObject(Corpse);
+ bot.Cache.Tick();
+ bot.Tick(BotActivity.Looting);
+ Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
+
+ // The last pickup is still animating when the corpse's contents arrive.
+ FakeHost.CastBusy = 1;
+ bot.Cache.OnCreateObject(Gem);
+ bot.Cache.Tick();
+ bot.P.OnViewObjectContents(Corpse);
+ TickFor(bot, 500);
+ Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "no pickup sent while the character animates");
+
+ FakeHost.CastBusy = 0;
+ for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
+ {
+ bot.Tick(BotActivity.Looting);
+ Thread.Sleep(10);
+ }
+ Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the pickup goes out once the character is still");
+
+ // Its own bend-down plays for longer than 3 retry windows: no retry, no give-up.
+ FakeHost.CastBusy = 1;
+ TickFor(bot, 1800);
+ Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "no retry while the pickup animates");
+ Check.False(FakeHost.Logs.Any(l => l.Contains("pickup failed")), "the item is not given up on");
+
+ // Still again and the item still on the corpse: the retry window starts now.
+ FakeHost.CastBusy = 0;
+ TickFor(bot, 250);
+ Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 1, "the retry window counts from when the character is still");
+ TickFor(bot, 500);
+ Check.Eq(FakeHost.ExternalMoves.Count(m => m.Id == Gem), 2, "then one retry");
+ }
+
+ private static void TickFor(Bot bot, int ms)
+ {
+ long end = Environment.TickCount64 + ms;
+ while (Environment.TickCount64 < end)
+ {
+ bot.Tick(BotActivity.Looting);
+ Thread.Sleep(10);
+ }
+ }
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs
new file mode 100644
index 0000000..4a1e263
--- /dev/null
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/MultiTargetTests.cs
@@ -0,0 +1,207 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi;
+using RynthCore.Plugin.RynthAi.CreatureData;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.Shared;
+using RynthCore.RynthAiHostTests.Fakes;
+using RynthCore.RynthAiTests.Harness;
+
+namespace RynthCore.RynthAiHostTests.Tests;
+
+// One spell, several monsters: rings, walls, blasts and chain spells (Conquest). Each monster the
+// spell hurts gets its own damage line naming it, the server sends health only for the selected
+// target, and a kill notice names the monster that died. These tests drive CombatManager with
+// those lines on the fake host: every line goes to the monster it names (never to the fight
+// target), the other monsters get a health estimate, and kill notices from one cast keep the scan
+// off each monster that died without dropping a fight target that is still alive.
+internal static class MultiTargetTests
+{
+ private const uint Player = 0x50000C01;
+ private const uint Lb = 0xA9B40000;
+ private const uint SkulkerWcid = 1001, MosswartWcid = 1002;
+
+ public static void Register(Runner r)
+ {
+ r.Add("damage text: the victim's name comes with the amount", VictimNames);
+ r.Add("multi-target: each damage line goes to the monster it names", LinesGoToTheirMonsters);
+ r.Add("multi-target: same-named monsters in one volley are told apart", SameNameVolley);
+ r.Add("multi-target: other targets get a health estimate, the server's number wins", HealthEstimates);
+ r.Add("multi-target: several kills from one cast keep the live fight target", KillsFromOneCast);
+ r.Add("multi-target: the fight target's own kill notice still drops it", FightTargetKill);
+ }
+
+ // ── The parser ───────────────────────────────────────────────────────────
+
+ private static string? Victim(string text) => CombatText.TryParseOutgoingHit(text, out string v, out _) ? v : null;
+
+ private static void VictimNames()
+ {
+ Check.Eq(Victim("You blast Drudge Skulker for 153 points with Whirling Blade VII."), "Drudge Skulker", "ACE war magic");
+ Check.Eq(Victim("You scorch the Mosswart Worshipper for 1,234 points of fire damage!"), "Mosswart Worshipper", "retail, 'the' dropped");
+ Check.Eq(Victim("Critical hit! Sneak Attack! You gore Olthoi Slasher for 1638 points with Force Arc VII."), "Olthoi Slasher", "two prefixes");
+ Check.Eq(Victim("Overpower! You frost Tusker Guard for 40 points with Frost Bolt VI."), "Tusker Guard", "Overpower prefix");
+ Check.Eq(Victim("You slash Banderling Scout for 12 points of slashing damage!"), "Banderling Scout", "melee");
+ Check.Eq(Victim("Olthoi Swarm Harvester blisters your lower leg for 12 points of acid damage!"), null, "a monster's hit on us");
+ Check.Eq(Victim("You drain 45 points of mana from Drudge Skulker."), null, "a drain");
+ Check.Eq(Victim("You heal yourself for 64 points."), null, "a heal");
+ Check.Eq(CombatText.CorpseOwnerName("Corpse of Drudge Skulker"), "Drudge Skulker", "corpse name");
+ Check.Eq(CombatText.CorpseOwnerName("Drudge Skulker"), null, "not a corpse");
+ }
+
+ // ── The rig ──────────────────────────────────────────────────────────────
+
+ private sealed class Rig
+ {
+ public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
+ public readonly MonsterDamageStore Store = new();
+ public CombatManager C = null!;
+ public RynthCore.Plugin.RynthAi.WorldObjectCache Cache = null!;
+ private readonly List _ids = new();
+ private uint _next = 0x80000301;
+
+ public Rig()
+ {
+ FakeHost.Reset();
+ FakeHost.WeaponCalls = true; // installs GetCurrentCombatMode
+ FakeHost.CombatModeValue = CombatMode.Magic;
+ FakeHost.Names[Player] = "Me";
+ FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
+ FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
+ }
+
+ public uint Mob(string name, uint wcid, float north, float east)
+ {
+ uint id = _next++;
+ FakeHost.Names[id] = name;
+ FakeHost.Positions[id] = (Lb | 0x1C, 96f + east, 96f + north, 0f);
+ FakeHost.ItemTypes[id] = 0x10;
+ FakeHost.Wcids[id] = wcid;
+ _ids.Add(id);
+ return id;
+ }
+
+ public void Build(uint fightTarget, IReadOnlyDictionary? health = null)
+ {
+ var host = FakeHost.Create();
+ Cache = FakeHost.MakeCache(host, Player, _ids, health);
+ C = new CombatManager(host, S, Cache);
+ C.SetPlayerId(Player);
+ C.SetDamageStores(null, Store);
+ C.EngageForTest(unchecked((int)fightTarget));
+ }
+
+ public float Hp(uint id) => Cache.GetHealthRatio(unchecked((int)id));
+
+ /// Learned non-crit average damage per monster type (the Damage tab's rows).
+ public Dictionary Learned()
+ => Store.Snapshot().GroupBy(r => r.Wcid)
+ .ToDictionary(g => g.Key, g => (g.First().AvgDamage, g.Sum(r => r.DmgSamples)));
+ }
+
+ // ── The tests ────────────────────────────────────────────────────────────
+
+ private static void LinesGoToTheirMonsters()
+ {
+ var rig = new Rig();
+ uint skulker = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0);
+ uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
+ rig.Build(skulker);
+
+ rig.C.HandleChatForDamage("You blast Drudge Skulker for 100 points with Lightning Chain VI.");
+ rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 40 points with Lightning Chain VI.");
+
+ var learned = rig.Learned();
+ Check.True(learned.ContainsKey(MosswartWcid), "the Mosswart's hit is learned against the Mosswart");
+ Check.Near(learned.GetValueOrDefault(MosswartWcid).Avg, 40, 1e-6, "the Mosswart's damage is its own 40");
+ Check.Near(learned.GetValueOrDefault(SkulkerWcid).Avg, 100, 1e-6, "the Skulker keeps only its own 100 (not 140, not 70)");
+ Check.Eq(learned.GetValueOrDefault(SkulkerWcid).Samples, 1, "one hit learned for the Skulker");
+ Check.True(rig.Hp(moss) > 0f && rig.Hp(moss) < 1f, $"the Mosswart is marked hurt ({rig.Hp(moss):0.00})");
+ Check.True(rig.Cache.IsHealthEstimated(unchecked((int)moss)), "and its health is our estimate");
+ Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)skulker)), "the fight target gets no estimate (the server sends its health)");
+ }
+
+ private static void SameNameVolley()
+ {
+ var rig = new Rig();
+ uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
+ uint near = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
+ uint far = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 20, 0);
+ rig.Build(target);
+ rig.Store.SetManualHp(SkulkerWcid, 200);
+
+ // One chain: the target, then the nearest other soldier, then the next.
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.");
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 50 points with Lightning Chain VI.");
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 20 points with Lightning Chain VI.");
+
+ Check.Near(rig.Hp(near), 0.75, 1e-4, "second line -> the nearest other soldier (200 hp, -50)");
+ Check.Near(rig.Hp(far), 0.90, 1e-4, "third line -> the next one (-20)");
+ Check.True(!rig.Cache.IsHealthEstimated(unchecked((int)target)), "the first line was the fight target's");
+ }
+
+ private static void HealthEstimates()
+ {
+ var rig = new Rig();
+ uint target = rig.Mob("Drudge Skulker", SkulkerWcid, 5, 0);
+ uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
+ rig.Build(target);
+ rig.Store.SetManualHp(MosswartWcid, 100);
+ int m = unchecked((int)moss);
+
+ Check.Near(rig.Hp(moss), -1, 1e-6, "no health known before the hit");
+ rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 30 points with Flame Ring VI.");
+ Check.Near(rig.Hp(moss), 0.70, 1e-4, "100 hp, hit for 30 -> 0.70");
+ System.Threading.Thread.Sleep(900); // next volley
+ rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 500 points with Flame Ring VI.");
+ Check.Near(rig.Hp(moss), RynthCore.Plugin.RynthAi.WorldObjectCache.EstimatedHealthFloor, 1e-6,
+ "an estimate never reads dead (0): only the server says dead");
+ rig.Cache.OnUpdateHealth(moss, 0.40f);
+ Check.Near(rig.Hp(moss), 0.40, 1e-6, "the server's number replaces the estimate");
+ Check.True(!rig.Cache.IsHealthEstimated(m), "and it is no longer an estimate");
+ rig.Cache.ApplyDamageEstimate(m, 0.0);
+ Check.Near(rig.Hp(moss), 0.40, 1e-6, "an unknown-max hit never raises a known value");
+ }
+
+ private static void KillsFromOneCast()
+ {
+ var rig = new Rig();
+ uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
+ uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
+ uint moss = rig.Mob("Mosswart Worshipper", MosswartWcid, 6, 2);
+ rig.Build(target);
+
+ // A cast hits all three; the server has the fight target at 60%.
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
+ rig.C.HandleChatForDamage("You blast Mosswart Worshipper for 100 points with Flame Ring VI.");
+ rig.Cache.OnUpdateHealth(target, 0.60f);
+
+ // The next cast kills the twin and the Mosswart (one notice each), not the target.
+ rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!");
+ rig.C.OnKillNotification("You slay Mosswart Worshipper viciously enough to impart death several times over!");
+
+ Check.True(rig.C.IsKillSuppressed(unchecked((int)twin)), "the same-named twin is the one that died");
+ Check.True(rig.C.IsKillSuppressed(unchecked((int)moss)), "the Mosswart died");
+ Check.True(!rig.C.IsKillSuppressed(unchecked((int)target)), "the live fight target is not suppressed");
+ Check.Eq(rig.C.activeTargetId, unchecked((int)target), "and is still the target");
+ }
+
+ private static void FightTargetKill()
+ {
+ var rig = new Rig();
+ uint target = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 5, 0);
+ uint twin = rig.Mob("Olthoi Swarm Soldier", SkulkerWcid, 7, 0);
+ rig.Build(target);
+
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
+ rig.C.HandleChatForDamage("You blast Olthoi Swarm Soldier for 100 points with Flame Ring VI.");
+ rig.Cache.OnUpdateHealth(target, 0f); // ACE: the 0 comes with the lethal hit, before the notice
+ rig.C.OnKillNotification("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!");
+
+ Check.True(rig.C.IsKillSuppressed(unchecked((int)target)), "the fight target died and is suppressed");
+ Check.Eq(rig.C.activeTargetId, 0, "and dropped");
+ Check.True(!rig.C.IsKillSuppressed(unchecked((int)twin)), "the twin is untouched");
+ }
+}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
index d73ea3c..bbbae57 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
@@ -49,6 +49,10 @@ internal static class UseRefusalTests
r.Add("move hold: off unless the plugin opts in (RynthNav, RynthLua unchanged)", MoveHoldOptIn);
r.Add("idle peace: Combat's idle peace swap waits while looting has work", IdlePeaceHeldWhileLooting);
r.Add("idle peace: looting has work = a corpse claimed, a corpse open, a corpse in range, or a use in flight", LootHoldsIdlePeaceInputs);
+ r.Add("use check jump: one jump per back-off, before the probe; none while normal or during the back-off", WatchProbeJump);
+ r.Add("use check jump (looting): the clean stop jumps (TapJump, not JumpNonAutonomous), the retry waits the pause, an open after it is logged as cleared", LootingStallJumpClears);
+ r.Add("use check jump (looting): still stuck after the jump -> back-off; the probe goes out only after a jump and the pause", LootingStallJumpBeforeProbe);
+ r.Add("use check jump: no jump while the server still owes an answer to a cast (a jump would fail it)", NoJumpWhilePacerOutstanding);
}
// ── UseRefusalWatch alone ─────────────────────────────────────────────────
@@ -536,4 +540,154 @@ internal static class UseRefusalTests
});
Check.False(Holds(), "all clear: no hold");
}
+
+ // ── The jump (2026-10-06 afternoon) ───────────────────────────────────────
+ // On ACE the player's jump (Player.HandleActionJump) is the one in-world action that empties the
+ // server's animation queues (the stuck state); the use check jumps at the clean stop and before
+ // each probe.
+
+ private static void WatchProbeJump()
+ {
+ var r = new Rig();
+ int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB);
+ Check.False(r.W.TakeProbeJump(r.T), "normal: no jump");
+ r.RefusedOpen(a); r.RefusedOpen(a); r.RefusedOpen(a);
+ Check.False(r.W.TakeProbeJump(r.T), "retrying: no probe jump (the clean stop jumps itself)");
+ r.RefusedOpen(a);
+ Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "stuck");
+ Check.False(r.W.TakeProbeJump(r.T), "during the back-off: no jump");
+ r.T = r.W.BackoffUntil;
+ Check.True(r.W.TakeProbeJump(r.T), "the back-off is over: jump before the probe");
+ Check.False(r.W.TakeProbeJump(r.T + 100), "once");
+ Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused");
+ Check.False(r.W.TakeProbeJump(r.T), "a new back-off: no jump yet");
+ r.T = r.W.BackoffUntil;
+ Check.True(r.W.TakeProbeJump(r.T), "again once the longer back-off is over");
+ r.W.OnOpened(r.T);
+ Check.False(r.W.TakeProbeJump(r.T + UseRefusalWatch.MaxBackoffMs), "after an open: never");
+ }
+
+ /// The 14:29 server: every open is answered 60 ms later and nothing opens, until the
+ /// first open after a jump (when ).
+ private static void StallServer(Bot bot, Func now, Action advance, bool jumpClears, int maxSteps, Func until)
+ {
+ long answerAt = 0; uint answerFor = 0;
+ for (int steps = 0; steps < maxSteps && !until(); steps++)
+ {
+ int uses = FakeHost.Uses.Count;
+ bot.Tick(BotActivity.Looting);
+ if (FakeHost.Uses.Count > uses) { answerAt = now() + 60; answerFor = FakeHost.Uses.Last(); }
+ advance(100);
+ if (answerAt != 0 && now() >= answerAt)
+ {
+ FakeHost.UseDone(0);
+ if (jumpClears && FakeHost.TapJumps > 0)
+ bot.P.OnViewObjectContents(answerFor);
+ answerAt = 0;
+ }
+ }
+ }
+
+ private static void LootingStallJumpClears()
+ {
+ World();
+ FakeHost.TapJumpCalls = true;
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ WithClock((now, advance) =>
+ {
+ int usesAtJump = -1; long jumpAt = 0;
+ StallServer(bot, now, advance, jumpClears: false, maxSteps: 400, until: () =>
+ {
+ if (FakeHost.TapJumps > 0 && usesAtJump < 0) { usesAtJump = FakeHost.Uses.Count; jumpAt = now(); }
+ return usesAtJump >= 0;
+ });
+ Check.Eq(FakeHost.TapJumps, 1, "the clean stop jumps once");
+ Check.Eq(FakeHost.Jumps, 0, "with the keyboard jump, not JumpNonAutonomous (ACE ignores 0xF7C9)");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop, a jump")), "logged");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump for the retry")), "the jump is logged");
+ Check.False(FakeHost.Logs.Any(l => l.Contains("Use check: facing")), "no facing turn when it jumps");
+
+ // The retry waits for the pause, then the server (cleared by the jump) opens it.
+ long retryAt = 0;
+ StallServer(bot, now, advance, jumpClears: true, maxSteps: 100, until: () =>
+ {
+ if (retryAt == 0 && FakeHost.Uses.Count > usesAtJump) retryAt = now();
+ return bot.Get("_openedContainerId") != 0;
+ });
+ Check.True(retryAt != 0, "a retry went out");
+ Check.True(retryAt - jumpAt >= UseRefusalWatch.CleanStopPauseMs, $"after the pause ({retryAt - jumpAt} ms)");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("after the use check's jump - the jump cleared")), "the open after the jump is logged as the fix");
+ Check.Eq(ChatCount(StuckLine), 0, "the player is never told to relog");
+ Check.Eq(bot.Get("_useRefusals").State, UseRefusalWatch.Phase.Normal, "back to normal");
+ });
+ }
+
+ private static void LootingStallJumpBeforeProbe()
+ {
+ World();
+ FakeHost.TapJumpCalls = true;
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ WithClock((now, advance) =>
+ {
+ StallServer(bot, now, advance, jumpClears: false, maxSteps: 600, until: () => ChatCount(StuckLine) > 0);
+ Check.Eq(ChatCount(StuckLine), 1, "the jump didn't help here: the player is told once");
+ Check.Eq(FakeHost.TapJumps, 1, "one jump so far (the clean stop)");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("the clean stop, the jump and retry didn't help")), "the verdict says the jump was tried");
+
+ var w = bot.Get("_useRefusals");
+ int usesAtStuck = FakeHost.Uses.Count;
+ for (int i = 0; i < 2400; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 4 minutes
+ Check.Eq(FakeHost.TapJumps, 1, "no jump during the back-off");
+ Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no opens during the back-off");
+
+ long probeJumpAt = 0;
+ for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++)
+ {
+ bot.Tick(BotActivity.Looting);
+ if (probeJumpAt == 0 && FakeHost.TapJumps == 2) probeJumpAt = now();
+ advance(100);
+ }
+ Check.Eq(FakeHost.TapJumps, 2, "a jump before the probe");
+ Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "then the probe");
+ Check.True(now() - 100 - probeJumpAt >= UseRefusalWatch.CleanStopPauseMs, "the probe waits the pause after the jump");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: jump before the probe")), "logged");
+
+ // The jump cleared it: the probe opens.
+ bot.P.OnViewObjectContents(FakeHost.Uses.Last());
+ Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("the jump cleared")), "and the log says the jump did it");
+ Check.False(w.HoldsOpens(now()), "looting is back on");
+ });
+ }
+
+ private static void NoJumpWhilePacerOutstanding()
+ {
+ World();
+ FakeHost.TapJumpCalls = true;
+ var host = FakeHost.Create(Player);
+ var bot = new Bot(host);
+ long t = 10_000_000;
+ ActionPacer.Reset();
+ ActionPacer.Enabled = true;
+ ActionPacer.NowMs = () => t;
+ try
+ {
+ ActionPacer.Begin(host, PacedKind.Cast, 0, "Revitalize Self VI", "Buff", FakeHost.UseDoneSeq);
+ Check.False((bool)bot.Call("TryUseCheckJump", t, "test")!, "no jump while the cast is unanswered");
+ Check.Eq(FakeHost.TapJumps, 0, "nothing sent");
+ Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: no jump test - the server still owes an answer")), "logged");
+ FakeHost.UseDone(0);
+ t += 50;
+ Check.True((bool)bot.Call("TryUseCheckJump", t, "test")!, "answered: the jump goes");
+ Check.Eq(FakeHost.TapJumps, 1, "one jump");
+ }
+ finally
+ {
+ ActionPacer.Enabled = false;
+ ActionPacer.Reset();
+ ActionPacer.NowMs = () => Environment.TickCount64;
+ }
+ }
}
diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs
index c9d9d44..2e70afc 100644
--- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs
+++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs
@@ -22,6 +22,8 @@ internal static class VitalsTests
{
r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds);
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
+ r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
+ r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
@@ -210,6 +212,75 @@ internal static class VitalsTests
return cast;
}
+ // Tom, 2026-10-06: a melee character should drink its listed stamina potions before Revitalize
+ // (which means switching the weapon for the wand and back).
+ private static void StaminaPotionFirst()
+ {
+ const uint Tincture = 0x80001234;
+ foreach (int mode in new[] { CombatMode.Melee, CombatMode.Magic })
+ {
+ FakeHost.Reset();
+ FakeHost.WeaponCalls = true;
+ FakeHost.CombatModeValue = mode;
+ foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
+ FakeHost.Skills[(Player, STypeLife)] = (400, 2);
+ FakeHost.Names[Tincture] = "Stamina Tincture";
+ var host = FakeHost.Create();
+ var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
+ GetManaAt = 0, TopOffMana = 0, RestamAt = 30, TopOffStam = 95, UsePotions = true, EnableBuffing = false };
+ s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Tincture), Name = "Stamina Tincture", Type = "Stamina" });
+ var skills = new CharacterSkills(host);
+ skills.SetPlayerId(Player);
+ var sm = new SpellManager(host, s);
+ sm.InitializeNatively();
+ sm.SetCharacterSkills(skills);
+ var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 20, MaxMana = 100, CurrentMana = 100 };
+ var b = new BuffManager(host, s, sm, vitals);
+ b.SetCharacterSkills(skills);
+ b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Tincture }));
+ Check.True(b.CheckVitals(), $"mode {mode}: stamina 20% acts");
+ bool drank = FakeHost.Uses.Contains(Tincture);
+ if (mode == CombatMode.Melee)
+ {
+ Check.True(drank, "melee: the tincture is drunk");
+ Check.Eq(FakeHost.Casts.Count, 0, "melee: no Revitalize (no wand switch)");
+ }
+ else
+ {
+ Check.False(drank, "caster in Magic stance: no potion first");
+ Check.True(FakeHost.Casts.Count > 0, "caster: Revitalize is cast");
+ }
+ }
+ }
+
+ // Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina.
+ private static void RestamTo()
+ {
+ var s = new LegacyUiSettings { RestamAt = 30, RestamTo = 0, TopOffStam = 95 };
+ bool run = false; int casts = 0;
+ Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "off: Re-stam At");
+ Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "off: at 40% no recharge");
+
+ s.RestamTo = 70;
+ Check.Eq(BuffManager.StaminaLine(true, 40, s, ref run, ref casts), 30, "above Re-stam At with no recharge started: nothing new");
+ Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 70, "under Re-stam At: recharge to 70");
+ casts++;
+ Check.Eq(BuffManager.StaminaLine(true, 45, s, ref run, ref casts), 70, "one cast got it to 45%: still recharging (the second cast)");
+ casts++;
+ Check.Eq(BuffManager.StaminaLine(true, 72, s, ref run, ref casts), 30, "reached 70: done");
+ Check.False(run, "the recharge ended");
+
+ // A recharge that never gains stops after the cap.
+ Check.Eq(BuffManager.StaminaLine(true, 20, s, ref run, ref casts), 70, "new recharge");
+ casts = BuffManager.RestamRunMaxCasts;
+ Check.Eq(BuffManager.StaminaLine(true, 35, s, ref run, ref casts), 30, "cap reached above Re-stam At: back to Re-stam At");
+
+ // Out of combat the top-off line applies, as before.
+ Check.Eq(BuffManager.StaminaLine(false, 50, s, ref run, ref casts), 95, "idle: Top Stam");
+ s.RestamTo = 20;
+ Check.Eq(BuffManager.StaminaLine(true, 25, s, ref run, ref casts), 30, "Re-stam To not above Re-stam At: ignored");
+ }
+
private static void StaminaToHealthThresholds()
{
// Defaults: today's behaviour (30% health, stamina over 20%).
diff --git a/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs b/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs
new file mode 100644
index 0000000..09d48cd
--- /dev/null
+++ b/Tools/RynthCore.TrackerSessionTests/KillCounterTests.cs
@@ -0,0 +1,131 @@
+using System;
+using RynthCore.Plugin.RynthTracker;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.TrackerSessionTests;
+
+// KillCounter (RynthTracker 0.3.0): one cast, several kills. The events are what the client
+// sees, in the order it sees them: our damage lines (one per monster a spell hurt), the
+// server's kill notices, and corpses ("Corpse of X") a few seconds later.
+internal static partial class Program
+{
+ private static readonly DateTime T0 = new(2026, 10, 3, 2, 0, 0, DateTimeKind.Utc);
+ private static DateTime At(double seconds) => T0.AddSeconds(seconds);
+
+ private static void Hit(KillCounter k, string line, double t)
+ {
+ Check(CombatText.TryParseOutgoingHit(line, out string victim, out _), $"parses: {line}");
+ k.OnHit(victim, At(t));
+ }
+
+ private static void TestKillCounter()
+ {
+ Console.WriteLine("-- kill counter");
+
+ // ACE ring: every kill gets its notice; the corpses that follow add nothing.
+ {
+ var k = new KillCounter();
+ Hit(k, "You blast Drudge Skulker for 80 points with Flame Ring VI.", 0.0);
+ Hit(k, "You blast Drudge Slinker for 75 points with Flame Ring VI.", 0.1);
+ Hit(k, "You blast Mosswart Worshipper for 70 points with Flame Ring VI.", 0.2);
+ k.OnKillNotice("Drudge Skulker's seared corpse smolders before you!", At(2.0));
+ k.OnKillNotice("You bring Drudge Slinker to a fiery end!", At(2.1));
+ k.OnKillNotice("Mosswart Worshipper is incinerated by your assault!", At(2.2));
+ Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "ring: corpse 1 matches its notice");
+ Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Notified, "ring: corpse 2 matches its notice");
+ Eq(k.OnCorpse("Mosswart Worshipper", At(5.2)), KillCounter.CorpseResult.Notified, "ring: corpse 3 matches its notice");
+ Eq(k.Kills, 3, "ring: three kills, none counted twice");
+ }
+
+ // Conquest chain: the primary's kill has a notice, the extra targets' don't.
+ {
+ var k = new KillCounter();
+ Hit(k, "You blast Drudge Skulker for 120 points with Lightning Chain VI.", 0.0);
+ Hit(k, "You blast Drudge Slinker for 60 points with Lightning Chain VI.", 0.2);
+ Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 0.4);
+ k.OnKillNotice("You smite Drudge Skulker mightily!", At(2.0)); // the primary
+ Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 2.2);
+ // the Slinker died on that cast with no line and no notice
+ Eq(k.OnCorpse("Drudge Skulker", At(5.0)), KillCounter.CorpseResult.Notified, "chain: the primary's corpse is its notice's");
+ Eq(k.OnCorpse("Drudge Slinker", At(5.1)), KillCounter.CorpseResult.Counted, "chain: the silent extra kill counts from its corpse");
+ Hit(k, "You blast Mosswart Worshipper for 30 points with Lightning Chain VI.", 6.0);
+ Eq(k.OnCorpse("Mosswart Worshipper", At(9.0)), KillCounter.CorpseResult.Counted, "chain: the last extra target too");
+ Eq(k.Kills, 3, "chain: three kills from the chain fight");
+ Eq(k.CorpseKills, 2, "chain: two of them found by their corpse");
+ }
+
+ // A swarm: same-named monsters, two die from one cast, one notice.
+ {
+ var k = new KillCounter();
+ Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0);
+ Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.1);
+ k.OnKillNotice("Olthoi Swarm Soldier's death is preceded by a sharp, stabbing pain!", At(1.5));
+ Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.0)), KillCounter.CorpseResult.Notified, "swarm: first corpse takes the notice");
+ Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.1)), KillCounter.CorpseResult.Counted, "swarm: second corpse counts");
+ Eq(k.OnCorpse("Olthoi Swarm Soldier", At(4.2)), KillCounter.CorpseResult.HitNotCounted, "swarm: never more corpses than the volley hit");
+ Eq(k.Kills, 2, "swarm: two kills");
+ }
+
+ // The primary's kill notice and an extra target's line in one volley, same name: the
+ // notice stands for the primary, so the silent twin still counts from its corpse.
+ {
+ var k = new KillCounter();
+ Hit(k, "You blast Olthoi Swarm Soldier for 100 points with Lightning Chain VI.", 0.0); // earlier cast, primary
+ k.OnKillNotice("You slay Olthoi Swarm Soldier viciously enough to impart death several times over!", At(2.0));
+ Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 2.1); // the twin, same cast
+ Eq(k.OnCorpse("Olthoi Swarm Soldier", At(5.0)), KillCounter.CorpseResult.Notified, "notice + twin: primary's corpse");
+ Hit(k, "You blast Olthoi Swarm Soldier for 60 points with Lightning Chain VI.", 5.5); // a lone hit later on the twin
+ Eq(k.OnCorpse("Olthoi Swarm Soldier", At(8.0)), KillCounter.CorpseResult.Counted, "notice + twin: the twin counts");
+ Eq(k.Kills, 2, "notice + twin: two kills");
+ }
+
+ // Several casts at the same two monsters are still two monsters (max, not sum).
+ {
+ var k = new KillCounter();
+ for (int cast = 0; cast < 4; cast++)
+ {
+ Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0);
+ Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", cast * 2.0 + 0.1);
+ }
+ Eq(k.OnCorpse("Drudge Skulker", At(9.0)), KillCounter.CorpseResult.Counted, "repeat casts: first corpse");
+ Eq(k.OnCorpse("Drudge Skulker", At(9.1)), KillCounter.CorpseResult.Counted, "repeat casts: second corpse");
+ Eq(k.OnCorpse("Drudge Skulker", At(9.2)), KillCounter.CorpseResult.HitNotCounted, "repeat casts: not a third");
+ }
+
+ // Single-target fighting: a corpse with no notice is someone else's kill, as before.
+ {
+ var k = new KillCounter();
+ Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0);
+ Hit(k, "You slash Banderling Scout for 14 points of slashing damage!", 1.5);
+ Eq(k.OnCorpse("Banderling Scout", At(4.0)), KillCounter.CorpseResult.HitNotCounted, "single-target: not counted without a notice");
+ Eq(k.OnCorpse("Tusker Guard", At(4.0)), KillCounter.CorpseResult.NotOurs, "a corpse we never hit");
+ Eq(k.Kills, 0, "single-target: no kills");
+ }
+
+ // Lines a second apart are separate casts (a melee swing each), not one volley.
+ {
+ var k = new KillCounter();
+ Hit(k, "You slash Banderling Scout for 12 points of slashing damage!", 0.0);
+ Hit(k, "You slash Banderling Guard for 14 points of slashing damage!", 1.0);
+ Eq(k.OnCorpse("Banderling Guard", At(3.0)), KillCounter.CorpseResult.HitNotCounted, "a second apart is not multi-target");
+ }
+
+ // Expiry: a multi-target hit stops vouching for a corpse after TokenLifeMs.
+ {
+ var k = new KillCounter();
+ Hit(k, "You blast Drudge Skulker for 10 points with Flame Ring VI.", 0.0);
+ Hit(k, "You blast Drudge Slinker for 10 points with Flame Ring VI.", 0.1);
+ Eq(k.OnCorpse("Drudge Slinker", At(0.1 + KillCounter.TokenLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old hit doesn't count");
+ }
+
+ // A notice waits NoticeLifeMs for its corpse, then is forgotten (the kill stays counted).
+ {
+ var k = new KillCounter();
+ k.OnKillNotice("You smite Drudge Skulker mightily!", At(0));
+ Eq(k.OnCorpse("Drudge Skulker", At(KillCounter.NoticeLifeMs / 1000.0 + 1)), KillCounter.CorpseResult.NotOurs, "an old notice is gone");
+ Eq(k.Kills, 1, "the notice's kill stays counted");
+ k.Reset();
+ Eq(k.Kills, 0, "reset clears the count");
+ }
+ }
+}
diff --git a/Tools/RynthCore.TrackerSessionTests/Program.cs b/Tools/RynthCore.TrackerSessionTests/Program.cs
index 0713fd5..642541f 100644
--- a/Tools/RynthCore.TrackerSessionTests/Program.cs
+++ b/Tools/RynthCore.TrackerSessionTests/Program.cs
@@ -11,7 +11,7 @@ namespace RynthCore.TrackerSessionTests;
// Self-contained; fails on zero assertions.
//
// Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-internal static class Program
+internal static partial class Program
{
private static int _asserts;
private static int _fails;
@@ -45,6 +45,7 @@ internal static class Program
TestFileNames();
TestFiles();
TestCleanup();
+ TestKillCounter();
Console.WriteLine($"\n{_asserts} assertions, {_fails} failed.");
if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
diff --git a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj
index 130092c..8a415b8 100644
--- a/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj
+++ b/Tools/RynthCore.TrackerSessionTests/RynthCore.TrackerSessionTests.csproj
@@ -17,6 +17,8 @@
+
+