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;

View file

@ -28,7 +28,8 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// </summary>
internal sealed class CreatureProfileStore
{
internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
/// <summary>Where creatures.json lives (the offline tests point it at a scratch folder).</summary>
internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
private const string FileName = "creatures.json";
private readonly object _lock = new();
@ -102,7 +103,12 @@ internal sealed class CreatureProfileStore
if (dict != null)
{
foreach (var kv in dict)
_byKey[kv.Key] = kv.Value;
{
// Player characters appraised before e52ccc8 (wcid 1 / 4) are not
// creatures: dropped, and the next save writes the file without them.
if (kv.Value != null && PlayerWeenies.IsPlayerWcid(kv.Value.Wcid)) { _dirty = true; continue; }
_byKey[kv.Key] = kv.Value!;
}
}
_lastSavedJson = json;
}
@ -212,6 +218,7 @@ internal sealed class CreatureProfileStore
public void Upsert(CreatureProfile sample, int difficulty = 0)
{
if (string.IsNullOrEmpty(sample.Name)) return;
if (PlayerWeenies.IsPlayerWcid(sample.Wcid)) return; // a player character, never creature data
lock (_lock)
{

View file

@ -159,6 +159,9 @@ internal sealed class MonsterDamageStore
private static string Num(double d) => d.ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>Nothing is recorded under wcid 0 or a player character's weenie (<see cref="PlayerWeenies"/>).</summary>
private static bool NotMonster(uint wcid) => wcid == 0 || PlayerWeenies.IsPlayerWcid(wcid);
/// <summary>Point the store at a character's folder and load its file. Safe to call again on character change.</summary>
public void SetCharacter(string charFolder)
{
@ -341,9 +344,25 @@ internal sealed class MonsterDamageStore
{
// Corrupt file — start fresh; it rewrites on next save.
}
// Rows a player character left behind (an appraised player or your own character
// listed as a monster) go, and the next save writes the file without them.
if (DropPlayerRowsLocked()) _dirty = true;
}
}
/// <summary>Removes every row under a player weenie. True when any went. Caller holds _lock.</summary>
private bool DropPlayerRowsLocked()
{
var gone = new List<uint>();
foreach (uint w in _byWcid.Keys) if (PlayerWeenies.IsPlayerWcid(w)) gone.Add(w);
foreach (uint w in gone) _byWcid.Remove(w);
var tierGone = new List<(uint, int)>();
foreach (var k in _byTier.Keys) if (PlayerWeenies.IsPlayerWcid(k.Wcid)) tierGone.Add(k);
foreach (var k in tierGone) _byTier.Remove(k);
return gone.Count > 0 || tierGone.Count > 0;
}
/// <summary>One AH/AD/AU/APK/AT row (a difficulty tier above 0). Caller holds _lock.</summary>
private void LoadTierRow(string[] f)
{
@ -529,7 +548,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordHit(uint weaponId, uint wcid, string name, string element, int tier, double damage, bool crit)
{
if (wcid == 0 || damage <= 0) return;
if (NotMonster(wcid) || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
@ -561,7 +580,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordKill(uint weaponId, uint wcid, string name, string element, int tier, int castCount, double totalDamage)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
int d = Difficulty;
lock (_lock)
{
@ -607,7 +626,7 @@ internal sealed class MonsterDamageStore
/// <summary>An attack or cast that did nothing: evaded, or the spell was resisted.</summary>
public void RecordMiss(uint weaponId, uint wcid, string name)
{
if (wcid == 0 || weaponId == 0) return;
if (NotMonster(wcid) || weaponId == 0) return;
int d = Difficulty;
lock (_lock)
{
@ -623,7 +642,7 @@ internal sealed class MonsterDamageStore
/// </summary>
public void RecordFightTime(uint weaponId, uint wcid, string name, double seconds, string? summonElement)
{
if (wcid == 0 || seconds <= 0 || seconds > 600) return;
if (NotMonster(wcid) || seconds <= 0 || seconds > 600) return;
int d = Difficulty;
lock (_lock)
{
@ -650,7 +669,7 @@ internal sealed class MonsterDamageStore
/// <summary>The monster hit us for <paramref name="damage"/> of <paramref name="element"/>.</summary>
public void RecordTaken(uint wcid, string name, string element, double damage)
{
if (wcid == 0 || damage <= 0) return;
if (NotMonster(wcid) || damage <= 0) return;
int d = Difficulty;
lock (_lock)
{
@ -758,7 +777,7 @@ internal sealed class MonsterDamageStore
/// collapsed row shows the LATEST tier used. In-memory only (not persisted) — resets per session.</summary>
public void NoteCast(uint wcid, int tier, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -859,7 +878,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (or clear, with hp &lt;= 0) the manual HP override for a wcid. Persists on next save.</summary>
public void SetManualHp(uint wcid, double hp, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -880,7 +899,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (0 clears) the per-monster weapon override. Persists on next save.</summary>
public void SetManualWeapon(uint wcid, uint weaponId, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -901,7 +920,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set ("" = Auto) the per-monster pet choice. Persists on next save.</summary>
public void SetManualPet(uint wcid, string choice, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);
@ -922,7 +941,7 @@ internal sealed class MonsterDamageStore
/// <summary>Set (0 clears) the per-monster offhand override. Persists on next save.</summary>
public void SetManualOffhand(uint wcid, uint offhandId, string? name = null)
{
if (wcid == 0) return;
if (NotMonster(wcid)) return;
lock (_lock)
{
var p = Get(wcid);

View file

@ -0,0 +1,25 @@
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Weenie class ids that only player characters use, so they are never monster data: the
/// Damage tab, monster_damage.txt and creatures.json skip them, and the stores drop rows
/// already saved under them when they load.
///
/// On ACE every player character is weenie 1 ("human") whatever the heritage (heritage is a
/// property), and admin / sentinel characters ("+Name") are weenie 4. creatures.json had
/// ~130 player characters under these two (appraisals from before e52ccc8), and no monster in
/// the shipped creature_weakness.json uses either.
/// </summary>
internal static class PlayerWeenies
{
public const uint Human = 1;
public const uint Admin = 4;
public static bool IsPlayerWcid(uint wcid) => wcid == Human || wcid == Admin;
/// <summary>
/// Player object ids (ACE's player guid range, 0x50000001-0x6FFFFFFF). Monsters are
/// dynamic (0x8xxxxxxx) or landblock statics (0x7xxxxxxx), never in this range.
/// </summary>
public static bool IsPlayerGuid(uint objectId) => objectId >= 0x50000000u && objectId < 0x70000000u;
}

View file

@ -282,6 +282,19 @@ internal sealed class LegacyDashboardRenderer
return withElement ? WeaponNames.WithElement(name, r.Element) : name;
}
/// <summary>The listed weapons the character no longer carries (WeaponList.MissingIds); none before the cache is set.</summary>
internal HashSet<int> MissingWeaponIds()
{
var cache = _weaponCache;
if (cache == null) return new HashSet<int>();
return WeaponList.MissingIds(_settings.ItemRules ?? new List<ItemRule>(), cache.GetInventory(),
id => cache[id], wo => WorldObjectCache.IsWieldedByPlayer(_host, wo));
}
/// <summary>A picker's name for a listed weapon: <see cref="WeaponDisplayName"/> plus " (missing)" when it isn't carried.</summary>
private string WeaponPickerName(ItemRule r, HashSet<int> missing) =>
WeaponDisplayName(r, withElement: true) + (missing.Contains(r.Id) ? WeaponList.MissingSuffix : "");
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr);
public void SetAutoVendorStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status);
public void SetAutoTradeStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoTradeStatusProvider(status);
@ -788,12 +801,13 @@ internal sealed class LegacyDashboardRenderer
{
try
{
var missing = MissingWeaponIds();
var payload = new MonstersBridgePayload
{
Rules = _settings.MonsterRules ?? new List<MonsterRule>(),
// Full names with the element ("Silver Wand (Fire)"); saved choices are by id.
Items = (_settings.ItemRules ?? new List<ItemRule>())
.Select(r => new MonsterBridgeItem { Id = r.Id, Name = WeaponDisplayName(r, withElement: true) }).ToList(),
.Select(r => new MonsterBridgeItem { Id = r.Id, Name = WeaponPickerName(r, missing) }).ToList(),
CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty,
};
@ -833,6 +847,7 @@ internal sealed class LegacyDashboardRenderer
try
{
var items = _settings.ItemRules ?? new List<ItemRule>();
var missing = MissingWeaponIds();
var sb = new System.Text.StringBuilder();
sb.Append('[');
bool first = true;
@ -840,7 +855,7 @@ internal sealed class LegacyDashboardRenderer
{
if (!first) sb.Append(',');
first = false;
sb.Append("{\"id\":").Append(it.Id).Append(",\"name\":").Append(JsonString(WeaponDisplayName(it, withElement: true))).Append('}');
sb.Append("{\"id\":").Append(it.Id).Append(",\"name\":").Append(JsonString(WeaponPickerName(it, missing))).Append('}');
}
sb.Append(']');
return sb.ToString();
@ -1331,6 +1346,8 @@ internal sealed class LegacyDashboardRenderer
ManaTapMinMana = _settings.ManaTapMinMana,
ManaStoneKeepCount = _settings.ManaStoneKeepCount,
CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty,
// The engine's Items face marks these "(missing)"; display only (ApplyItemsJson ignores it).
MissingIds = MissingWeaponIds().OrderBy(id => id).ToList(),
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.ItemsBridgePayload);
}
@ -2949,6 +2966,7 @@ internal sealed class LegacyDashboardRenderer
sb.Append("\"children\":"); AppendMetaRuleArray(sb, r.Children ?? new List<MetaRule>()); sb.Append(',');
sb.Append("\"actionChildren\":"); AppendMetaRuleArray(sb, r.ActionChildren ?? new List<MetaRule>()); sb.Append(',');
sb.Append("\"enabled\":").Append(r.Enabled ? "true" : "false").Append(',');
if (!string.IsNullOrEmpty(r.Name)) { sb.Append("\"name\":\""); AppendEscaped(sb, r.Name); sb.Append("\","); }
long ms = r.LastFiredAt == DateTime.MinValue ? 99999L : (long)(DateTime.Now - r.LastFiredAt).TotalMilliseconds;
sb.Append("\"lastFiredMs\":").Append(ms.ToString(System.Globalization.CultureInfo.InvariantCulture));
sb.Append('}');
@ -3069,7 +3087,8 @@ internal sealed class LegacyDashboardRenderer
case "update_rule":
// The engine's editor saves every change (2026-10-05): keep the running rule's
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule)))
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule),
keepName: cmd.Rule.Name == null))
TryAutoSaveMetaCmd();
break;
@ -3103,6 +3122,7 @@ internal sealed class LegacyDashboardRenderer
{
var copy = DtoToMetaRule(cmd.Rule);
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
if (cmd.Rule.Name == null) copy.Name = _settings.MetaRules[cmd.Index].Name;
_settings.MetaRules.Insert(cmd.Index + 1, copy);
TryAutoSaveMetaCmd();
}
@ -3162,6 +3182,7 @@ internal sealed class LegacyDashboardRenderer
Action = (MetaActionType)dto.Action,
ActionData = dto.ActionData ?? "",
Enabled = dto.Enabled,
Name = AfFileWriter.OneLine(dto.Name),
};
foreach (var c in dto.Children ?? new List<MetaRuleDto>())
r.Children.Add(DtoToMetaRule(c));

View file

@ -326,6 +326,7 @@ internal sealed class LegacyMetaUi
ActionData = rule.ActionData,
CallReturnState = rule.CallReturnState,
ChatColors = rule.ChatColors,
Name = rule.Name,
Children = CloneChildren(rule.Children),
ActionChildren = CloneChildren(rule.ActionChildren)
};
@ -1025,6 +1026,7 @@ internal sealed class LegacyMetaUi
ActionData = r.ActionData,
CallReturnState = r.CallReturnState,
ChatColors = r.ChatColors,
Name = r.Name,
Children = CloneChildren(r.Children),
ActionChildren = CloneChildren(r.ActionChildren)
});

View file

@ -758,6 +758,9 @@ public sealed class ItemsBridgePayload
public int ManaTapMinMana { get; set; }
public int ManaStoneKeepCount { get; set; }
public string CurrentTargetName { get; set; } = string.Empty;
/// <summary>Listed weapons the character no longer carries (not in the pack, not wielded), by
/// id: the engine's Items face shows them as missing. Display only, never read back.</summary>
public List<int> MissingIds { get; set; } = new();
}
// ── Nav bridge types ─────────────────────────────────────────────────────────
@ -1097,6 +1100,11 @@ public sealed class MetaRule
/// (the property initializer runs, so backward-compatible).</summary>
public bool Enabled { get; set; } = true;
/// <summary>A name to find the rule by in the Meta panel (optional; only top-level rules have
/// one). Saved in .af as a "~~ @name ..." line before the rule's IF: (a plain comment to
/// other tools, like "~~ @disabled"); .met has no place for it.</summary>
public string Name { get; set; } = string.Empty;
[JsonIgnore]
public bool HasFired { get; set; }

View file

@ -12,6 +12,9 @@ internal sealed class MetaRuleDto
public List<MetaRuleDto> Children { get; set; } = new();
public List<MetaRuleDto> ActionChildren { get; set; } = new();
public bool Enabled { get; set; } = true;
/// <summary>The rule's name; null from an engine without rule names (an update then keeps the
/// name the rule has, so a mismatched engine never wipes names).</summary>
public string? Name { get; set; }
}
internal sealed class MetaCommand

View file

@ -86,7 +86,10 @@ public sealed partial class RynthAiPlugin
return true;
case "quit":
case "exit":
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/quit");
// Close the client (also /ub quit|exit, which land here). "/quit" is not an AC
// client command and did nothing; the engine's /rc quit closes the client the way
// its close button does, logging the character off.
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit");
return true;
// ── Send a chat line / slash command (VTank /mt send) ────────────

View file

@ -99,6 +99,7 @@ internal static class AfFileParser
idx++; // consume STATE: line
bool pendingDisabled = false; // set by a "~~ @disabled" marker line
string pendingName = ""; // set by a "~~ @name ..." marker line
while (idx < lines.Length)
{
string trimmed = lines[idx].TrimStart();
@ -113,6 +114,8 @@ internal static class AfFileParser
{
if (trimmed.Equals("~~ @disabled", StringComparison.OrdinalIgnoreCase))
pendingDisabled = true;
else if (TryRuleName(trimmed, out string name))
pendingName = name;
idx++;
continue;
}
@ -120,8 +123,9 @@ internal static class AfFileParser
// Look for IF: line
if (trimmed.StartsWith("IF:"))
{
var rule = new MetaRule { State = stateName, Enabled = !pendingDisabled };
var rule = new MetaRule { State = stateName, Enabled = !pendingDisabled, Name = pendingName };
pendingDisabled = false;
pendingName = "";
int ifIndent = CountLeadingTabs(lines[idx]);
ParseIfBlock(lines, ref idx, rule, ifIndent);
rules.Add(rule);
@ -133,6 +137,19 @@ internal static class AfFileParser
}
}
/// <summary>"~~ @name Rebuff when low" (AfFileWriter's rule name line): the name, trimmed.
/// "~~ @names..." or an empty "~~ @name" is just a comment.</summary>
internal static bool TryRuleName(string trimmedLine, out string name)
{
name = "";
const string marker = "~~ @name";
if (!trimmedLine.StartsWith(marker, StringComparison.OrdinalIgnoreCase)) return false;
string rest = trimmedLine.Substring(marker.Length);
if (rest.Length == 0 || !char.IsWhiteSpace(rest[0])) return false;
name = rest.Trim();
return name.Length > 0;
}
private static void ParseIfBlock(string[] lines, ref int idx, MetaRule rule, int ifIndent)
{
// Parse condition from IF: line

View file

@ -65,10 +65,20 @@ internal static class AfFileWriter
// ── Rule writing ────────────────────────────────────────────────────────
/// <summary>A rule name on one line (it is written as a "~~ @name" comment line).</summary>
internal static string OneLine(string? text)
{
if (string.IsNullOrEmpty(text)) return "";
return text.Replace("\r", " ").Replace("\n", " ").Replace("\t", " ").Trim();
}
private static void WriteRule(TextWriter writer, MetaRule rule)
{
// Disabled marker (backward-compatible: a plain ~~ comment to old
// parsers, recognised by AfFileParser to set Enabled=false).
// Name and disabled markers (backward-compatible: plain ~~ comments to old
// parsers and other tools; AfFileParser reads them back).
string name = OneLine(rule.Name);
if (name.Length > 0)
writer.WriteLine("\t~~ @name " + name);
if (!rule.Enabled)
writer.WriteLine("\t~~ @disabled");

View file

@ -16,15 +16,22 @@ namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// Evaluates RynthAi expressions.
///
/// Follows the UtilityBelt expression reference (utilitybelt.gitlab.io/docs/expressions).
///
/// Syntax:
/// Infix operators: == > < >= <= + - * / % # &amp;&amp; || ~ &lt;&lt; >> &amp; ^ |
/// Infix operators: == != > < >= <= + - * / % # &amp;&amp; || ~ &lt;&lt; >> &amp; ^ |
/// (&amp;&amp; and || skip the side that can't change the answer)
/// Function calls: funcname[arg1, arg2, ...] (args can be nested expressions)
/// Variables: $name is shorthand for getvar[name]
/// Literals: plain numbers (decimal or 0x hex) or identifiers
/// Sequences: expr; expr; ... (value of the last)
/// Variables: $name / @name / &amp;name = getvar / getpvar / getgvar[name];
/// $name = value assigns; x{i}, x{key}, x{a:b}, $x[a:b], text[a:b]
/// Literals: numbers (decimal or 0x hex), true/false (1/0), `backtick text`,
/// bare text of words and spaces, \x escapes one character
///
/// Boolean convention: "0" and "" are false, everything else is true.
/// All values are strings internally; numeric coercion happens per-operator.
/// Lists are stored by reference; variables hold a list handle (e.g. "L:0").
/// Lists are text ("[a,b]"); the list functions that change a list write it back to the
/// variable it came from. Dictionaries and stopwatches are handles ("D:0", "SW:0").
/// </summary>
internal sealed class ExpressionEngine
{
@ -36,9 +43,42 @@ internal sealed class ExpressionEngine
// Lists are value-typed: serialized as "[item1,item2,...]" strings — no backing store.
// Dict store: handle → (key → value). Handles look like "D:0", "D:1", …
// Dicts are ephemeral: cleared at the start of each top-level Evaluate call.
// A dict lives as long as something holds its handle: "setvar[myDict,dictcreate[]]" and
// later "dictadditem[$myDict,foo,1]" is the reference's own pattern. (Dicts used to be
// cleared after every top-level evaluation and the ids restarted at D:0, so a stored handle
// was dead or, worse, named a newer, unrelated dict.) Unreferenced ones are swept once the
// store grows past _dictSweepAt; handles are never reused.
private readonly Dictionary<string, Dictionary<string, string>> _dicts = new(StringComparer.Ordinal);
private int _nextDictId;
private const int DictSweepMin = 256;
private int _dictSweepAt = DictSweepMin;
private static readonly Regex DictHandleRx = new(@"D:\d+", RegexOptions.CultureInvariant);
/// <summary>Drops dicts no variable (memory, persistent, global), option, pending delayexec
/// or live dict refers to. Runs only between top-level evaluations, so no temporary of an
/// evaluation in progress is lost.</summary>
private void SweepDicts()
{
var live = new HashSet<string>(StringComparer.Ordinal);
var todo = new Queue<string>();
void Scan(string? s)
{
if (string.IsNullOrEmpty(s) || s.IndexOf("D:", StringComparison.Ordinal) < 0) return;
foreach (Match m in DictHandleRx.Matches(s))
if (_dicts.ContainsKey(m.Value) && live.Add(m.Value)) todo.Enqueue(m.Value);
}
foreach (string v in _variables.Values) Scan(v);
if (_pvars != null) foreach (string v in _pvars.Values) Scan(v);
if (_gvars != null) foreach (string v in _gvars.Values) Scan(v);
foreach (string v in _options.Values) Scan(v);
foreach (var (_, expr) in _delayedExecs) Scan(expr);
while (todo.Count > 0)
foreach (var (k, v) in _dicts[todo.Dequeue()]) { Scan(k); Scan(v); }
foreach (string h in _dicts.Keys.ToList())
if (!live.Contains(h)) _dicts.Remove(h);
_dictSweepAt = Math.Max(DictSweepMin, live.Count * 2);
}
private int _evalDepth;
// Hard recursion caps. A .NET StackOverflowException is uncatchable and
@ -177,10 +217,10 @@ internal sealed class ExpressionEngine
/// </summary>
public string Evaluate(string expression)
{
string expr = expression?.Trim() ?? "";
string expr = TrimArg(expression ?? "");
if (expr.Length == 0) return "";
if (_evalDepth >= MaxEvalDepth) return "ERR:Depth:max recursion exceeded";
if (_evalDepth == 0) { _dicts.Clear(); _nextDictId = 0; _parenDepth = 0; }
if (_evalDepth == 0) { _parenDepth = 0; if (_dicts.Count > _dictSweepAt) SweepDicts(); }
_evalDepth++;
try { return new Parser(this, expr).Run(); }
catch (Exception ex) { return $"ERR:{ex.GetType().Name}:{ex.Message}"; }
@ -208,9 +248,12 @@ internal sealed class ExpressionEngine
// ── Lazy (only the taken branch is evaluated) ─────────────────────────
if (funcName == "iif")
{
// "If the first parameter is false or not a number, returns the third argument":
// text is not true here (iif[abc,yes,no] is no). The reference also evaluates both
// branches; we still evaluate only the chosen one (no meta relies on both running).
var raw = SplitArgs(argsStr);
if (raw.Count < 2) return "";
return ToBool(Evaluate(raw[0]))
return IsNumber(Evaluate(raw[0]), out double c) && c != 0
? Evaluate(raw[1])
: (raw.Count >= 3 ? Evaluate(raw[2]) : "");
}
@ -238,6 +281,9 @@ internal sealed class ExpressionEngine
// Raw expression template for higher-order list functions (not pre-evaluated).
string Tmpl(int i) => i < rawArgs.Count ? StripBackticks(rawArgs[i]) : "";
// A name, pattern, state, setting or format argument (see TextArg).
string Text(int i) => i < rawArgs.Count ? TextArg(rawArgs[i]) : "";
return funcName switch
{
// ── Session variables ──────────────────────────────────────────────
@ -302,19 +348,21 @@ internal sealed class ExpressionEngine
// ── List functions ────────────────────────────────────────────────
"listcreate" => EvalListCreate(rawArgs),
"listadd" => EvalListAdd(A(0), A(1)),
"listinsert" => EvalListInsert(A(0), A(1), A(2)),
"listremove" => EvalListRemove(A(0), A(1)),
"listremoveat" => EvalListRemoveAt(A(0), A(1)),
// These change the list (the reference: "Returns the list object"). A list is text
// here, so the changed list is written back to the variable it came from.
"listadd" => ListOp(rawArgs, A(0), l => EvalListAdd(l, A(1))),
"listinsert" => ListOp(rawArgs, A(0), l => EvalListInsert(l, A(1), A(2))),
"listremove" => ListOp(rawArgs, A(0), l => EvalListRemove(l, A(1))),
"listremoveat" => ListOp(rawArgs, A(0), l => EvalListRemoveAt(l, A(1))),
"listgetitem" => EvalListGetItem(A(0), A(1)),
"listcontains" => EvalListContains(A(0), A(1)),
"listindexof" => EvalListIndexOf(A(0), A(1)),
"listlastindexof" => EvalListLastIndexOf(A(0), A(1)),
"listcopy" => EvalListCopy(A(0)),
"listreverse" => EvalListReverse(A(0)),
"listpop" => EvalListPop(A(0), rawArgs.Count >= 2 ? A(1) : "-1"),
"listpop" => EvalListPop(rawArgs, A(0), rawArgs.Count >= 2 ? A(1) : "-1"),
"listcount" => EvalListCount(A(0)),
"listclear" => EvalListClear(A(0)),
"listclear" => ListOp(rawArgs, A(0), EvalListClear),
"listfromrange" => EvalListFromRange(A(0), A(1)),
// Higher-order: expression arg is a raw template evaluated per iteration
@ -341,17 +389,17 @@ internal sealed class ExpressionEngine
"wobjectfindall" => EvalWobjectFindAll(),
"wobjectfindallbyobjectclass" => EvalWobjectFindAllByObjectClass(A(0)),
"wobjectfindallbytemplatetype" => EvalWobjectFindAllByTemplateType(A(0)),
"wobjectfindallbynamerx" => EvalWobjectFindAllByNameRx(Tmpl(0)),
"wobjectfindallbynamerx" => EvalWobjectFindAllByNameRx(Text(0)),
"wobjectfindallinventory" => EvalWobjectFindAllInventory(),
"wobjectfindalllandscape" => EvalWobjectFindAllLandscape(),
"wobjectfindallinventorybytemplatetype" => EvalWobjectFindAllInventoryByTemplateType(A(0)),
"wobjectfindallinventorybyobjectclass" => EvalWobjectFindAllInventoryByObjectClass(A(0)),
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)),
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Text(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Text(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Text(0)),
"wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)),
"wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Text(0)),
"wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)),
"wobjectgetselection" => EvalWobjectGetSelection(),
"wobjectgetplayer" => EvalWobjectGetPlayer(),
@ -366,7 +414,7 @@ internal sealed class ExpressionEngine
"wobjectfindnearestmonster" => EvalWobjectFindNearestMonster(),
"wobjectfindbyid" => EvalWobjectFindById(A(0)),
"wobjectfindnearestbyobjectclass" => EvalWobjectFindNearestByObjectClass(A(0)),
"wobjectfindnearestbynameandobjectclass" => EvalWobjectFindNearestByNameAndObjectClass(A(0), Tmpl(1)),
"wobjectfindnearestbynameandobjectclass" => EvalWobjectFindNearestByNameAndObjectClass(A(0), Text(1)),
"wobjectgetisdooropen" => EvalWobjectGetIsDoorOpen(A(0)),
"wobjectgetphysicsstate" => EvalWobjectGetPhysicsState(A(0)),
"wobjectgetintprop" => EvalWobjectGetIntProp(A(0), A(1)),
@ -386,8 +434,8 @@ internal sealed class ExpressionEngine
"wobjectgetspellids" => EvalWobjectGetSpellIds(A(0)),
"wobjectgetactivespellids" => EvalWobjectGetActiveSpellIds(A(0)),
"wobjectgetactivespelldurations" => EvalWobjectGetActiveSpellDurations(A(0)),
"getitemcountininventorybyname" => EvalItemCountByName(Tmpl(0)),
"getitemcountininventorybynamerx" => EvalItemCountByNameRx(Tmpl(0)),
"getitemcountininventorybyname" => EvalItemCountByName(Text(0)),
"getitemcountininventorybynamerx" => EvalItemCountByNameRx(Text(0)),
"getinventorycountbytemplatetype" => EvalGetInventoryCountByTemplateType(A(0)),
"actiontryselect" => EvalActionTrySelect(A(0)),
"actiontryuseitem" => EvalActionTryUseItem(A(0)),
@ -417,18 +465,20 @@ internal sealed class ExpressionEngine
"spellname" => SpellDatabase.GetSpellName((int)ToDouble(A(0))),
"componentname" => ComponentDatabase.GetComponentName((uint)ToDouble(A(0))),
"componentdata" => EvalComponentData(A(0)),
"getknownspells" => EvalGetKnownSpells(),
"getheadingto" => EvalGetHeadingTo(A(0)),
"getheading" => EvalGetHeading(A(0)),
// ── Math ──────────────────────────────────────────────────────────
"getobjectinternaltype" => EvalGetObjectInternalType(A(0)),
"isfalse" => ToDouble(A(0)) == 0 ? "1" : "0",
"istrue" => ToDouble(A(0)) != 0 ? "1" : "0",
"iif" => EvalIif(A(0), A(1), A(2)),
// "Checks if a value is equal to false (0)" / "equal to true (1)": text is neither
// (isfalse[abc] was 1), and 2 is not 1.
"isfalse" => IsNumber(A(0), out double fv) && fv == 0 ? "1" : "0",
"istrue" => IsNumber(A(0), out double tv) && tv == 1 ? "1" : "0",
"randint" => Random.Shared.Next((int)ToDouble(A(0)), (int)ToDouble(A(1))).ToString(CultureInfo.InvariantCulture),
"cstr" => A(0),
"cstrf" => EvalCstrf(A(0), Tmpl(1)),
"cstrf" => EvalCstrf(A(0), Text(1)),
"cnumber" => ToDouble(A(0)).ToString("G", CultureInfo.InvariantCulture),
"strlen" => A(0).Length.ToString(CultureInfo.InvariantCulture),
"floor" => Fmt(Math.Floor(ToDouble(A(0)))),
@ -469,7 +519,8 @@ internal sealed class ExpressionEngine
// ── Game time (Dereth) ────────────────────────────────────────────
"getgameyear" => GetGameYear().ToString(CultureInfo.InvariantCulture),
"getgamemonth" => GetGameMonth().ToString(CultureInfo.InvariantCulture),
"getgamemonthname" => GetGameMonthName(A(0)),
// The reference's own example calls it getmonthname[1].
"getgamemonthname" or "getmonthname" => GetGameMonthName(A(0)),
"getgameday" => GetGameDay().ToString(CultureInfo.InvariantCulture),
"getgamehour" => GetGameHour().ToString(CultureInfo.InvariantCulture),
"getgamehourname" => GetGameHourName(A(0)),
@ -499,13 +550,13 @@ internal sealed class ExpressionEngine
"raoptset" or "uboptset" => EvalOptSet(A(0), A(1)),
// ── RynthAi settings / meta state (VTank-compatible names) ────────
"rasetmetastate" or "vtsetmetastate" or "setmetastate" => EvalVtSetMetaState(Tmpl(0)),
"rasetmetastate" or "vtsetmetastate" or "setmetastate" => EvalVtSetMetaState(Text(0)),
"ragetmetastate" or "vtgetmetastate" or "getmetastate" => _settings?.CurrentState ?? "",
// UB vtgetmeta[]: the loaded meta's name (file name without extension).
"vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath)
? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Tmpl(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Tmpl(0)),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Text(0)),
// ── Dynamic evaluation ────────────────────────────────────────────
"exec" => Evaluate(A(0)),
@ -527,6 +578,9 @@ internal sealed class ExpressionEngine
"dictclear" => EvalDictClear(A(0)),
"dictcopy" => EvalDictCopy(A(0)),
// "Strings support slices like arrays. ie test[1:]": a word that isn't a function,
// followed by [start:stop].
_ when TopLevelColon(argsStr) >= 0 => SliceBy(expr.Substring(0, lb).Trim(), argsStr),
_ => EvalUnknownFunction(funcName)
};
}
@ -535,9 +589,12 @@ internal sealed class ExpressionEngine
/// missing verb ONCE per distinct name, so a typo'd or unsupported meta function is visible
/// instead of silently evaluating to empty. Rate-limited by the seen-set to avoid log spam.</summary>
private readonly HashSet<string> _loggedUnknownFns = new();
private bool _sawUnknownFn; // set by any unknown call (TextArg asks)
private int _quietUnknownFn; // > 0: don't log (TextArg is only trying an argument)
private string EvalUnknownFunction(string funcName)
{
if (!string.IsNullOrEmpty(funcName) && _loggedUnknownFns.Add(funcName))
_sawUnknownFn = true;
if (_quietUnknownFn == 0 && !string.IsNullOrEmpty(funcName) && _loggedUnknownFns.Add(funcName))
_host.Log($"[Meta] unknown expression function '{funcName}[...]' — evaluates to empty; " +
"check spelling / supported verbs. (logged once per name)");
return "";
@ -754,18 +811,22 @@ internal sealed class ExpressionEngine
catch { return d.ToString("G", CultureInfo.InvariantCulture); }
}
// Both trueVal and falseVal are pre-evaluated by the caller (C# arg eval order) — matches UB behaviour.
private static string EvalIif(string cond, string trueVal, string falseVal)
=> ToDouble(cond) != 0 ? trueVal : falseVal;
private static bool IsNumber(string s, out double d)
=> double.TryParse(s, NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out d);
// 0=none, 1=number, 3=string, 7=object — matches UB internal type constants.
// 0=none, 1=number, 3=string, 7=object — matches UB internal type constants. Lists and
// coordinates are objects in UB (they read as 3, text, because they are text here).
private static string EvalGetObjectInternalType(string val)
{
if (string.IsNullOrEmpty(val)) return "0";
if (TryParseWobjectHandle(val, out _, out _)) return "7";
// A world object handle. Not a bare number: an id is still a number (any nonzero
// integer used to read as an object, getobjectinternaltype[5] was 7).
if (val.StartsWith("[WorldObject] ", StringComparison.Ordinal) && TryParseWobjectHandle(val, out _, out _)) return "7";
if (val.Length > 3 && val[0] == 'S' && val[1] == 'W' && val[2] == ':') return "7";
if (val.Length > 2 && val[0] == 'D' && val[1] == ':') return "7";
if (double.TryParse(val, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out _)) return "1";
if (GetList(val) != null) return "7";
if (val.Split('|').Length == 3 && TryParseCoordObject(val, out _, out _, out _)) return "7";
return "3";
}
@ -1148,6 +1209,38 @@ internal sealed class ExpressionEngine
return items;
}
/// <summary>
/// A name, pattern, state, setting or format argument. The reference makes these ordinary
/// string arguments, so an expression is evaluated: "$itemname", "getvar[x]",
/// "`^`+$name+`$`", "\(Knight\|Wisp\)\.\+Essence". They used to be taken as typed, so all
/// of those searched for their own source text. Anything else is still taken as typed, so
/// plain text with punctuation keeps working: "The Baron's Key", "High-Stakes Gambling
/// Token", "(Contract)", "Recharge-Norm-Hitp". A lone word[...] that isn't a function
/// (a regex such as "Pack[0-9]") stays as typed too.
/// </summary>
private string TextArg(string raw)
{
string a = raw.Trim();
if (a.Length == 0) return "";
bool expr = a[0] is '`' or '$' or '@'
|| (a[0] == '&' && a.Length > 1 && (char.IsLetterOrDigit(a[1]) || a[1] == '_'))
|| a.IndexOf('\\') >= 0;
if (expr) return Evaluate(a);
int lb = a.IndexOf('[');
if (lb <= 0 || FindClose(a, lb, '[', ']') != a.Length) return a;
for (int i = 0; i < lb; i++)
if (!char.IsLetterOrDigit(a[i]) && a[i] != '_') return a;
_sawUnknownFn = false;
_quietUnknownFn++;
try
{
string v = Evaluate(a);
return _sawUnknownFn ? a : v;
}
finally { _quietUnknownFn--; }
}
private static string StripBackticks(string s)
{
s = s.Trim();
@ -1244,14 +1337,49 @@ internal sealed class ExpressionEngine
return NewList(copy);
}
private static string EvalListPop(string handle, string indexArg)
/// <summary>Removes the item and returns it (it used to stay in the list: listpop on a
/// variable never shrank it).</summary>
private string EvalListPop(List<string> rawArgs, string handle, string indexArg)
{
var list = GetList(handle);
if (list == null || list.Count == 0) return "";
int idx = (int)ToLong(indexArg);
if (idx < 0) idx = list.Count - 1; // -1 = last item
if (idx < 0 || idx >= list.Count) return "";
return list[idx];
string item = list[idx];
list.RemoveAt(idx);
WriteBackList(rawArgs, NewList(list));
return item;
}
/// <summary>Runs a list-changing function and, when its list came from a variable
/// ($x, @x, &amp;x, getvar[x], getpvar[x], getgvar[x]), stores the changed list there, so
/// "listadd[getvar[CharList], Drakkon]" adds to CharList. A list given any other way
/// (listcreate[...], an item of another list) just gives the changed copy.</summary>
private string ListOp(List<string> rawArgs, string handle, Func<string, string> op)
{
string result = op(handle);
if (GetList(handle) != null && GetList(result) != null) WriteBackList(rawArgs, result);
return result;
}
private static readonly Regex ListSourceCall = new(@"^(getvar|getpvar|getgvar)\[(.*)\]$",
RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant);
private void WriteBackList(List<string> rawArgs, string list)
{
if (rawArgs.Count == 0) return;
string a = rawArgs[0].Trim();
if (a.Length > 1 && a[0] is '$' or '@' or '&' && a.Skip(1).All(c => char.IsLetterOrDigit(c) || c == '_'))
{
WriteVar(a[0], a.Substring(1), list);
return;
}
var m = ListSourceCall.Match(a);
if (!m.Success || FindClose(a, m.Groups[1].Length, '[', ']') != a.Length) return;
char sigil = char.ToLowerInvariant(m.Groups[1].Value[3]) switch { 'p' => '@', 'g' => '&', _ => '$' };
string name = Evaluate(m.Groups[2].Value);
if (name.Length > 0) WriteVar(sigil, name, list);
}
private static string EvalListCount(string handle)
@ -2526,6 +2654,7 @@ internal sealed class ExpressionEngine
if (!int.TryParse(spellArg.Trim(), out int spellId) || spellId == 0) return "2";
if (!_host.HasCastSpell) return "2";
if (!TryParseWobjectHandle(targetArg, out uint targetId, out _) || targetId == 0) return "2";
if (SpellKnownToBeUnknown(spellId)) return "2";
if (!EnsureMagicModeForCast()) return "0";
@ -2799,6 +2928,7 @@ internal sealed class ExpressionEngine
{
if (!int.TryParse(arg.Trim(), out int spellId) || spellId == 0) return "2";
if (!_host.HasCastSpell) return "2";
if (SpellKnownToBeUnknown(spellId)) return "2";
if (!EnsureMagicModeForCast()) return "0";
@ -2810,6 +2940,26 @@ internal sealed class ExpressionEngine
return "1";
}
/// <summary>The character doesn't know the spell (as far as the client can tell): the
/// reference's "2 if the attempt is impossible". It used to wield a wand, cast anyway and
/// report 1 (started). Unreadable counts as known, so nothing is refused by mistake.</summary>
private bool SpellKnownToBeUnknown(int spellId)
=> _playerId != 0 && _host.HasIsSpellKnown
&& _host.IsSpellKnown(_playerId, (uint)spellId, out bool known) && !known;
/// <summary>getknownspells[]: the ids of the spells in the character's spellbook.</summary>
private string EvalGetKnownSpells()
{
if (!_host.HasReadKnownSpells) return "[]";
var buf = new uint[8192];
int count = _host.ReadKnownSpells(buf, buf.Length);
if (count <= 0) return "[]";
var ids = new List<string>(Math.Min(count, buf.Length));
for (int i = 0; i < count && i < buf.Length; i++)
ids.Add(buf[i].ToString(CultureInfo.InvariantCulture));
return NewList(ids);
}
private string EvalActionTryEquipAnyWand()
{
if (_worldObjectCache == null || !_host.HasUseObject) return "0";
@ -3081,11 +3231,15 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(objArg, out uint uid, out _)) return "0";
if (!_host.HasGetPlayerPose) return "0";
if (!_host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _)) return "0";
if (!_host.TryGetPlayerPose(out uint pc, out float px, out float py, out _, out _, out _, out _, out _)) return "0";
if (!_host.HasGetObjectPosition) return "0";
if (!_host.TryGetObjectPosition(uid, out _, out float tx, out float ty, out _)) return "0";
if (!_host.TryGetObjectPosition(uid, out uint tc, out float tx, out float ty, out _)) return "0";
double deg = Math.Atan2(tx - px, ty - py) * (180.0 / Math.PI);
// x/y are metres within each one's own landblock (192 m square); add the landblocks'
// offsets, or a target across a landblock edge points the wrong way.
double dx = ((int)(tc >> 24) - (int)(pc >> 24)) * 192.0 + (tx - px);
double dy = ((int)((tc >> 16) & 0xFF) - (int)((pc >> 16) & 0xFF)) * 192.0 + (ty - py);
double deg = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (deg < 0) deg += 360.0;
return deg.ToString("G", CultureInfo.InvariantCulture);
}
@ -3158,7 +3312,7 @@ internal sealed class ExpressionEngine
private static readonly string[] MonthNames =
{
"Morningthaw","Solclaim","Seedsow","Leafdawning","Verdantine","Thistledown",
"HarvestGain","Leafcull","Frostfell","Snowreap","Coldeve","Wintersebb"
"Harvestgain","Leafcull","Frostfell","Snowreap","Coldeve","Wintersebb"
};
private static readonly string[] HourNames =
@ -3203,7 +3357,8 @@ internal sealed class ExpressionEngine
private int GetGameYear() => (int)(GetGameTicks() / TicksInYear);
private int GetGameMonth() => (int)(GetGameTicks() % TicksInYear / TicksInMonth);
private int GetGameDay() => (int)(GetGameTicks() % TicksInMonth / TicksInDay);
// "the current ingame day of the month. 1-30" (it was 0-29).
private int GetGameDay() => (int)(GetGameTicks() % TicksInMonth / TicksInDay) + 1;
private int GetGameHour() => (int)(GetGameTicks() % TicksInDay / TicksInHour);
private bool GetIsDay() { int h = GetGameHour(); return h >= 4 && h < 12; }
@ -3258,16 +3413,13 @@ internal sealed class ExpressionEngine
}
// VTank getfellowshipstatus[] — the migration keystone (~149 metas use it).
// Contract reverse-engineered from real meta usage across the VTank library
// (512 calls: only ==0 / ==1 / !=0; AutoFellow gates `/ub fellow recruit`
// — a leader-only action — on ==1):
// 0 = not in a fellowship
// 1 = in a fellowship and you are the leader
// 2 = in a fellowship and you are NOT the leader
// Documented: "Returns 1 if you are in a fellowship, 0 otherwise". It used to return 2 for a
// member who isn't the leader (a guess from meta usage), so metas testing ==1 saw a member
// as not in a fellowship (2026-10-11). Leader checks: getfellowshipisleader[].
private string EvalGetFellowshipStatus()
{
if (_fellowshipTracker == null || !_fellowshipTracker.IsInFellowship) return "0";
return _fellowshipTracker.IsLeader ? "1" : "2";
return "1";
}
private string EvalGetFellowId(string arg)
@ -3633,6 +3785,81 @@ internal sealed class ExpressionEngine
return dict != null ? NewDict(dict) : NewDict();
}
// ── Variable shorthand, indexes and slices ────────────────────────────────
/// <summary>Reads a variable by sigil: $ memory, @ persistent, &amp; global. Unset reads "0".</summary>
internal string ReadVar(char sigil, string name)
{
var store = sigil switch { '@' => GetPvars(), '&' => GetGvars(), _ => _variables };
return store.TryGetValue(name, out string? v) ? v ?? "" : "0";
}
/// <summary>Writes a variable by sigil, as setvar / setpvar / setgvar do.</summary>
internal string WriteVar(char sigil, string name, string value) => sigil switch
{
'@' => EvalSetPvar(name, value),
'&' => EvalSetGvar(name, value),
_ => EvalSetVar(name, value),
};
/// <summary>x{i}: a list item, a dictionary value by key, or a character of text. A negative
/// index counts from the end. Missing → "" (the reference throws).</summary>
internal string IndexValue(string value, string key)
{
var dict = GetDict(value.Trim());
if (dict != null) return dict.TryGetValue(key, out string? dv) ? dv : "";
var list = GetList(value);
int count = list?.Count ?? value.Length;
long i = ToLong(key);
if (i < 0) i += count;
if (i < 0 || i >= count) return "";
return list != null ? list[(int)i] : value[(int)i].ToString();
}
/// <summary>x{start:stop} / x[start:stop]: a sub-list or substring, as Python slices
/// (stop excluded, negatives count from the end, empty means the start / the end).</summary>
internal string SliceValue(string value, string start, string stop)
{
var list = GetList(value);
int n = list?.Count ?? value.Length;
int Norm(string s, int dflt)
{
if (s.Trim().Length == 0) return dflt;
long i = ToLong(s);
if (i < 0) i += n;
return (int)Math.Clamp(i, 0, n);
}
int a = Norm(start, 0), b = Norm(stop, n);
if (b < a) b = a;
return list != null ? NewList(list.GetRange(a, b - a)) : value.Substring(a, b - a);
}
/// <summary>Index of a ':' outside brackets and backticks, or -1 (marks a slice).</summary>
internal static int TopLevelColon(string s)
{
int depth = 0;
bool inBacktick = false;
for (int i = 0; i < s.Length; i++)
{
if (IsEscape(s, i, inBacktick)) { i++; continue; }
char c = s[i];
if (c == '`') inBacktick = !inBacktick;
else if (inBacktick) continue;
else if (c is '[' or '{' or '(') depth++;
else if (c is ']' or '}' or ')') depth--;
else if (c == ':' && depth == 0) return i;
}
return -1;
}
/// <summary>Evaluates "start:stop" (either side may be empty) and slices.</summary>
internal string SliceBy(string value, string spec)
{
int colon = TopLevelColon(spec);
string a = spec.Substring(0, colon), b = spec.Substring(colon + 1);
return SliceValue(value, a.Trim().Length > 0 ? Evaluate(a) : "", b.Trim().Length > 0 ? Evaluate(b) : "");
}
// ── Coercions ─────────────────────────────────────────────────────────────
/// <summary>"0" and "" are false; everything else is true.</summary>
@ -3669,7 +3896,8 @@ internal sealed class ExpressionEngine
// ── Argument splitter ─────────────────────────────────────────────────────
/// <summary>Splits a comma-separated argument list, respecting nested bracket depth and backtick strings.</summary>
/// <summary>Splits a comma-separated argument list, respecting nested bracket depth, backtick
/// strings and backslash escapes ("echo[Not here\, sorry,15]" is two arguments).</summary>
private static List<string> SplitArgs(string s)
{
var list = new List<string>();
@ -3678,6 +3906,7 @@ internal sealed class ExpressionEngine
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (IsEscape(s, i, inBacktick)) { i++; continue; }
if (c == '`') { inBacktick = !inBacktick; }
else if (!inBacktick)
{
@ -3685,15 +3914,53 @@ internal sealed class ExpressionEngine
else if (c == ']') depth--;
else if (c == ',' && depth == 0)
{
list.Add(s.Substring(start, i - start).Trim());
list.Add(TrimArg(s.Substring(start, i - start)));
start = i + 1;
}
}
}
list.Add(s.Substring(start).Trim());
list.Add(TrimArg(s.Substring(start)));
return list;
}
/// <summary>A backslash escape at <paramref name="i"/>: outside backticks '\' escapes any
/// character; inside them only "\`" and "\\" are escapes (other backslashes are text, so
/// a regex like `\d+` keeps its backslash).</summary>
private static bool IsEscape(string s, int i, bool inBacktick)
=> s[i] == '\\' && i + 1 < s.Length && (!inBacktick || s[i + 1] is '`' or '\\');
/// <summary>Trim, but keep an escaped trailing space ("abc\ ").</summary>
private static string TrimArg(string s)
{
string t = s.Trim();
if (t.Length < s.Length && t.Length > 0 && t[^1] == '\\')
{
int slashes = 0;
for (int i = t.Length - 1; i >= 0 && t[i] == '\\'; i--) slashes++;
int at = s.IndexOf(t, StringComparison.Ordinal) + t.Length;
if (slashes % 2 == 1 && at < s.Length) t += s[at];
}
return t;
}
/// <summary>Index just past the bracket that closes the one at <paramref name="open"/>
/// (or the end of the text), skipping backtick strings and escapes.</summary>
private static int FindClose(string s, int open, char openCh, char closeCh)
{
int depth = 0;
bool inBacktick = false;
for (int i = open; i < s.Length; i++)
{
if (IsEscape(s, i, inBacktick)) { i++; continue; }
char c = s[i];
if (c == '`') inBacktick = !inBacktick;
else if (inBacktick) continue;
else if (c == openCh) depth++;
else if (c == closeCh && --depth == 0) return i + 1;
}
return s.Length;
}
// ── Infix expression parser ───────────────────────────────────────────────
/// <summary>
@ -3708,9 +3975,40 @@ internal sealed class ExpressionEngine
private readonly string _s;
private int _p;
// > 0 while parsing the side of && / || that must not run: function calls and
// assignments are skipped (read for their length only), so "0 && echo[x]" echoes nothing.
private int _skip;
internal Parser(ExpressionEngine eng, string s) { _eng = eng; _s = s; }
internal string Run() => ParseOr();
/// <summary>
/// Expressions separated by ';' run in order; the value is the last one's
/// ("setvar[t, stopwatchcreate[]]; stopwatchstart[$t]"). Everything after the first
/// ';' used to be dropped.
/// </summary>
internal string Run()
{
string last = ParseOr();
while (true)
{
Ws();
if (_p >= _s.Length || _s[_p] != ';') break;
_p++;
Ws();
if (_p >= _s.Length) break;
if (_s[_p] == ';') continue;
last = ParseOr();
}
return last;
}
/// <summary>Parses (and so consumes) one operand without running anything in it.</summary>
private void Skip(Func<string> parse)
{
_skip++;
try { parse(); }
finally { _skip--; }
}
// ── Whitespace ────────────────────────────────────────────────────────
@ -3753,21 +4051,32 @@ internal sealed class ExpressionEngine
// ── Precedence levels ─────────────────────────────────────────────────
// Priority 1 (lowest): ||
// Priority 1 (lowest): || (short-circuit: a true left side skips the right side)
private string ParseOr()
{
var l = ParseAnd();
Ws();
while (Try("||")) { var r = ParseAnd(); l = ToBool(l) || ToBool(r) ? "1" : "0"; Ws(); }
while (Try("||"))
{
if (ToBool(l)) { Skip(ParseAnd); l = "1"; }
else l = ToBool(ParseAnd()) ? "1" : "0";
Ws();
}
return l;
}
// Priority 2: &&
// Priority 2: && (short-circuit: a false left side skips the right side, so
// "$debug && echo[...]" only echoes when debugging; it used to always run)
private string ParseAnd()
{
var l = ParseBitOr();
Ws();
while (Try("&&")) { var r = ParseBitOr(); l = ToBool(l) && ToBool(r) ? "1" : "0"; Ws(); }
while (Try("&&"))
{
if (!ToBool(l)) { Skip(ParseBitOr); l = "0"; }
else l = ToBool(ParseBitOr()) ? "1" : "0";
Ws();
}
return l;
}
@ -3921,7 +4230,7 @@ internal sealed class ExpressionEngine
Ws();
if (_p >= _s.Length) return "";
char c = _s[_p];
if (c is '`' or '$' or '(' or '~' or '-') return ParseUnary();
if (c is '`' or '$' or '@' or '(' or '~' or '-') return ParseUnary();
int wordEnd = _p;
while (wordEnd < _s.Length && (char.IsLetterOrDigit(_s[wordEnd]) || _s[wordEnd] == '_' || _s[wordEnd] == '.'))
@ -3938,7 +4247,7 @@ internal sealed class ExpressionEngine
else if (ch is ']' or ')') { if (depth == 0) break; depth--; }
else if (depth == 0)
{
if (ch == ',') break;
if (ch is ',' or ';') break;
if (q + 1 < _s.Length)
{
char n = _s[q + 1];
@ -3982,9 +4291,9 @@ internal sealed class ExpressionEngine
Ws();
if (_p < _s.Length && _s[_p] == ')') _p++;
_eng._parenDepth--;
return inner;
return ParseIndexes(inner);
}
return ParseAtom();
return ParseIndexes(ParseAtom());
}
/// <summary>
@ -3997,16 +4306,19 @@ internal sealed class ExpressionEngine
if (_p >= _s.Length) return "";
// Backtick string literal: `content` → content (verbatim, no evaluation)
// \` inside the string is an escaped backtick (needed for nested expressions).
// \` inside the string is an escaped backtick (needed for nested expressions), and
// \\ is one backslash: real metas nest "`chatbox[\\/vt forcebuff]`" (the inner text
// is then "\/vt forcebuff") and write the regex `\\d+`. Any other \x stays as is,
// as in the reference's `\d+`.
if (_s[_p] == '`')
{
_p++; // consume opening backtick
var sb = new System.Text.StringBuilder();
while (_p < _s.Length && _s[_p] != '`')
{
if (_s[_p] == '\\' && _p + 1 < _s.Length && _s[_p + 1] == '`')
if (_s[_p] == '\\' && _p + 1 < _s.Length && _s[_p + 1] is '`' or '\\')
{
sb.Append('`');
sb.Append(_s[_p + 1]);
_p += 2;
}
else
@ -4018,18 +4330,10 @@ internal sealed class ExpressionEngine
return sb.ToString();
}
// $name — shorthand for getvar[name]
if (_s[_p] == '$')
{
_p++;
int vs = _p;
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_'))
_p++;
string varName = _s.Substring(vs, _p - vs);
// Same as getvar[name]: an unset variable reads "0" (it read "", so
// '$kills == 0' was false until kills was first set).
return _eng._variables.TryGetValue(varName, out string? vv) ? vv ?? "" : "0";
}
// $name / @name / &name: getvar / getpvar / getgvar shorthand
if (_s[_p] == '$' || _s[_p] == '@'
|| (_s[_p] == '&' && _p + 1 < _s.Length && (char.IsLetterOrDigit(_s[_p + 1]) || _s[_p + 1] == '_')))
return ParseVariable();
// Hex literal: 0x / 0X (positive or negative)
bool negHex = _s[_p] == '-' && _p + 2 < _s.Length && _s[_p + 1] == '0' && (_s[_p + 2] == 'x' || _s[_p + 2] == 'X');
@ -4058,31 +4362,147 @@ internal sealed class ExpressionEngine
int start = _p;
// Identifier (letters, digits, underscores, dots for decimal numbers)
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_' || _s[_p] == '.'))
_p++;
// A word: letters, digits, underscores, dots (decimal numbers), and backslash
// escapes, each of which stands for the character after it ("p\@cMan\$" = p@cMan$).
var word = new System.Text.StringBuilder();
bool escaped = false;
ReadWord(word, ref escaped);
if (_p < _s.Length && _s[_p] == '[')
if (!escaped && _p > start && _p < _s.Length && _s[_p] == '[')
{
// Function call: consume '[' and scan to its matching ']'
_p++;
int depth = 1;
while (_p < _s.Length && depth > 0)
{
if (_s[_p] == '[') depth++;
else if (_s[_p] == ']') depth--;
_p++;
}
// Function call: scan to the matching ']' (backticks and escapes skipped)
_p = FindClose(_s, _p, '[', ']');
// Pass the entire "funcname[args]" string to EvaluatePrimary
// (not on the skipped side of && / ||: nothing in it may run)
if (_skip > 0) return "0";
return _eng.EvaluatePrimary(_s.Substring(start, _p - start));
}
if (_p > start)
return _eng.EvaluatePrimary(_s.Substring(start, _p - start));
if (_p == start)
{
// Skip unrecognised characters (guards against infinite loops). A ';' is left
// for Run(), which starts the next expression there.
if (_s[_p] != ';') _p++;
return "";
}
// Skip unrecognised characters (guards against infinite loops)
_p++;
return "";
// Text of letters and spaces needs no escaping, so the words that follow (with
// the spaces between them) are part of it: "echo[Uses dispel gems,15]". Only the
// first word used to be kept. A number stays one word ("\1\2\3 test" is how the
// reference writes text that starts with digits).
bool number = !escaped && char.IsDigit(_s[start]);
bool words = !number && ReadMoreWords(word, ref escaped);
string text = word.ToString();
// "Although there are keywords for true/false, internally they represent number 1/0."
if (!escaped && !words)
{
if (text.Equals("true", StringComparison.OrdinalIgnoreCase)) return "1";
if (text.Equals("false", StringComparison.OrdinalIgnoreCase)) return "0";
}
return text;
}
/// <summary>
/// $name, @name, &amp;name: a memory, persistent or global variable (the reference's
/// shorthand for getvar / getpvar / getgvar; only $ was supported). The name may be a
/// function call whose value is the name ("$wobjectgetname[wobjectgetplayer[]]"), and
/// "$name[1:3]" is a slice. "$name = value" assigns (not in the reference, but UB has
/// it and real metas use it ~500 times): the value is everything up to &amp;&amp;, ||, ';' or
/// the end, so "$x=listfilter[...] &amp;&amp; listcount[$x]>0" sets x to the list.
/// </summary>
private string ParseVariable()
{
char sigil = _s[_p++];
int ns = _p;
while (_p < _s.Length && (char.IsLetterOrDigit(_s[_p]) || _s[_p] == '_')) _p++;
if (_p == ns) return ""; // a stray sigil: as before
string name = _s.Substring(ns, _p - ns);
string? slice = null;
if (_p < _s.Length && _s[_p] == '[')
{
int close = FindClose(_s, _p, '[', ']');
string inner = _s.Substring(_p + 1, Math.Max(0, close - _p - 2));
if (TopLevelColon(inner) >= 0) slice = inner;
else name = _skip > 0 ? "" : _eng.EvaluatePrimary(_s.Substring(ns, close - ns));
_p = close;
}
if (slice == null)
{
int save = _p;
Ws();
if (_p < _s.Length && _s[_p] == '=' && (_p + 1 >= _s.Length || _s[_p + 1] != '='))
{
_p++;
string value = ParseBitOr();
return _skip > 0 ? value : _eng.WriteVar(sigil, name, value);
}
_p = save;
}
string v = _eng.ReadVar(sigil, name);
return slice == null || _skip > 0 ? v : _eng.SliceBy(v, slice);
}
/// <summary>x{key} after a value: list item, dictionary value or character; x{a:b} slices.
/// Repeats: "$commands{$name}{params}".</summary>
private string ParseIndexes(string value)
{
while (_p < _s.Length && _s[_p] == '{')
{
int close = FindClose(_s, _p, '{', '}');
string inner = _s.Substring(_p + 1, Math.Max(0, close - _p - 2));
_p = close;
if (_skip > 0) continue;
value = TopLevelColon(inner) >= 0
? _eng.SliceBy(value, inner)
: _eng.IndexValue(value, _eng.Evaluate(inner));
}
return value;
}
private static bool IsWordChar(char c) => char.IsLetterOrDigit(c) || c == '_' || c == '.';
private void ReadWord(System.Text.StringBuilder sb, ref bool escaped)
{
while (_p < _s.Length)
{
char c = _s[_p];
if (IsWordChar(c)) { sb.Append(c); _p++; }
else if (c == '\\' && _p + 1 < _s.Length) { sb.Append(_s[_p + 1]); _p += 2; escaped = true; }
else break;
}
}
/// <summary>
/// Appends the words that follow the one just read, with the spaces between them.
/// Spaces before a '+' are kept too ("\/vt nav load +getpvar[HuntNav]" is the text
/// "/vt nav load " joined to the nav name); other leading and trailing spaces are not.
/// A word that is a function name ("text func[...]") is not taken.
/// </summary>
private bool ReadMoreWords(System.Text.StringBuilder sb, ref bool escaped)
{
bool any = false;
while (true)
{
int q = _p;
while (q < _s.Length && (_s[q] == ' ' || _s[q] == '\t')) q++;
if (q == _p || q >= _s.Length) break;
char n = _s[q];
if (n == '+') { sb.Append(_s, _p, q - _p); _p = q; break; }
if (!IsWordChar(n) && n != '\\') break;
int save = _p, saveLen = sb.Length;
sb.Append(_s, _p, q - _p);
_p = q;
bool e2 = false;
ReadWord(sb, ref e2);
if (!e2 && _p < _s.Length && _s[_p] == '[') { _p = save; sb.Length = saveLen; break; }
escaped |= e2;
any = true;
}
return any;
}
}
}

View file

@ -135,6 +135,13 @@ internal sealed class MetaManager
public void SetMtCommandHandler(Func<string, bool> handler) => _mtCommandHandler = handler;
public void SetRaCommandHandler(Action<string> handler) => _raCommandHandler = handler;
/// <summary>Embedded Nav Route's "Patrol" (any case): the dungeon patrol instead of a route,
/// unless the meta or NavProfiles has a route by that name.</summary>
internal const string PatrolRoute = "Patrol";
internal static bool IsPatrolRoute(string routeName) =>
string.Equals(routeName?.Trim(), PatrolRoute, StringComparison.OrdinalIgnoreCase);
public void SetObjectCache(WorldObjectCache cache)
{
_objectCache = cache;
@ -923,6 +930,18 @@ internal sealed class MetaManager
}
}
// "Patrol" with no route of that name: the dungeon patrol (/ra dunnav-patrol, a
// circular hunt through every cell of this dungeon, no nav file). The Meta panel
// offers it first in Embedded Nav Route's list. A real route called Patrol wins.
if (IsPatrolRoute(routeName) && !_settings.EmbeddedNavs.ContainsKey(routeName)
&& !File.Exists(Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles", routeName + ".nav")))
{
_host.Log("[Meta] EmbedNav: Patrol -> /ra dunnav-patrol");
if (_raCommandHandler != null) _raCommandHandler("/ra dunnav-patrol");
else _host.WriteToChat("[RynthAi Meta] Patrol: no /ra command handler", 1);
break;
}
if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded))
{
var newRoute = NavRouteParser.LoadFromLines(embedded);

View file

@ -19,12 +19,14 @@ namespace RynthCore.Plugin.RynthAi.Meta;
internal static class MetaRuleEdits
{
/// <summary>Puts <paramref name="edited"/> at <paramref name="index"/>, keeping the old rule's
/// runtime latch and the fields the panel can't send. False when the index is out of range.</summary>
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited)
/// runtime latch and the fields the panel can't send. <paramref name="keepName"/>: the edit came
/// from an engine without rule names, so the rule keeps its name. False when the index is out of range.</summary>
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited, bool keepName = false)
{
if (index < 0 || index >= rules.Count) return false;
MetaRule old = rules[index];
KeepHidden(old, edited);
if (keepName) edited.Name = old.Name;
edited.HasFired = old.HasFired;
edited.LastFiredAt = old.LastFiredAt;
rules[index] = edited;

View file

@ -636,6 +636,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
@ -1333,6 +1334,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_loginComplete) TickAwakenedTier();
// A stop the action pacing held (nothing of ours moving, a server action unanswered)
// goes out as soon as the server has answered: a stop is never dropped (2026-10-12).
if (_loginComplete) RynthCore.Plugin.Shared.MoveAudit.FlushPendingStops(Host, "once the server answered");
// Periodically flush the creature profile store (~ every 5 seconds at 60Hz).
if (++_creatureSaveTickCounter >= 300)
{
@ -2052,6 +2057,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_petManager?.OnChatWindowText(text);
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
_combatManager?.HandleChatForDamage(text);
_missileCraftingManager?.HandleChat(text);
@ -2149,6 +2155,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
/// </summary>
private bool IsFightableCreature(uint objectId)
{
if (IsPlayerOrPet(objectId)) return false;
WorldObject? obj = _objectCache?[unchecked((int)objectId)];
if (obj != null && obj.ObjectClass is AcObjectClass.Npc or AcObjectClass.Vendor
or AcObjectClass.Player or AcObjectClass.CombatPet)
@ -2156,6 +2163,30 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return !Host.HasObjectIsAttackable || Host.ObjectIsAttackable(objectId);
}
// PublicWeenieDesc bitfield BF_PLAYER, and PropertyInstanceId PetOwner.
private const uint BfPlayer = 0x8;
private const uint PropIidPetOwner = 44;
/// <summary>
/// Your own character, another player, or someone's pet or summon: never a monster row or
/// a creatures.json entry, whatever the object cache calls it. The cache files any creature
/// whose type reads before anything else as a Monster - other players do, and so did your
/// own character when something looked it up through the cache - and players are
/// attackable, so the class and attackable checks alone let them through (the character's
/// own row in the Damage tab, 2026-10-11). Checked without the cache: the id, the player
/// guid range, the weenie's player flag, a pet owner, and the player weenies.
/// </summary>
private bool IsPlayerOrPet(uint objectId, uint wcid = 0)
{
if (objectId == 0) return false;
if (objectId == _playerId || objectId == Host.GetPlayerId()) return true;
if (CreatureData.PlayerWeenies.IsPlayerGuid(objectId)) return true;
if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(objectId, out uint bf) && (bf & BfPlayer) != 0) return true;
if (Host.TryGetObjectInstanceIdProperty(objectId, PropIidPetOwner, out uint owner) && owner != 0) return true;
if (wcid == 0 && Host.HasGetObjectWcid) Host.TryGetObjectWcid(objectId, out wcid);
return CreatureData.PlayerWeenies.IsPlayerWcid(wcid);
}
// Exact per-hit damage from the engine (AttackerNotification 0x01B1). This is
// the only selection-free source of real damage numbers — combat uses it to
// learn per-monster damage and predict kill shots. isAttacker==true = our hit.
@ -2185,6 +2216,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
foreach (var r in rows.OrderByDescending(x => x.KillSamples)
.ThenBy(x => x.Element, StringComparer.OrdinalIgnoreCase))
{
if (CreatureData.PlayerWeenies.IsPlayerWcid(r.Wcid)) continue; // a player character's row, never a monster
string name = "wcid " + r.Wcid.ToString();
double hp = 0;
if (_creatureStore != null && _creatureStore.TryGetByWcid(r.Wcid, out var prof) && prof != null)
@ -2206,9 +2238,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return sb.ToString();
}
/// <summary>Structured per-monster learning for the interactive Damage panel.
/// One JSON object per (monster, weapon, spell) row. Polled live by the engine
/// MonsterDamagePanel via RynthPluginGetMonsterDamageJson.</summary>
/// <summary>Structured per-monster learning for the interactive Damage panel: the Default
/// line, then ONE row per monster name. Polled live by the engine DamageFace via
/// RynthPluginGetMonsterDamageJson.
///
/// Rows come from the learned rows (monster_damage.txt), the monsters appraised this
/// session and the monsters on this landblock. Player characters (yours included) and
/// pets are never rows (<see cref="IsPlayerOrPet"/>, <see cref="CreatureData.PlayerWeenies"/>).
///
/// One row per NAME: a server often has several weenies of one monster (retail has five
/// "Rampager"s: 10810, 10811, 16916, 21526, 22599), and each wcid used to be a row of its
/// own, so two Rampagers side by side were two identical-looking rows, one with the kills
/// and one without (2026-10-11). The learned data stays per wcid; the row adds it up,
/// lists the wcids in "wcids" (the panel shows "(2 kinds)"), and a weapon, offhand, pet,
/// HP or removal on it applies to every one of them (<see cref="DamageGroupOf"/>).</summary>
public string BuildMonsterDamageJson()
{
var store = _damageStore;
@ -2230,13 +2273,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
string NameOf(uint id, string prefix) => id == 0 ? "" : WeaponLabel(id, prefix);
// Group the per-(weapon,element,tier) stat rows by MONSTER (wcid). The Damage tab now
// shows ONE collapsed row per monster (latest tier used + total kills); the per-tier
// breakdown rides along in a nested "tiers" array for the expand drawer.
// The per-(weapon,element,tier) stat rows by wcid. Rows a player left behind are skipped
// (the store drops them when it loads; this covers a file loaded before that).
var byWcid = new Dictionary<uint, List<CreatureData.MonsterDamageStore.DamageRow>>();
var order = new List<uint>();
foreach (var r in rows)
{
if (CreatureData.PlayerWeenies.IsPlayerWcid(r.Wcid)) continue;
if (!byWcid.TryGetValue(r.Wcid, out var glist)) { glist = new(); byWcid[r.Wcid] = glist; order.Add(r.Wcid); }
glist.Add(r);
}
@ -2250,10 +2293,33 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return string.IsNullOrEmpty(name) ? "wcid " + wcid : name;
}
// Every monster to list, grouped by name: learned first, then appraised this session
// (not yet fought), then nearby.
uint[] seen;
lock (_seenMonstersThisSession) seen = System.Linq.Enumerable.ToArray(_seenMonstersThisSession);
var groups = new Dictionary<string, List<uint>>(StringComparer.OrdinalIgnoreCase);
var listed = new HashSet<uint>();
void Add(uint w, string rowName)
{
if (w == 0 || CreatureData.PlayerWeenies.IsPlayerWcid(w) || !listed.Add(w)) return;
string n = ResolveName(w, rowName);
if (!groups.TryGetValue(n, out var g)) groups[n] = g = new List<uint>();
g.Add(w);
}
foreach (uint w in order) Add(w, byWcid[w].Count > 0 ? byWcid[w][0].Name : "");
foreach (uint w in seen) Add(w, _jsonNearby.TryGetValue(w, out string? sn) ? sn : "");
foreach (var kv in _jsonNearby) Add(kv.Key, kv.Value);
int KillsOf(uint w)
{
int k = 0;
if (byWcid.TryGetValue(w, out var l)) foreach (var x in l) k += x.KillSamples;
return k;
}
var groupOf = new Dictionary<uint, uint[]>();
var sb = new System.Text.StringBuilder();
sb.Append('[');
bool first = true;
var emittedWcids = new HashSet<uint>();
// The DEFAULT line (top row). Carries the per-character default weapon; the panel renders
// it specially (weapon picker + chevron → the Default debuff/shape rule). isDefault=true.
@ -2269,43 +2335,55 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"bestWid\":0,\"bestWeapon\":\"\",\"assignedOff\":0,\"assignedOffName\":\"\",")
.Append("\"key\":\"__default__\",\"tiers\":[]")
.Append('}');
first = false;
// STABLE order by monster name (then wcid) so rows don't reshuffle as counters tick.
foreach (uint wcid in order.OrderBy(w => ResolveName(w, byWcid[w].Count > 0 ? byWcid[w][0].Name : ""),
StringComparer.OrdinalIgnoreCase).ThenBy(w => w))
foreach (var grp in groups.OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase).ThenBy(g => g.Value.Min()))
{
var glist = byWcid[wcid];
emittedWcids.Add(wcid);
string name = ResolveName(wcid, glist.Count > 0 ? glist[0].Name : "");
var hpAt = HpAt(wcid, vt);
bool hpManual = hpAt.Manual;
double hp = hpAt.Hp;
string name = grp.Key;
// The row's own wcid (what the panel's edits, details and removal name): the one with
// the most kills, then one with anything learned, then the lowest.
uint[] members = grp.Value.OrderByDescending(KillsOf).ThenByDescending(w => byWcid.ContainsKey(w))
.ThenBy(w => w).ToArray();
uint wcid = members[0];
uint[] wcids = members.OrderBy(w => w).ToArray();
if (wcids.Length > 1) foreach (uint w in wcids) groupOf[w] = wcids;
var glist = new List<CreatureData.MonsterDamageStore.DamageRow>();
foreach (uint w in members) if (byWcid.TryGetValue(w, out var l)) glist.AddRange(l);
// HP: a manual one on any of them wins (they are set together), else the first known.
(double Hp, bool Manual, bool Estimated, string Source) hpAt = default;
foreach (uint w in members)
{
var h = HpAt(w, vt, learned: byWcid.ContainsKey(w));
if (h.Manual) { hpAt = h; break; }
if (hpAt.Hp <= 0 && h.Hp > 0) hpAt = h;
}
int latestTier = store.GetLastTier(wcid); // negative = ring
int totalKills = 0; foreach (var x in glist) totalKills += x.KillSamples;
// Representative entry for the collapsed row's crit/casts = the latest-tier one,
// else the most-killed one.
// Representative entry for the collapsed row's crit/casts = the latest-tier one
// (the row's own wcid first), else the most-killed one.
CreatureData.MonsterDamageStore.DamageRow m = default; bool haveM = false;
foreach (var x in glist) if (x.Tier == latestTier) { m = x; haveM = true; break; }
if (!haveM) { int bk = -1; foreach (var x in glist) if (x.KillSamples > bk) { bk = x.KillSamples; m = x; haveM = true; } }
uint assignedWid = store.GetManualWeapon(wcid);
uint bestWid = BestFor(wcid);
uint assignedOff = store.GetManualOffhand(wcid);
uint assignedWid = 0, assignedOff = 0; string pet = "";
foreach (uint w in members) { assignedWid = store.GetManualWeapon(w); if (assignedWid != 0) break; }
foreach (uint w in members) { assignedOff = store.GetManualOffhand(w); if (assignedOff != 0) break; }
foreach (uint w in members) { pet = store.GetManualPet(w); if (pet.Length > 0) break; }
uint bestWid = BestFor(wcid);
if (!first) sb.Append(',');
first = false;
sb.Append('{')
sb.Append(",{")
.Append("\"wcid\":").Append(wcid).Append(',')
.Append("\"name\":").Append(JsonStr(name)).Append(',')
.Append("\"wid\":").Append(haveM ? m.WeaponId : 0).Append(',')
.Append("\"weapon\":").Append(JsonStr(haveM ? NameOf(m.WeaponId, "Weapon") : "")).Append(',')
.Append("\"elem\":").Append(JsonStr(haveM ? (m.Element ?? "") : "")).Append(',')
.Append("\"tier\":").Append(latestTier).Append(',')
.Append("\"hp\":").Append((int)Math.Round(hp)).Append(',')
.Append("\"hpManual\":").Append(hpManual ? "true" : "false").Append(',')
.Append("\"hp\":").Append((int)Math.Round(hpAt.Hp)).Append(',')
.Append("\"hpManual\":").Append(hpAt.Manual ? "true" : "false").Append(',')
.Append(hpAt.Estimated ? "\"hpEst\":true," : "")
.Append("\"crit\":").Append(JsonNum(haveM ? m.AvgCritDamage : 0)).Append(',')
.Append("\"critN\":").Append(haveM ? m.CritSamples : 0).Append(',')
@ -2319,13 +2397,17 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
.Append("\"bestWeapon\":").Append(JsonStr(NameOf(bestWid, "Weapon"))).Append(',')
.Append("\"assignedOff\":").Append(assignedOff).Append(',')
.Append("\"assignedOffName\":").Append(JsonStr(NameOf(assignedOff, "Offhand"))).Append(',')
.Append("\"pet\":").Append(JsonStr(store.GetManualPet(wcid))).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(store.GetManualPet(wcid)))).Append(',')
.Append(WeakJson(wcid, name))
.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"pet\":").Append(JsonStr(pet)).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(pet))).Append(',')
.Append(WeakJson(wcid, name, wcids));
if (wcids.Length > 1) sb.Append("\"wcids\":[").Append(string.Join(",", wcids)).Append("],");
sb.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[");
// The per-tier drawer: one line per (weapon, element, spell tier), the kinds' numbers
// added up (kills summed, averages weighted by their samples).
bool tf = true;
foreach (var x in glist.OrderByDescending(z => z.KillSamples).ThenByDescending(z => z.Tier))
foreach (var x in MergeTierRows(glist).OrderByDescending(z => z.KillSamples).ThenByDescending(z => z.Tier))
{
if (!tf) sb.Append(',');
tf = false;
@ -2344,53 +2426,53 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
sb.Append("]}");
}
// Bare rows for monsters appraised this session but not yet fought (one per wcid), so the
// table populates as you ID nearby mobs. HP from creatures.json (appraised); empty tiers.
uint[] seen;
lock (_seenMonstersThisSession) seen = System.Linq.Enumerable.ToArray(_seenMonstersThisSession);
foreach (uint wcid in seen.Concat(_jsonNearby.Keys))
{
if (emittedWcids.Contains(wcid)) continue;
emittedWcids.Add(wcid);
string name = ResolveName(wcid, _jsonNearby.TryGetValue(wcid, out string? nearName) ? nearName : "");
var hpAt = HpAt(wcid, vt, learned: false);
bool hpManual = hpAt.Manual;
double hp = hpAt.Hp;
uint assignedWid = store.GetManualWeapon(wcid);
uint bestWid = BestFor(wcid);
uint assignedOff = store.GetManualOffhand(wcid);
int latestTier = store.GetLastTier(wcid);
if (!first) sb.Append(',');
first = false;
sb.Append('{')
.Append("\"wcid\":").Append(wcid).Append(',')
.Append("\"name\":").Append(JsonStr(name)).Append(',')
.Append("\"wid\":0,\"weapon\":\"\",\"elem\":\"\",")
.Append("\"tier\":").Append(latestTier).Append(',')
.Append("\"hp\":").Append((int)Math.Round(hp)).Append(',')
.Append("\"hpManual\":").Append(hpManual ? "true" : "false").Append(',')
.Append(hpAt.Estimated ? "\"hpEst\":true," : "")
.Append("\"crit\":0,\"critN\":0,\"noncrit\":0,\"noncritN\":0,\"casts\":0,\"kills\":0,")
.Append("\"assignedWid\":").Append(assignedWid).Append(',')
.Append("\"assignedWeapon\":").Append(JsonStr(NameOf(assignedWid, "Weapon"))).Append(',')
.Append("\"bestWid\":").Append(bestWid).Append(',')
.Append("\"bestWeapon\":").Append(JsonStr(NameOf(bestWid, "Weapon"))).Append(',')
.Append("\"assignedOff\":").Append(assignedOff).Append(',')
.Append("\"assignedOffName\":").Append(JsonStr(NameOf(assignedOff, "Offhand"))).Append(',')
.Append("\"pet\":").Append(JsonStr(store.GetManualPet(wcid))).Append(',')
.Append("\"petLabel\":").Append(JsonStr(PetChoiceLabel(store.GetManualPet(wcid)))).Append(',')
.Append(WeakJson(wcid, name))
.Append("\"key\":").Append(JsonStr(wcid.ToString())).Append(',')
.Append("\"tiers\":[]")
.Append('}');
}
_damageGroups = groupOf;
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// One entry per (weapon, element, spell tier) across a row's wcids: kills and samples
/// summed, casts to kill weighted by kills, crit and non-crit damage by their samples.
/// A single wcid's rows come back as they are (each key is there once).
/// </summary>
private static List<CreatureData.MonsterDamageStore.DamageRow> MergeTierRows(
List<CreatureData.MonsterDamageStore.DamageRow> rows)
{
var merged = new List<CreatureData.MonsterDamageStore.DamageRow>();
var at = new Dictionary<(uint, string, int), int>();
foreach (var x in rows)
{
var key = (x.WeaponId, x.Element ?? "", x.Tier);
if (!at.TryGetValue(key, out int i)) { at[key] = merged.Count; merged.Add(x); continue; }
var a = merged[i];
static double W(double av, int an, double bv, int bn) => an + bn > 0 ? (av * an + bv * bn) / (an + bn) : Math.Max(av, bv);
merged[i] = a with
{
AvgDamage = W(a.AvgDamage, a.DmgSamples, x.AvgDamage, x.DmgSamples),
DmgSamples = a.DmgSamples + x.DmgSamples,
AvgCritDamage = W(a.AvgCritDamage, a.CritSamples, x.AvgCritDamage, x.CritSamples),
CritSamples = a.CritSamples + x.CritSamples,
AvgNonCritDamage = W(a.AvgNonCritDamage, a.NonCritSamples, x.AvgNonCritDamage, x.NonCritSamples),
NonCritSamples = a.NonCritSamples + x.NonCritSamples,
AvgCastsToKill = W(a.AvgCastsToKill, a.KillSamples, x.AvgCastsToKill, x.KillSamples),
KillSamples = a.KillSamples + x.KillSamples,
};
}
return merged;
}
/// <summary>
/// wcid -> every wcid of its Damage-tab row, for rows of more than one kind (same name),
/// from the last <see cref="BuildMonsterDamageJson"/>. Swapped whole, never changed.
/// </summary>
private volatile Dictionary<uint, uint[]> _damageGroups = new();
/// <summary>The wcids a Damage-tab edit on <paramref name="wcid"/>'s row applies to: its row's
/// kinds, or just itself.</summary>
internal uint[] DamageGroupOf(uint wcid)
=> _damageGroups.TryGetValue(wcid, out uint[]? g) ? g : new[] { wcid };
/// <summary>"weak" (top elements with multipliers) and "weakSrc" fields for a Damage-tab row, each followed by a comma.</summary>
private uint _jsonTargetWcid;
private int _jsonViewTier; // the difficulty tier BuildMonsterDamageJson is writing (WeakJson reads it)
@ -2411,9 +2493,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
uint uid = unchecked((uint)wo.Id);
// Attackable only: NPCs the object cache classifies as monsters would otherwise
// be added as Damage-tab rows here (e52ccc8 closed the appraisal path only).
// IsFightableCreature also turns away your own character, other players and pets,
// which the cache can class as monsters (IsPlayerOrPet).
if (!IsFightableCreature(uid)) continue;
if (!Host.TryGetObjectPosition(uid, out uint cell, out _, out _, out _) || (cell >> 16) != myBlock) continue;
if (Host.TryGetObjectWcid(uid, out uint w) && w != 0 && !map.ContainsKey(w)) map[w] = wo.Name ?? "";
if (Host.TryGetObjectWcid(uid, out uint w) && w != 0 && !CreatureData.PlayerWeenies.IsPlayerWcid(w)
&& !map.ContainsKey(w)) map[w] = wo.Name ?? "";
}
return map;
}
@ -2427,14 +2512,23 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return Host.TryGetObjectWcid(unchecked((uint)id), out uint w) ? w : 0;
}
private string WeakJson(uint wcid, string name)
/// <summary>A row's "weak", "weakSrc", "secKill", "hitRate", "targeted" and "nearby" fields, each followed
/// by a comma. Targeted / nearby when any of <paramref name="wcids"/> (the row's kinds) is.</summary>
private string WeakJson(uint wcid, string name, uint[] wcids)
{
var r = _combatManager?.WeaknessFor(wcid, name);
var (sec, hit) = _damageStore?.GetSummary(wcid, _jsonViewTier) ?? (-1, -1);
bool targeted = false, nearby = false;
foreach (uint w in wcids)
{
if (w == 0) continue;
targeted |= w == _jsonTargetWcid;
nearby |= _jsonNearby.ContainsKey(w);
}
return "\"weak\":" + JsonStr(r?.Describe() ?? "") + ",\"weakSrc\":" + JsonStr(r?.Source ?? "")
+ ",\"secKill\":" + JsonNum(sec) + ",\"hitRate\":" + JsonNum(hit)
+ ",\"targeted\":" + (wcid != 0 && wcid == _jsonTargetWcid ? "true" : "false")
+ ",\"nearby\":" + (wcid != 0 && _jsonNearby.ContainsKey(wcid) ? "true" : "false") + ",";
+ ",\"targeted\":" + (targeted ? "true" : "false")
+ ",\"nearby\":" + (nearby ? "true" : "false") + ",";
}
/// <summary>
@ -2542,7 +2636,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Off Aelrynth the tier is 0 and this is the value as typed, as before.
int vt = DamageViewDifficulty;
double value = hp > 0 && vt > 0 ? hp / CreatureData.AwakenedTier.HealthScale(vt) : hp;
_damageStore.SetManualHp(wcid, value);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualHp(w, value); // every kind of the row
_damageStore.SaveIfDirty();
}
@ -2670,7 +2764,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterWeapon(uint wcid, uint weaponId)
{
if (_damageStore == null) return;
_damageStore.SetManualWeapon(wcid, weaponId);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualWeapon(w, weaponId);
_damageStore.SaveIfDirty();
}
@ -2687,7 +2781,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterOffhand(uint wcid, uint offhandId)
{
if (_damageStore == null) return;
_damageStore.SetManualOffhand(wcid, offhandId);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualOffhand(w, offhandId);
_damageStore.SaveIfDirty();
}
@ -2695,7 +2789,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public void SetMonsterPet(uint wcid, string choice)
{
if (_damageStore == null) return;
_damageStore.SetManualPet(wcid, choice);
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualPet(w, choice);
_damageStore.SaveIfDirty();
}
@ -2764,8 +2858,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// and monsters from another server couldn't be cleared (2026-09-29).
if (uint.TryParse(key, out uint onlyWcid))
{
bool gone = _damageStore.DeleteWcid(onlyWcid);
lock (_seenMonstersThisSession) gone |= _seenMonstersThisSession.Remove(onlyWcid);
// A row of several kinds (same name) goes as a whole.
bool gone = false;
foreach (uint w in DamageGroupOf(onlyWcid))
{
gone |= _damageStore.DeleteWcid(w);
lock (_seenMonstersThisSession) gone |= _seenMonstersThisSession.Remove(w);
}
_damageStore.SaveIfDirty();
return gone;
}
@ -2864,6 +2963,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
uint wcid = 0;
if (Host.HasGetObjectWcid) Host.TryGetObjectWcid(targetId, out wcid);
// Appraising yourself, another player or a pet returns health too: never creature
// data, never a Damage-tab row (the caller checks the same; this is the store's door).
if (IsPlayerOrPet(targetId, wcid)) return;
var sample = new CreatureData.CreatureProfile
{
@ -3205,6 +3307,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "autotrade": HandleAutoTradeRaCommand(parts); break;
case "trade": HandleTradeCommand(parts); break;
case "busyinfo": HandleBusyInfoCommand(); break;
// /ra quit | /ra exit: close the client (the engine's /rc quit: as its close button)
case "quit":
case "exit": if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit"); break;
// give variants — first-match (with optional count prefix)
case "give": HandleGiveCommand(parts, GiveItemMatch.Exact, partialPlayer: false); break;
case "givep": HandleGiveCommand(parts, GiveItemMatch.Partial, partialPlayer: false); break;