Snapshot for release 2026.10.12.1 (internal 8d252bd)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:13 -04:00
commit 3c4f093e3d
60 changed files with 5748 additions and 602 deletions

View file

@ -285,6 +285,189 @@ public class BuffManager : IDisposable
private const double LowManaHealRestSec = 2;
private const double LowManaFamilyRestSec = 15;
// ── Mana reserve (2026-10-11) ──
// A void mage at 1/383 mana kept casting Corruption at Rampagers and never Stamina to Mana.
// Combat drained mana under what Stamina to Mana itself costs; the server refused it ("You
// don't have enough Mana"), which rested the family 15 s; no mana potion was listed, so no
// vitals flag held the arbiter, and combat spent every point that regenerated on attacks
// that were refused too. Now, for a character that fights with magic:
// - the refill line is the larger of Get Mana At (Top Off Mana idle) and ManaReserveFactor
// times the cost of the best Stamina to Mana it can cast (ManaUnderLine);
// - under it, while Stamina to Mana or a listed mana potion can refill, vitals hold the tick
// (WantsManaNow, part of WantsVitalRecharge, read every tick so combat can't take the
// tick that follows a UseDone) and combat holds its casts (OffensiveCastHold);
// - under Stamina to Mana's cost, the highest level it can pay for goes; with none, mana
// regenerates while attacks wait, and a vital refused for mana rests only LowManaHealRestSec.
// No peace-stance switch to regenerate faster: ACE's stance modifier skips mana
// (Creature.GetStanceMod returns 1.0 for MaxMana), and the switch back would cost the swap.
internal const double ManaReserveFactor = 1.5;
private const double ManaUnavailableMs = 5000;
private const double ManaRefusalMemoryMs = 5000;
private DateTime _manaUnavailableUntil = DateTime.MinValue;
private DateTime _lastManaRefusalAt = DateTime.MinValue;
private bool _manaStarvedLogged;
private int _topS2MId;
private DateTime _topS2MAt = DateTime.MinValue;
/// <summary>Tests: a spell's mana cost instead of the dat's (0 = unknown). FakeHost.Reset sets
/// it to "unknown" so tests don't depend on a portal.dat on the PC.</summary>
internal static Func<int, int>? ManaCostOverride;
/// <summary>Tests: whether a monster is within Monster Range (else CombatManager decides).</summary>
internal Func<bool>? InCombatOverride { get; set; }
private bool InCombatNow() => InCombatOverride?.Invoke()
?? _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
/// <summary>
/// A spell's mana cost: its BaseMana from the portal.dat SpellTable, the most it can cost
/// (ACE Creature.CalculateManaUsage; Mana Conversion only lowers it on a skill roll, so the
/// base is the one number that is sure to be enough). No dat: an estimate from the spell's
/// level. 0 = unknown.
/// </summary>
internal static int SpellManaCost(int spellId)
{
if (spellId == 0) return 0;
if (ManaCostOverride != null) return Math.Max(0, ManaCostOverride(spellId));
if (ComponentDatabase.TryGetSpellBaseMana(spellId, out int mana)) return mana;
int level = SpellTableStub.GetById(spellId)?.Level ?? 0;
return EstimatedManaCost(level);
}
/// <summary>Retail's base mana by spell level (I 10 ... VI 50, VII 70, VIII 80; the dat can differ
/// per spell). Used only when the dat can't be read.</summary>
internal static int EstimatedManaCost(int level) => level switch
{
<= 0 => 0,
<= 7 => level * 10,
_ => 80,
};
/// <summary>The Stamina to Mana level vitals would cast now (0 = none: unknown, or Life Magic
/// not usable). Cached for a second: the arbiter asks every tick.</summary>
private int TopStaminaToManaId()
{
if ((DateTime.Now - _topS2MAt).TotalMilliseconds < 1000) return _topS2MId;
_topS2MAt = DateTime.Now;
_topS2MId = IsSkillUsable(AcSkillType.LifeMagic)
? _spellManager.GetDynamicSelfBuffId("Stamina to Mana Self", AcSkillType.LifeMagic, LevelLacksComponents)
: 0;
return _topS2MId;
}
/// <summary>The mana the reserve keeps for Stamina to Mana: ManaReserveFactor x its cost, never
/// above halfway between the cost and max mana (a small pool would refill when nearly full).
/// 0 = no reserve (no Stamina to Mana, cost unknown, or more than max mana).</summary>
internal int ManaReserve()
{
int cost = SpellManaCost(TopStaminaToManaId());
int max = (int)_vitals.MaxMana;
if (cost <= 0 || max <= 0 || cost >= max) return 0;
int reserve = (int)Math.Ceiling(cost * ManaReserveFactor);
return Math.Min(reserve, cost + (max - cost) / 2);
}
/// <summary>Combat fights with magic (CombatManager's chosen weapon is a wand; before it chose,
/// the stance). A melee character's attacks don't spend mana, so the reserve doesn't hold them.</summary>
private bool FightsWithMagic() => _combatManager?.FightsWithMagic ?? CurrentCombatMode == CombatMode.Magic;
/// <summary>Mana is under the line vitals refill at: the % line (Get Mana At in combat, Top Off
/// Mana idle; 0 = off) or, for a caster, the reserve. <paramref name="line"/>: the line in points.</summary>
internal bool ManaUnderLine(bool inCombat, out int line)
{
line = 0;
int pctLine = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
int max = (int)_vitals.MaxMana;
if (pctLine <= 0 || max <= 0) return false;
line = (int)Math.Ceiling(max * pctLine / 100.0);
bool under = _vitals.ManaPct < pctLine;
if (FightsWithMagic())
{
int reserve = ManaReserve();
if (reserve > line) line = reserve;
if (reserve > 0 && _vitals.CurrentMana < reserve) under = true;
}
return under;
}
/// <summary>Stamina to Mana (not parked by a hard refusal; the short rest after a mana refusal
/// doesn't count) or a listed mana potion can refill mana.</summary>
private bool ManaRefillPossible()
{
if (_settings.UsePotions && HasListedPotion("ManaPotion")) return true;
int id = TopStaminaToManaId();
if (id == 0 || !StaminaAllowsStaminaToMana()) return false;
int family = SpellTableStub.GetById(id)?.Family ?? 0;
return !(family != 0 && _buffFailCooldownUntil.TryGetValue(family, out DateTime until)
&& (until - DateTime.Now).TotalSeconds > LowManaHealRestSec);
}
/// <summary>Stamina lets Stamina to Mana go: over 15%, or a stamina kit or listed stamina potion
/// can bring it there. Not Revitalize: it costs mana itself, and trading mana for stamina and
/// back while attacks wait could keep a caster from attacking for minutes.</summary>
private bool StaminaAllowsStaminaToMana() => _vitals.StaminaPct > 15
|| BestPackStaminaKit() != null
|| (_settings.UsePotions && HasListedPotion("StaminaPotion", "Stamina"));
/// <summary>
/// Mana can't pay for Stamina to Mana: under the cost of its lowest known level when costs are
/// known (the highest level it can pay for is cast first, see AttemptVitalCast), or refused
/// for mana in the last ManaRefusalMemoryMs when they aren't.
/// </summary>
internal bool ManaStarved(out int cost, out string spellName)
{
int id = TopStaminaToManaId();
cost = SpellManaCost(id);
spellName = id != 0 ? SpellTableStub.GetById(id)?.Name ?? "Stamina to Mana" : "Stamina to Mana";
if (id == 0 || _vitals.MaxMana == 0) return false;
if (cost > 0) return _vitals.CurrentMana < cost && AffordableVitalId("Stamina to Mana Self") == 0;
return (DateTime.Now - _lastManaRefusalAt).TotalMilliseconds < ManaRefusalMemoryMs;
}
/// <summary>The highest level of a vital spell whose known cost current mana can pay (a level
/// with an unknown cost counts as payable). 0 = none.</summary>
private int AffordableVitalId(string baseName)
{
uint cur = _vitals.CurrentMana;
return _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic,
id => LevelLacksComponents(id) || SpellManaCost(id) > cur);
}
/// <summary>
/// In combat, a caster's mana under the refill line with something able to refill it (now, or
/// once mana regenerates to Stamina to Mana's cost): vitals want the tick. Read by
/// WantsVitalRecharge every tick, like WantsHealNow, so it doesn't depend on CheckVitals having
/// run (it doesn't while a gesture animates or the client is busy). Backs off ManaUnavailableMs
/// after a check that found nothing able to refill.
/// </summary>
internal bool WantsManaNow()
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return false;
if (DateTime.Now < _manaUnavailableUntil) return false;
if (!InCombatNow() || !FightsWithMagic()) return false;
return ManaUnderLine(true, out _) && ManaRefillPossible();
}
/// <summary>
/// For CombatManager, before an attack or debuff cast: a reason to hold it, or null. Held when
/// mana is under the spell's own cost (it would be refused), or under the refill line while
/// vitals can refill it (Stamina to Mana goes first).
/// </summary>
internal string? OffensiveCastHold(int spellId)
{
if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return null;
uint cur = _vitals.CurrentMana;
int cost = SpellManaCost(spellId);
if (cost > 0 && cur < cost)
return $"mana {cur}/{_vitals.MaxMana} is under {SpellTableStub.GetById(spellId)?.Name ?? "the spell"}'s cost ({cost})";
if (WantsManaNow())
{
ManaUnderLine(true, out int line);
return $"mana {cur}/{_vitals.MaxMana} is under the reserve ({line}): Stamina to Mana goes first";
}
return null;
}
private readonly Dictionary<int, DateTime> _castIssuedAtByFamily = new();
private readonly Dictionary<int, DateTime> _expiryAtCastByFamily = new();
private const double AuditSettleMs = 15_000.0;
@ -669,7 +852,7 @@ public class BuffManager : IDisposable
/// and they need the same mid-cast protection a buff gets. Side-effect free:
/// CheckVitals repopulates these flags every cycle it reaches.
/// </summary>
public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow();
public bool WantsVitalRecharge => _isHealingSelf || _isRechargingMana || _isRechargingStamina || WantsHealNow() || WantsManaNow();
// Health below a heal line wins the arbiter's tick by itself. The flags above are only set on
// a tick where CheckVitals actually ran and acted, and it doesn't run while the client is busy
@ -751,7 +934,7 @@ public class BuffManager : IDisposable
return _kitIsStamina ? LabelStamina : LabelHealing;
if (_isHealingSelf || WantsHealNow()) return LabelHealing;
if (_pendingSpellId != 0) return LabelBuffing;
if (_isRechargingMana) return LabelMana;
if (_isRechargingMana || WantsManaNow()) return LabelMana;
if (_isRechargingStamina) return LabelStamina;
return LabelBuffing;
}
@ -1450,7 +1633,7 @@ public class BuffManager : IDisposable
// Otherwise idle → top up to the HIGH (TopOffHP / TopOffStam /
// TopOffMana) thresholds so we re-engage at full. Thresholds are
// strict "<": set a value to 0 to disable that vital in that mode.
bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
bool inCombat = InCombatNow();
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
@ -1501,12 +1684,44 @@ public class BuffManager : IDisposable
if (HealthUnderAnyLine(curHealthPct, curStamPct))
_healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs);
if (curManaPct < manaThreshold
&& ((curStamPct > 15 && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion")))
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
if (manaLow)
{
_isRechargingMana = true;
return true;
_vitalWhy = "";
if ((curStamPct > 15 && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion"))
{
_isRechargingMana = true;
return true;
}
// Stamina too low for Stamina to Mana: a stamina kit, Revitalize or a potion first,
// whatever Re-stam At says (it may be under 15 or off).
if (curStamPct <= 15 && TopStaminaToManaId() != 0
&& (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina")))
{
_isRechargingStamina = true;
return true;
}
// Mana can't pay for any Stamina to Mana and nothing else refilled it: a caster's
// attacks wait while it regenerates (WantsManaNow holds the arbiter, OffensiveCastHold
// the casts), then Stamina to Mana goes. Not for a melee fighter: its attacks cost none.
if (FightsWithMagic() && ManaStarved(out int s2mCost, out string s2mName))
{
_isRechargingMana = true;
Hold("mana regenerating", $"mana {_vitals.CurrentMana}/{_vitals.MaxMana}, {s2mName} costs {s2mCost}");
if (!_manaStarvedLogged)
{
_manaStarvedLogged = true;
string costText = s2mCost > 0 ? $"under {s2mName}'s cost ({s2mCost})" : $"too low for {s2mName} (refused for mana)";
_host.Log($"[RynthAi] Vitals: mana {_vitals.CurrentMana}/{_vitals.MaxMana} is {costText}: attacks wait, regenerating.");
}
return true;
}
// Nothing can refill it (no Stamina to Mana, parked, no potion): don't hold the bot for it.
if (inCombat) _manaUnavailableUntil = DateTime.Now.AddMilliseconds(ManaUnavailableMs);
}
else _manaStarvedLogged = false;
// 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.
// Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon
@ -1664,6 +1879,22 @@ public class BuffManager : IDisposable
}
}
if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers");
// Stamina to Mana / Revitalize under their cost (the mana reserve, 2026-10-11): the server
// would refuse it. The highest level mana can pay for goes instead; with none, not handled
// (a potion gets its turn, or mana regenerates - CheckVitals). Mana Conversion can lower a
// cost only on a skill roll, so the base cost is the line. A heal still tries: it falls to
// its potion within LowManaHealRestSec if refused.
if (baseName is not ("Heal Self" or "Stamina to Health Self") && _vitals.MaxMana > 0)
{
int cost = SpellManaCost(spellId);
if (cost > 0 && _vitals.CurrentMana < cost)
{
int payable = AffordableVitalId(baseName);
if (payable == 0)
return VitalNo($"mana {_vitals.CurrentMana} is under {SpellTableStub.GetById(spellId)?.Name ?? baseName}'s cost ({cost})");
spellId = payable;
}
}
// Parked after a hard server refusal (see OnChatWindowText) — the same
// per-family cooldown the buff selectors honour.
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
@ -1697,6 +1928,7 @@ public class BuffManager : IDisposable
return VitalNo($"the client refused the cast (spell {spellId})");
}
NoteCastIssued(spellId);
if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again
if (_pendingVitalLabel == LabelHealing)
{
_healSpellIds.Add(spellId);
@ -2140,6 +2372,21 @@ public class BuffManager : IDisposable
return false;
}
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
// parked buff logged on each one - 47,000 lines in 10 minutes on 2026-10-11, so the log
// rotated every few minutes and held nothing from before. Once per buff and reason a minute.
private readonly Dictionary<string, DateTime> _diagSkipLoggedAt = new();
private void DiagSkip(string buff, string line)
{
int cut = line.IndexOf(" — ", StringComparison.Ordinal);
string reason = cut >= 0 ? line.Substring(cut, Math.Min(18, line.Length - cut)) : line;
string key = buff + "|" + reason;
DateTime now = DateTime.Now;
if (_diagSkipLoggedAt.TryGetValue(key, out DateTime at) && (now - at).TotalSeconds < 60) return;
_diagSkipLoggedAt[key] = now;
_host.Log(line);
}
private bool CheckAndCastSelfBuffs()
{
// Auto batch-rebuff: when any buff drops below the configured threshold,
@ -2172,7 +2419,7 @@ public class BuffManager : IDisposable
if (!IsSkillUsable(castSkill))
{
LastBuffSkipReason = $"skill not usable: {buffBaseName} ({castSkill})";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — skill {castSkill} not usable");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' — skill {castSkill} not usable");
continue;
}
@ -2180,14 +2427,14 @@ public class BuffManager : IDisposable
if (spellId == 0)
{
LastBuffSkipReason = $"not known / unresolvable: {buffBaseName}";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' — FindBestSpellId returned 0");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' — FindBestSpellId returned 0");
continue;
}
if (IsBuffActive(spellId))
{
LastBuffSkipReason = $"already active: {buffBaseName} (id={spellId})";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — already active");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — already active");
continue;
}
@ -2200,7 +2447,7 @@ public class BuffManager : IDisposable
&& DateTime.Now < coolUntil)
{
LastBuffSkipReason = $"fail-cooldown: {buffBaseName} (fam={buffFamily}, {(coolUntil - DateTime.Now).TotalSeconds:0}s)";
if (diagnose) _host.Log($"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s");
if (diagnose) DiagSkip(buffBaseName, $"[FR] skip '{buffBaseName}' (id={spellId}) — hard-fail cooldown {(coolUntil - DateTime.Now).TotalSeconds:0}s");
continue;
}
@ -3395,6 +3642,7 @@ public class BuffManager : IDisposable
if (lower.Contains("enough mana"))
{
_cast.Result(null, "not enough mana", atStart: true);
_lastManaRefusalAt = DateTime.Now; // a combat cast's refusal too: ManaStarved with costs unknown
if (_pendingSpellId == 0) return;
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
double restSec = LowManaFamilyRestSec;
@ -3405,11 +3653,13 @@ public class BuffManager : IDisposable
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
// A heal rests only LowManaHealRestSec (2026-10-05): long enough for the mana step
// after it to cast Stamina to Mana or drink, not 15 s with no Heal Self after the
// mana was back (a mage low on mana mid-fight).
bool healSpell = _pendingSpellId == _pendingVitalSpellId && _pendingVitalLabel == LabelHealing;
restSec = healSpell ? LowManaHealRestSec : LowManaFamilyRestSec;
// A vital rests only LowManaHealRestSec. A heal (2026-10-05): long enough for the
// mana step after it to cast Stamina to Mana or drink, not 15 s with no Heal Self
// after the mana was back. Stamina to Mana and Revitalize (2026-10-11): 15 s parked
// the only thing that refills mana, and combat spent what regenerated meanwhile; now
// mana regenerates to its cost while attacks wait (the mana reserve), then it goes.
bool vitalSpell = _pendingSpellId == _pendingVitalSpellId;
restSec = vitalSpell ? LowManaHealRestSec : LowManaFamilyRestSec;
_buffFailCooldownUntil[pendingSpell.Family] = DateTime.Now.AddSeconds(restSec);
}
_host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} - not enough mana; resting the family {restSec:0}s, buffs {LowManaBuffPauseMs / 1000:0}s.");

View file

@ -290,6 +290,45 @@ public partial class CombatManager : IDisposable
public Func<bool>? HoldIdlePeace { get; set; }
private bool _idlePeaceHeldLogged;
/// <summary>
/// RynthAi's mana reserve (BuffManager.OffensiveCastHold): given the attack or debuff spell
/// about to be cast, a reason to hold it (mana under its cost, or under the reserve kept for
/// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11).
/// </summary>
public Func<int, string?>? ManaReserveHold { get; set; }
private bool _manaCastHeld; // AttackWithMagic held its cast for mana this tick
private bool _manaHoldLogged;
// The kind of weapon EquipWeaponAndSetStance last chose (a CombatMode), -1 before it chose.
private int _chosenWeaponMode = -1;
/// <summary>Combat fights with magic: its chosen weapon is a wand (before it chose, the stance).
/// BuffManager's mana reserve holds only a caster's attacks.</summary>
public bool FightsWithMagic => _chosenWeaponMode >= 0
? _chosenWeaponMode == CombatMode.Magic
: CurrentCombatMode == CombatMode.Magic;
/// <summary>True (and logged once per hold) when the mana reserve holds this cast.</summary>
private bool ManaHoldsCast(int spellId)
{
string? why = null;
try { why = ManaReserveHold?.Invoke(spellId); } catch { why = null; }
if (why == null)
{
if (_manaHoldLogged) _host.Log("[CombatCast] mana is back: attacks resume");
_manaHoldLogged = false;
return false;
}
_manaCastHeld = true;
LastCombatSkipReason = "mana-reserve"; // D4 record-only
if (!_manaHoldLogged)
{
_manaHoldLogged = true;
_host.Log($"[CombatCast] attacks wait: {why}");
}
return true;
}
/// <summary>Current combat mode — read live from AC client each access to avoid event-drop drift.</summary>
public int CurrentCombatMode =>
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
@ -434,6 +473,18 @@ public partial class CombatManager : IDisposable
string Name, uint Wcid, int CastCount, uint WeaponId, string Element, int Tier, double Damage, DateTime Expiry,
DateTime Started = default, string? Summon = null, int Id = 0);
// Predicted kills that never happened (player log, 2026-10-11): two Rampagers side by side,
// each cast landing nothing. The casts-to-kill average said one Nether Arc kills a Rampager, so
// every cast#1 was a "predicted kill" and the bot swapped to the other one, and back, for 30
// minutes (~460 swaps, 533 casts since the last kill). Each swap drops the target, which wipes
// the no-damage judge (DropTarget clears the miss streak and the pending verdict, and a new
// target restarts the streak), so the NO DAMAGE report, the flight recorder and the blacklist
// never ran. A monster we swapped off as dead that is fought again is alive: the prediction
// was wrong, so no more predicted swaps off it — the bot stays on it and the judge can count.
private readonly Dictionary<int, DateTime> _predictedSwapAt = new(); // id -> when we swapped off it as a predicted kill
private readonly Dictionary<int, DateTime> _predictionFailedAt = new(); // id -> when it turned out alive: never predicted again
private const double PredictionMemoryMs = 10 * 60_000; // both forget after 10 min
// Ring of recently-fought objects (by id). The single _lastFight* slot only credits a kill
// that lands one-back; when we've advanced PAST the dying mob (rapid multi-mob melee) its
// death message matches neither the current target nor _lastFight, and the kill is lost
@ -866,7 +917,8 @@ public partial class CombatManager : IDisposable
if (!string.IsNullOrEmpty(wo.Name) && _seenMonsterNameToWcid.Count < 256
&& !_seenMonsterNameToWcid.ContainsKey(wo.Name)
&& (!_host.HasObjectIsAttackable || _host.ObjectIsAttackable((uint)wo.Id))
&& _host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)wo.Id, out uint scanWcid) && scanWcid != 0)
&& _host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)wo.Id, out uint scanWcid) && scanWcid != 0
&& !CreatureData.PlayerWeenies.IsPlayerWcid(scanWcid)) // players the cache classed as monsters
_seenMonsterNameToWcid[wo.Name] = scanWcid;
// Allow the currently-engaged target out to DisengageDistance: AC's
@ -1612,8 +1664,92 @@ public partial class CombatManager : IDisposable
_lastSpellCast = DateTime.Now;
}
// ── Position re-sync after casts that land nothing (2026-10-12) ──────────────────────────
// Flight 63260: after a stray stop burst rode with a cast, every projectile cast (Corruption
// VII, Nether Arc VII) was answered - components burned, UseDone - and nothing landed, until a
// real sidestep (12:32:13) ended it. ACE launches projectiles from the caster's SERVER physics
// position and drops a spawn that fails or collides at once without a word; it re-syncs that
// position only when a reported position differs from the last one (Player_Tick
// UpdatePlayerPosition), and standing still reports the same spot. So after
// ResyncAfterMagicMisses magic casts in a row with no damage (any target: swaps between two
// monsters don't reset it), RynthAi takes one short real sidestep - a movement key down and
// up through the client (MoveToState + AutonomousPositions), alternating sides - once the
// server has answered the last cast, and casts nothing until it is done. At most once per
// ResyncCooldownMs.
internal const int ResyncAfterMagicMisses = 3;
internal const double ResyncStepMs = 300;
internal const double ResyncSettleMs = 400;
internal const double ResyncCooldownMs = 30_000;
private const uint MotionSideStepRight = 0x6500000F;
private const uint MotionSideStepLeft = 0x65000010;
private int _magicMissesSinceHit;
private int _resyncState; // 0 idle, 1 wanted, 2 stepping, 3 settling
private DateTime _resyncAt = DateTime.MinValue;
private DateTime _lastResyncAt = DateTime.MinValue;
private uint _resyncMotion;
private bool _resyncLeftNext;
internal int ResyncSteps { get; private set; }
internal bool ResyncActive => _resyncState != 0;
private void NoteMagicMissForResync(int tid)
{
_magicMissesSinceHit++;
if (_resyncState != 0 || _magicMissesSinceHit < ResyncAfterMagicMisses) return;
DateTime now = TargetClock();
if (_lastResyncAt != DateTime.MinValue && (now - _lastResyncAt).TotalMilliseconds < ResyncCooldownMs) return;
if (!_host.HasSetMotion) return;
_resyncState = 1;
_resyncAt = now;
_host.Log($"[CombatCast] {_magicMissesSinceHit} magic casts in a row landed nothing (last at 0x{(uint)tid:X8}) - " +
"one short sidestep to re-sync the server's copy of our position before the next cast");
}
/// <summary>
/// The re-sync sidestep, one step per call (Think, before a cast). True while it runs: no cast.
/// Starts only when no server action is unanswered and the character isn't animating.
/// </summary>
internal bool TickResyncStep()
{
if (_resyncState == 0) return false;
DateTime now = TargetClock();
switch (_resyncState)
{
case 1:
if (ActionPacer.Enabled
&& (ActionPacer.Current(_host) != null || ActionPacer.GestureHolds(_host, "Combat/Resync", HealNeed.None, out _)))
{
if ((now - _resyncAt).TotalMilliseconds > 10_000) { _resyncState = 0; _host.Log("[CombatCast] re-sync sidestep given up: the server never went idle"); }
return true;
}
_resyncMotion = _resyncLeftNext ? MotionSideStepLeft : MotionSideStepRight;
_resyncLeftNext = !_resyncLeftNext;
if (!_host.SetMotionBy("Combat/Resync", _resyncMotion, true)) { _resyncState = 0; return false; }
_resyncState = 2;
_resyncAt = now;
return true;
case 2:
if ((now - _resyncAt).TotalMilliseconds < ResyncStepMs) return true;
_host.SetMotionBy("Combat/Resync", _resyncMotion, false);
_resyncState = 3;
_resyncAt = now;
return true;
default:
if ((now - _resyncAt).TotalMilliseconds < ResyncSettleMs) return true;
_resyncState = 0;
_lastResyncAt = now;
_magicMissesSinceHit = 0;
ResyncSteps++;
_host.Log("[CombatCast] re-sync sidestep done");
return false;
}
}
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
// Damage / health change on the cast we're judging → that cast HIT.
if (targetId == _pendingJudgeTargetId)
_damageSincePendingCast = true;
@ -1744,6 +1880,44 @@ public partial class CombatManager : IDisposable
private DateTime _lastNoDamageReportAt = DateTime.MinValue;
private const double NoDamageReportGapMs = 10 * 60_000; // one report per 10 min per client
// ── What the server said about each combat cast (2026-10-11) ─────────────────────────────
// A player log with 30 minutes of casts that landed nothing could not show what the server
// answered: chat is logged only while a buff is pending ([BuffChat]), never around an attack or
// debuff cast. A resist, a fizzle, an out-of-range or a silent nothing all looked the same.
// Now every combat cast logs the lines that arrive within CastChatTraceMs of its send (the
// incantation, the hit or resist, components, refusals), capped per cast; the monsters'
// swings at us and our evades of them are left out.
private int _castTraceSpellId;
private int _castTraceTargetId;
private DateTime _castTraceAt = DateTime.MinValue;
private int _castTraceLines;
private const double CastChatTraceMs = 4000;
private const int CastChatTraceMaxLines = 8;
internal void StartCastChatTrace(int spellId, int targetId)
{
_castTraceSpellId = spellId;
_castTraceTargetId = targetId;
_castTraceAt = TargetClock();
_castTraceLines = 0;
}
/// <summary>Every chat line goes through here (RynthAiPlugin.OnChatWindowText); logs it when a
/// combat cast went out in the last <see cref="CastChatTraceMs"/>.</summary>
internal void TraceCastChat(string? text, int chatType)
{
if (_castTraceAt == DateTime.MinValue || string.IsNullOrEmpty(text)) return;
double ms = (TargetClock() - _castTraceAt).TotalMilliseconds;
if (ms > CastChatTraceMs) { _castTraceAt = DateTime.MinValue; return; }
if (_castTraceLines >= CastChatTraceMaxLines) return;
string line = text.Trim();
if (line.StartsWith("You evaded ", StringComparison.Ordinal)) return; // their swing, our evade
if (!line.StartsWith("You ", StringComparison.Ordinal) && IncomingDamage.IsMatch(line)) return; // their hit on us
_castTraceLines++;
string spell = SpellTableStub.GetById(_castTraceSpellId)?.Name ?? $"spell {_castTraceSpellId}";
_host.Log($"[CombatChat] +{ms:0} ms after '{spell}' at 0x{(uint)_castTraceTargetId:X8}: type={chatType} '{line}'");
}
private void ReportNoDamageCasts(int tid)
{
DateTime now = DateTime.Now;
@ -1775,8 +1949,9 @@ public partial class CombatManager : IDisposable
bool hit = _damageSincePendingCast;
_pendingJudgeCastAt = DateTime.MinValue;
if (hit) { _consecutiveCastMisses = 0; return; }
if (hit) { _consecutiveCastMisses = 0; _magicMissesSinceHit = 0; return; }
if (CurrentCombatMode == CombatMode.Magic) NoteMagicMissForResync(tid);
_consecutiveCastMisses++;
if (_consecutiveCastMisses >= _settings.BlacklistAttempts)
{
@ -1933,6 +2108,7 @@ public partial class CombatManager : IDisposable
_recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
ForgetScanned(swapId);
_predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed)
// Queue this predicted one-shot so it's CREDITED when its death confirms —
// we may swap away before its KillerNotification. Capture the name LIVE
// from the world filter (_fightTargetName is often empty this early).
@ -2349,6 +2525,7 @@ public partial class CombatManager : IDisposable
_predictKillSwap = false;
if (isRing || _damageStore == null || _fightTargetWcid == 0) return;
if (activeTargetId == 0 || activeTargetId != _fightTargetId) return;
if (PredictionFailed(activeTargetId)) return; // survived a predicted kill — stay on it
if (!HasAlternateTarget(activeTargetId)) return; // nothing to swap to — keep casting
// (A) Casts-to-kill: we've fired the number of casts this wcid typically
@ -2387,6 +2564,56 @@ public partial class CombatManager : IDisposable
return false;
}
/// <summary>
/// True when <paramref name="id"/> survived a predicted kill: we swapped off it as dead and are
/// now casting at it again (the kill-notice match is by name only, so being fought again is the
/// one sure sign). Logs once when that is first seen. Called after each cast at the fight target.
/// </summary>
private bool PredictionFailed(int id)
{
DateTime now = TargetClock();
if (_predictionFailedAt.Count > 0 || _predictedSwapAt.Count > 0)
{
PruneOlderThan(_predictionFailedAt, now);
PruneOlderThan(_predictedSwapAt, now);
}
if (_predictionFailedAt.ContainsKey(id)) return true;
if (!_predictedSwapAt.TryGetValue(id, out DateTime swappedAt)) return false;
_predictedSwapAt.Remove(id);
_predictionFailedAt[id] = now;
float hp = _worldFilter.GetHealthRatio(id);
string health = hp >= 0f ? $"health {hp * 100f:0}%" : "health unknown";
_host.Log($"[RynthAi] Predicted kill of 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' didn't happen: fought again " +
$"{(now - swappedAt).TotalSeconds:0.0} s after the swap ({health}, dealt~{_fightDamage:0} this fight). " +
"No more predicted swaps off it, so its casts are judged for damage.");
return true;
}
private static void PruneOlderThan(Dictionary<int, DateTime> map, DateTime now)
{
List<int>? old = null;
foreach (var kv in map)
if ((now - kv.Value).TotalMilliseconds > PredictionMemoryMs) (old ??= new()).Add(kv.Key);
if (old != null) foreach (int k in old) map.Remove(k);
}
/// <summary>Test seam: a cast at the fight target, then the kill-shot decision (as AttackWithMagic does).</summary>
internal bool CastAndPredictForTest(uint weaponId, string element, int tier)
{
_fightCastCount++;
_lastCastWeaponId = weaponId;
_lastCastElement = element;
_lastCastTier = tier;
EvaluateKillShot(weaponId, element, tier, isRing: false);
bool predicted = _predictKillSwap;
_predictKillSwap = false;
return predicted;
}
/// <summary>Test seam: the confirmed predicted-kill swap off the fight target.</summary>
internal void PredictedSwapForTest() => ExecuteDeferredKillSwap();
/// <summary>Floor between attack commands for the first cast at a new target when the server
/// gates are available (see <see cref="AttackIntervalMs"/>). Only bounds how fast a refused
/// cast could be retried; a refusal sets the target as the last attacked, so the retry waits
@ -2784,6 +3011,15 @@ public partial class CombatManager : IDisposable
return true;
}
// Casts landing nothing: one short real sidestep re-syncs the server's copy of our
// position (TickResyncStep, 2026-10-12); nothing is cast while it runs.
if (CurrentCombatMode == CombatMode.Magic && TickResyncStep())
{
LastCombatSkipReason = "position-resync";
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// MAGIC and MISSILE: the server turns the player to the target itself,
// as retail did — ACE Rotate(target) before a targeted cast (and again
// after the windup if needed) and before the first missile shot and
@ -2897,6 +3133,13 @@ public partial class CombatManager : IDisposable
_tickWait = CombatLatencyTracker.Wait.Face;
return true;
}
// Held for mana (the reserve, or under the spell's cost): nothing was sent, so
// it isn't an attack either; the next tick asks again.
if (_manaCastHeld)
{
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
// Don't restore the physical weapon on top of a cast just issued this tick
// (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would
@ -4124,6 +4367,7 @@ public partial class CombatManager : IDisposable
int desiredMode = IsWandObject(weaponObj) ? CombatMode.Magic
: weaponObj.ObjectClass == AcObjectClass.MissileWeapon ? CombatMode.Missile
: CombatMode.Melee;
_chosenWeaponMode = desiredMode;
bool diagNow = (DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5;
@ -5054,6 +5298,7 @@ public partial class CombatManager : IDisposable
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
_manaCastHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -5133,11 +5378,13 @@ public partial class CombatManager : IDisposable
spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier);
if (spellId == 0) continue;
if (ManaHoldsCast(spellId)) return; // mana reserve: Stamina to Mana first, or regenerate
try
{
_host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
MarkCombatCastIssued();
StartCastChatTrace(spellId, activeTargetId);
_lastSpellCast = DateTime.Now;
_lastCastWasRing = false;
_pendingDebuffKey = debuffKey;
@ -5189,6 +5436,7 @@ public partial class CombatManager : IDisposable
}
// A ring or a wall hits several monsters: its damage isn't the fight target's alone.
bool multiTarget = isRing || castShape == ShapeWall;
if (offensiveSpellId != 0 && ManaHoldsCast(offensiveSpellId)) return; // mana reserve
if (offensiveSpellId != 0)
{
LastCombatSkipReason = "cast"; // D4 record-only: offensive cast issued this tick
@ -5202,6 +5450,7 @@ public partial class CombatManager : IDisposable
{
_host.CastSpellFor((uint)activeTargetId, offensiveSpellId, "Combat", SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
MarkCombatCastIssued();
StartCastChatTrace(offensiveSpellId, activeTargetId);
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
_lastSpellCast = DateTime.Now;

View file

@ -97,6 +97,18 @@ internal static class ComponentDatabase
return false;
}
// spellId → BaseMana from the same SpellTable pass: the most a cast can cost (ACE
// Creature.CalculateManaUsage starts from it; Mana Conversion only lowers it on a roll).
private static readonly Dictionary<int, int> _spellBaseMana = new();
/// <summary>A spell's base mana cost from the portal.dat SpellTable. False when the dat
/// couldn't be read or the spell isn't in it.</summary>
public static bool TryGetSpellBaseMana(int spellId, out int mana)
{
EnsureLoaded();
return _spellBaseMana.TryGetValue(spellId, out mana) && mana > 0;
}
private static bool _loaded;
private static readonly object _lock = new();
private static Action<string>? _log;
@ -339,15 +351,16 @@ internal static class ComponentDatabase
{
if (r.BaseStream.Position + 4 > raw.Length) break;
uint spellId = r.ReadUInt32();
uint[] comps = ReadSpellBaseFormula(r, out uint school, out uint power);
uint[] comps = ReadSpellBaseFormula(r, out uint school, out uint power, out uint baseMana);
_spellComps[(int)spellId] = comps;
_spellMeta[(int)spellId] = ((int)school, (int)power);
_spellBaseMana[(int)spellId] = (int)baseMana;
n++;
}
return n;
}
private static uint[] ReadSpellBaseFormula(BinaryReader r, out uint school, out uint power)
private static uint[] ReadSpellBaseFormula(BinaryReader r, out uint school, out uint power, out uint baseMana)
{
byte[] nameB = ReadObf(r); Align(r);
byte[] descB = ReadObf(r); Align(r);
@ -356,7 +369,7 @@ internal static class ComponentDatabase
r.ReadUInt32(); // Icon
r.ReadUInt32(); // Category
r.ReadUInt32(); // Bitfield
r.ReadUInt32(); // BaseMana
baseMana = r.ReadUInt32(); // BaseMana (the mana cost before Mana Conversion)
r.ReadSingle(); // BaseRangeConstant
r.ReadSingle(); // BaseRangeMod
power = r.ReadUInt32(); // Power (the spell's difficulty; ACE's scroll rule reads it)

View file

@ -148,6 +148,34 @@ internal static class WeaponList
return list;
}
/// <summary>Appended to a listed item's name in the pickers when it isn't carried (<see cref="MissingIds"/>).</summary>
public const string MissingSuffix = " (missing)";
/// <summary>
/// The listed items the character no longer carries: neither in the pack
/// (<paramref name="inventory"/>, WorldObjectCache.GetInventory) nor wielded. The client
/// can still know an object that left (sold, given, on a mule), so the saved name alone
/// looked fine while combat couldn't use it (2026-10-11, Drakkon's buff wand 0x8000EF07,
/// shown as "Wand"). An empty inventory means it isn't known yet (logging in): nothing is
/// reported missing then. For the Items panel's warning and the pickers' "(missing)".
/// </summary>
public static HashSet<int> MissingIds(IEnumerable<ItemRule> rules, IEnumerable<WorldObject> inventory,
Func<int, WorldObject?> lookup, Func<WorldObject, bool> isWielded)
{
var missing = new HashSet<int>();
var carried = new HashSet<int>();
foreach (var wo in inventory) carried.Add(wo.Id);
if (carried.Count == 0) return missing;
foreach (var r in rules)
{
if (r.Id == 0 || carried.Contains(r.Id)) continue;
var wo = lookup(r.Id);
if (wo != null && isWielded(wo)) continue;
missing.Add(r.Id);
}
return missing;
}
/// <summary>
/// The Items panel's edited list, mapped onto the saved one by id: the saved name stays
/// (the panel shows the full name; entries are matched and saved by id), an element the
@ -194,19 +222,37 @@ internal static class WeaponList
{
unlisted = false;
int first = 0;
bool anyListedWand = false;
bool anyListedCarried = false;
// Only a wand the character still carries (in the pack or in hand). A listed wand the
// client saw once but that left the pack (sold, given, on a mule) used to be returned:
// the server ignores a wield of it, every buff got parked "fighting unbuffed", and
// Drakkon died over and over (2026-10-11, wand 0x8000EF07 shown as '?').
var pack = inventory as ICollection<WorldObject> ?? new List<WorldObject>(inventory);
var carried = new HashSet<int>();
foreach (var wo in pack) carried.Add(wo.Id);
var gone = new List<(ItemRule Rule, WorldObject Wo)>();
foreach (var r in rules)
{
var wo = lookup(r.Id);
if (wo == null) continue;
if (!IsWand(wo)) continue;
anyListedWand = true;
if (isWielded(wo)) return r.Id;
if (!carried.Contains(wo.Id)) { gone.Add((r, wo)); continue; }
anyListedCarried = true;
if (first == 0) first = r.Id;
}
if (first != 0) return first;
if (anyListedWand || !allowUnlisted) return 0;
foreach (var wo in inventory)
// A listed wand no longer carried: another of the same name in the pack stands in for it.
foreach (var (r, wo) in gone)
{
string name = !string.IsNullOrWhiteSpace(r.Name) ? r.Name : wo.Name ?? "";
if (name.Length < 3 || name == "?") continue;
foreach (var p in pack)
if (IsWand(p) && string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
return p.Id;
}
if (anyListedCarried || !allowUnlisted) return 0;
foreach (var wo in pack)
if (wo.ObjectClass == AcObjectClass.WandStaffOrb)
{
unlisted = true;