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;

View file

@ -4,10 +4,15 @@ using System.Text;
namespace RynthCore.Plugin.RynthChat;
/// <summary>
/// The newest 500 chat lines, exported to the engine as JSON
/// The newest chat lines, exported to the engine as JSON
/// (RynthChatGetScrollbackJson). Add runs on the game thread (chat dispatch),
/// BuildJson on the engine's pump thread; the lock covers both.
///
/// How many: DefaultCapacity until the engine says otherwise
/// (RynthChatSetCapacity, from the chat setting "Chat history"; 0.3.0). It was
/// a fixed 500 before. Changing it keeps the newest lines and never touches the
/// numbering: the engine (and its Discord relay) tell new lines from old by seq.
///
/// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}.
/// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it.
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
@ -16,14 +21,55 @@ namespace RynthCore.Plugin.RynthChat;
/// </summary>
internal sealed class ChatBuffer
{
private const int Capacity = 500;
/// <summary>The engine's default for "Chat history" (ChatHistory.DefaultLines there).</summary>
internal const int DefaultCapacity = 2000;
internal const int MinCapacity = 100;
internal const int MaxCapacity = 10000;
private readonly ChatLine[] _ring = new ChatLine[Capacity];
private readonly object _lock = new();
private int _head; // next write index (mod Capacity)
private int _count; // total items stored (≤ Capacity)
private ChatLine?[] _ring;
private readonly object _lock = new();
private int _head; // next write index (mod _ring.Length)
private int _count; // lines stored (<= _ring.Length)
private ulong _nextSeq = 1;
internal ChatBuffer(int capacity = DefaultCapacity)
{
_ring = new ChatLine?[Math.Clamp(capacity, MinCapacity, MaxCapacity)];
}
internal int Capacity
{
get { lock (_lock) return _ring.Length; }
}
internal int Count
{
get { lock (_lock) return _count; }
}
/// <summary>
/// Keeps up to <paramref name="capacity"/> lines from now on (clamped to
/// MinCapacity..MaxCapacity); when it shrinks, the oldest go. Returns the capacity
/// applied. Any thread.
/// </summary>
internal int SetCapacity(int capacity)
{
capacity = Math.Clamp(capacity, MinCapacity, MaxCapacity);
lock (_lock)
{
if (capacity == _ring.Length) return capacity;
int keep = Math.Min(_count, capacity);
var ring = new ChatLine?[capacity];
int oldCap = _ring.Length;
int start = (_head - keep + oldCap) % oldCap; // the oldest line kept
for (int i = 0; i < keep; i++) ring[i] = _ring[(start + i) % oldCap];
_ring = ring;
_count = keep;
_head = keep % capacity;
return capacity;
}
}
internal void Add(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return;
@ -37,7 +83,7 @@ internal sealed class ChatBuffer
{
// Numbered under the lock, so the ring is always in seq order (the
// engine skips anything at or below the last seq it has seen).
_ring[_head % Capacity] = new ChatLine
_ring[_head] = new ChatLine
{
Seq = _nextSeq++,
Timestamp = ts,
@ -46,33 +92,36 @@ internal sealed class ChatBuffer
Sender = sender,
Text = text,
};
_head = (_head + 1) % Capacity;
if (_count < Capacity) _count++;
_head = (_head + 1) % _ring.Length;
if (_count < _ring.Length) _count++;
}
}
// Returns JSON array of lines with Seq > sinceSeq, oldest-first.
/// <summary>
/// The lines with Seq > sinceSeq as a JSON array, oldest first. Only those are
/// copied out under the lock: the ring holds consecutive seqs, so they are the
/// newest (newest seq - sinceSeq) lines. Until 0.3.0 the whole ring was cloned
/// and walked on every poll (10 a second), which grows with the history length.
/// </summary>
internal string BuildJson(ulong sinceSeq)
{
ChatLine[] snapshot;
int count;
int head;
ChatLine?[] lines;
lock (_lock)
{
snapshot = (ChatLine[])_ring.Clone();
count = _count;
head = _head;
ulong newest = _nextSeq - 1;
int n = sinceSeq >= newest ? 0 : (int)Math.Min((ulong)_count, newest - sinceSeq);
if (n == 0) return "[]";
lines = new ChatLine?[n];
int cap = _ring.Length;
int start = (_head - n + cap) % cap;
for (int i = 0; i < n; i++) lines[i] = _ring[(start + i) % cap];
}
var sb = new StringBuilder(256);
var sb = new StringBuilder(64 + lines.Length * 192);
sb.Append('[');
bool first = true;
// Iterate oldest→newest. Oldest entry is at (head - count + Capacity) % Capacity.
int start = (head - count + Capacity) % Capacity;
for (int i = 0; i < count; i++)
foreach (ChatLine? line in lines)
{
var line = snapshot[(start + i) % Capacity];
if (line == null || line.Seq <= sinceSeq) continue;
if (!first) sb.Append(',');

View file

@ -64,6 +64,18 @@ public static unsafe class PluginExports
}
}
/// <summary>
/// How many lines the scrollback keeps (the engine's "Chat history" setting; 0.3.0).
/// Returns the number applied (clamped to 100..10000), or 0 before the plugin is up.
/// Engines before it never call this, and the plugin keeps ChatBuffer.DefaultCapacity.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthChatSetCapacity", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int SetCapacity(int lines)
{
try { return Runtime.Plugin?.SetScrollbackCapacity(lines) ?? 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLine(IntPtr ansiText)
{

View file

@ -7,7 +7,7 @@ namespace RynthCore.Plugin.RynthChat;
public sealed class RynthChatPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthChat");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.2.1");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0");
private readonly ChatBuffer _buffer = new();
@ -42,6 +42,8 @@ public sealed class RynthChatPlugin : RynthPluginBase
internal string BuildScrollbackJson(ulong sinceSeq) => _buffer.BuildJson(sinceSeq);
internal int SetScrollbackCapacity(int lines) => _buffer.SetCapacity(lines);
// Called on the game thread from the engine's deferred chat dispatch
// (Win32Backend posts WM_RYNTHCORE_CHAT so this runs on a fresh, non-reentrant
// message dispatch rather than inline inside the Enter keystroke handler).

View file

@ -48,6 +48,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight

View file

@ -57,9 +57,12 @@ public sealed class RynthOraclePlugin : RynthPluginBase
{
DefaultWidth = 620f, DefaultHeight = 560f, MinWidth = 420f, MinHeight = 260f,
});
// The Void window is opened from the Oracle window: no bar button (and no Scripts menu
// line, which would bring back the Scripts button just for it).
_void = _ui.Add(new UiWindow("RynthOracle/Void", "Void")
{
DefaultWidth = 220f, DefaultHeight = 150f, MinWidth = 160f, MinHeight = 110f,
ShowInBar = false,
});
_mainView.SetVoidWindow = v => { if (_void != null) { _void.Visible = v; _void.NeedsPass = true; } };
_mainView.VoidWindowVisible = () => _void?.Visible ?? false;

View file

@ -47,6 +47,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Event types

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight

View file

@ -29,6 +29,32 @@ internal sealed unsafe class HostSortWorld : ISortWorld
public SortInventory? ReadInventory() => _reader.Read(_host);
// PutItemInContainer answered "not bound" once: plain moves from then on.
private bool _putUnbound;
public SortAbilities Abilities => new()
{
ReadOrder = _host.HasContainerOrder,
PlaceMoves = _host.HasPutItemInContainer && !_putUnbound,
Merge = _host.HasMergeStackInternal,
};
// Diagnostics: a "looting" pause that lasts says what the open container looked like.
private long _lootPauseSince = -1;
private bool _lootPauseLogged;
private int _lootPauseChanges, _lootPauseLastCount = int.MinValue;
private void NoteLongLootPause(bool looting, uint ground, int count, long nowMs)
{
if (!looting) { _lootPauseSince = -1; _lootPauseLogged = false; _lootPauseChanges = 0; _lootPauseLastCount = int.MinValue; return; }
if (_lootPauseSince < 0) _lootPauseSince = nowMs;
if (count != _lootPauseLastCount) { _lootPauseChanges++; _lootPauseLastCount = count; }
if (!_lootPauseLogged && nowMs - _lootPauseSince > 20_000)
{
_lootPauseLogged = true;
try { _host.Log($"[RynthSort] paused for looting over 20 s: open container 0x{ground:X8}, item count now {count}, {_lootPauseChanges} count change(s) in that time"); } catch { }
}
}
public GateInputs ReadGate(bool sortInCombat, long nowMs)
{
var g = new GateInputs { SortInCombat = sortInCombat };
@ -38,10 +64,13 @@ internal sealed unsafe class HostSortWorld : ISortWorld
int count = 0;
if (ground != 0)
{
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground) : -1;
if (count < 0) count = _host.GetContainerContents(ground, _groundBuf);
// One way of counting only: mixing the two (the item count when it reads, else the
// contents list) could flip between two different numbers and look like looting.
count = _host.HasGetNumContainedItems ? _host.GetNumContainedItems(ground)
: _host.GetContainerContents(ground, _groundBuf);
}
g.Looting = _loot.Update(ground, count, nowMs);
NoteLongLootPause(g.Looting, ground, count, nowMs);
g.VendorOpen = _host.HasVendorTrade ? _host.TryGetVendorInfo(out _) : _vendorOpenByEvent();
g.TradeOpen = _host.HasTrade && _host.TryGetTradeState(out TradeState trade) && trade.IsOpen;
@ -56,12 +85,22 @@ internal sealed unsafe class HostSortWorld : ISortWorld
uint id = move.Item.Id;
if (move.MergeInto != 0 && _host.HasMergeStackInternal)
return _host.MergeStackInternal(id, move.MergeInto);
if (move.Kind == MoveKind.Stack) return false; // a join in place needs the merge
if (move.Placement >= 0 && _host.HasPutItemInContainer && !_putUnbound)
{
int rc = _host.PutItemInContainer(id, move.Dest.Id, move.Placement);
if (rc != -1) return rc == 1;
_putUnbound = true;
try { _host.Log("[RynthSort] this client can't send a move to a slot; items are moved to their packs but not put in order"); } catch { }
}
if (move.Kind == MoveKind.Reorder) return false; // a slot change in place needs PutItemInContainer
return _host.HasMoveItemInternal && _host.MoveItemInternal(id, move.Dest.Id, 0, Math.Max(1, move.Item.Stack));
}
public MoveObservation Observe(uint itemId)
public MoveObservation Observe(in SortMove move)
{
var o = new MoveObservation();
uint itemId = move.Item.Id;
var o = new MoveObservation { Slot = -1 };
if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(itemId, out uint container, out uint wielder, out _))
{
o.Exists = true;
@ -75,6 +114,8 @@ internal sealed unsafe class HostSortWorld : ISortWorld
o.Container = 0xFFFFFFFF;
}
o.Stack = _host.TryGetObjectIntProperty(itemId, 12, out int s) && s > 0 ? s : 1;
if (move.Kind == MoveKind.Reorder && o.Exists && o.Container == move.Dest.Id)
o.Slot = _reader.SlotOf(_host, move.Dest.Id, itemId);
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out uint error, out uint type, out uint obj))
{
o.ErrorSeq = seq;

View file

@ -27,7 +27,7 @@ public static unsafe class PluginExports
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
public static IntPtr GetVersion() => LiteralPointer("0.3.0"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{

View file

@ -3,7 +3,8 @@
<!--
RynthSort: keeps a character's packs sorted while they play or while RynthAi hunts. New
items that land in the main pack move to the side pack their rule names, after a settle
time; Tidy, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
time; misplaced items move to theirs, stacks are joined and items are put in order inside
each pack (slot orders, API v80); Sort now, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
rules are imported on first run). Pack moves wait for RynthAi through its read-only
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
windows (ImGui), no Avalonia.
@ -26,8 +27,8 @@
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the
window; vendor info (v67), plugin interfaces (v68), refusals (v70) and trade (v72) are
each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
window; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
orders / moves to a slot (v80: in-pack order, top-to-bottom pack numbers) are each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
</PropertyGroup>

View file

@ -11,12 +11,14 @@ using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthSort;
/// <summary>
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. New items that land in the
/// main pack move to the side pack their rule names once they have sat there for the settle time;
/// Tidy also moves misplaced items between side packs, Clean sends items no rule wants back to the
/// main pack, Unpack empties the side packs. Rules are tried in order and the first that matches
/// wins: by item class or by part of the name. Rules and settings are kept per character; the
/// RynthSort Lua script's saved rules are taken over on a character's first run.
/// RynthSort: keeps your packs sorted while you play or RynthAi hunts. Auto-sort keeps every pack
/// tidy: new items that land in the main pack move to the side pack their rule names once they have
/// sat there for the settle time, items in the wrong side pack move to theirs, stacks of one kind
/// are joined and (with the engine's slot orders, API v80) items are put in order, A-Z, inside
/// each pack. Clean also sends items no rule wants back to the main pack; Unpack empties the side
/// packs. A rule lists classes and parts of names and the pack they go to; a name match beats a
/// class match. Rules and settings are kept per character; the RynthSort Lua script's saved rules
/// are taken over on a character's first run.
///
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
@ -28,7 +30,7 @@ namespace RynthCore.Plugin.RynthSort;
/// </summary>
public sealed class RynthSortPlugin : RynthPluginBase
{
public const string Version = "0.1.0";
public const string Version = "0.3.0";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 500;
@ -51,6 +53,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
private long _saveDueMs;
private bool _vendorOpen;
private bool _noUiLogged;
private bool _backupOnSave;
private readonly List<string> _warnings = new();
public override int Initialize()
@ -58,6 +61,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
_ui.Log = msg => Host.Log(msg);
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
_sort.SettingsChanged = RequestSave;
_sort.PacksFixed = OnPacksFixed;
_panel = new SortPanel(_sort, RequestSave)
{
Warnings = () => _warnings,
@ -143,8 +147,6 @@ public sealed class RynthSortPlugin : RynthPluginBase
Print("Auto-sort " + word);
break;
case "now":
_sort.StartJob(SortScope.Main);
break;
case "tidy":
_sort.StartJob(SortScope.All);
break;
@ -227,6 +229,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
_sort.Data = data;
_identityKnown = true;
_backupOnSave = false;
string own = _store.PathFor(server, name);
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
@ -281,6 +284,25 @@ public sealed class RynthSortPlugin : RynthPluginBase
return false;
}
/// <summary>The one-time pack fix ran: one log line per rule, a chat line, and a save (keeping a .bak of an imported file).</summary>
private void OnPacksFixed(List<string> lines, int changed)
{
bool imported = _sort.Data.ImportedFrom.Length > 0;
foreach (string line in lines) Host.Log("[RynthSort] pack fix: " + line);
if (imported)
{
int left = lines.Count - changed;
Print($"The rules taken over from the RynthSort script counted foci as packs: {changed} now point at the right pack"
+ (left > 0 ? $", {left} left as they were (see the log)." : "."));
_backupOnSave = true;
}
else if (changed > 0)
{
Host.Log($"[RynthSort] pack fix: {changed} rule(s) now remember their pack by id");
}
RequestSave();
}
private void RequestSave()
{
if (_window != null) _window.NeedsPass = true;
@ -292,8 +314,9 @@ public sealed class RynthSortPlugin : RynthPluginBase
_saveDueMs = 0;
if (!_identityKnown) return;
_sort.Data.Settings.Clamp();
string? error = _store.Save(_server, _character, _sort.Data);
string? error = _store.Save(_server, _character, _sort.Data, _backupOnSave);
if (error != null) Host.Log("[RynthSort] save failed: " + error);
else _backupOnSave = false;
}
/// <summary>A pass when one is wanted, or on the refresh interval while visible (the status ticks on).</summary>

View file

@ -13,7 +13,7 @@ internal sealed class SortSettings
{
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
/// <summary>Auto-sort: new items in the main pack go to their pack after the settle time.</summary>
/// <summary>Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).</summary>
public bool Auto = true;
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
public int SettleSec = 5;
@ -21,8 +21,17 @@ internal sealed class SortSettings
public int GapMs = 300;
/// <summary>Moves may go while RynthAi fights (never while it waits on the server or animates).</summary>
public bool SortInCombat;
/// <summary>The window was open when last seen.</summary>
public bool WindowOpen = true;
/// <summary>Items are put in order inside each pack (A-Z by name), when the engine can read slot orders (API v80).</summary>
public bool OrderInPacks = true;
/// <summary>The order inside a pack groups by kind (class) first, then name.</summary>
public bool OrderKindFirst;
/// <summary>
/// The window was open when last seen. Closed for a character RynthSort hasn't seen (it
/// has a button on the RynthCore bar and /rsort), so a new character or alt doesn't get it
/// popping up at every login until closed once; open once after taking over the Lua
/// script's rules, to show them.
/// </summary>
public bool WindowOpen;
public void Clamp()
{
@ -38,6 +47,17 @@ internal sealed class CharacterSortData
public SortSettings Settings = new();
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
public string ImportedFrom = string.Empty;
/// <summary>
/// The rules are tied to pack ids (<see cref="PackFix"/> ran once). False for files saved
/// before pack ids, a new character's defaults and a fresh import from the Lua script.
/// </summary>
public bool PacksFixed;
/// <summary>
/// The Lua script's rules as its file has them, while <see cref="PacksFixed"/> is false and the
/// rules came from it: tells untouched imported rules (Lua numbers) from ones picked in
/// RynthSort's window since. Null when unknown. Not saved.
/// </summary>
public List<SortRule>? LuaRules;
}
/// <summary>
@ -87,13 +107,20 @@ internal sealed class SortStore
string own = PathFor(server, character);
if (File.Exists(own))
{
if (TryRead(own, out CharacterSortData? d, out problem)) return d!;
return new CharacterSortData();
if (!TryRead(own, out CharacterSortData? d, out problem)) return new CharacterSortData();
// Imported before pack ids: the Lua script's file says which rules are still its own.
if (!d!.PacksFixed && d.ImportedFrom.Length > 0 && File.Exists(d.ImportedFrom)
&& TryRead(d.ImportedFrom, out CharacterSortData? luaNow, out _))
d.LuaRules = luaNow!.Rules;
return d;
}
string lua = LuaPathFor(server, character);
if (File.Exists(lua) && TryRead(lua, out CharacterSortData? imported, out problem))
{
imported!.ImportedFrom = lua;
imported.PacksFixed = false; // Lua pack numbers: fixed on the first settled read
imported.LuaRules = imported.Rules.ConvertAll(r => r.Clone());
imported.Settings.WindowOpen = true; // show the rules just taken over (the Lua file has no windowOpen)
return imported;
}
return new CharacterSortData();
@ -149,37 +176,67 @@ internal sealed class SortStore
st.SettleSec = Int(s, "settleSec", st.SettleSec);
st.GapMs = Int(s, "gapMs", st.GapMs);
st.SortInCombat = Bool(s, "sortInCombat", st.SortInCombat);
st.OrderInPacks = Bool(s, "orderInPacks", st.OrderInPacks);
st.OrderKindFirst = Bool(s, "orderKindFirst", st.OrderKindFirst);
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
st.Clamp();
}
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
d.ImportedFrom = f.GetString() ?? string.Empty;
// Missing (a version 1 file, the Lua script's file): rules by number only, not fixed yet.
d.PacksFixed = Bool(root, "packsFixed", false);
return d;
}
/// <summary>
/// One rule. Version 3 has "classes" and "names" lists; anything older (versions 1 and 2, and the
/// Lua script's file) has one test, { kind = "class" | "name", class, text }, which becomes a
/// rule with that one class or name. Version 3 writes those old fields too (its first entry),
/// so an older RynthSort reading a newer file still gets a sensible rule.
/// </summary>
private static SortRule? ParseRule(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
var r = new SortRule
{
On = Bool(e, "on", true),
Kind = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase) ? RuleKind.Name : RuleKind.Class,
Class = Int(e, "class", ObjectClasses.SpellComponent),
Text = e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? string.Empty : string.Empty,
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
PackId = UInt(e, "packId"),
PackNote = e.TryGetProperty("packNote", out JsonElement pn) && pn.ValueKind == JsonValueKind.String ? pn.GetString() ?? string.Empty : string.Empty,
};
if (r.Text.Length > 64) r.Text = r.Text[..64];
bool hasClasses = e.TryGetProperty("classes", out JsonElement cl) && cl.ValueKind == JsonValueKind.Array;
bool hasNames = e.TryGetProperty("names", out JsonElement nm) && nm.ValueKind == JsonValueKind.Array;
if (hasClasses || hasNames)
{
if (hasClasses)
foreach (JsonElement c in cl.EnumerateArray())
if (c.ValueKind == JsonValueKind.Number && c.TryGetDouble(out double v) && v >= 0 && v <= 1000) r.AddClass((int)Math.Round(v));
if (hasNames)
foreach (JsonElement n in nm.EnumerateArray())
if (n.ValueKind == JsonValueKind.String) r.AddName(n.GetString());
}
else
{
bool byName = e.TryGetProperty("kind", out JsonElement k) && k.ValueKind == JsonValueKind.String
&& string.Equals(k.GetString(), "name", StringComparison.OrdinalIgnoreCase);
if (byName) r.AddName(e.TryGetProperty("text", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null);
else r.AddClass(Int(e, "class", ObjectClasses.SpellComponent));
}
if (r.PackNote.Length > 96) r.PackNote = r.PackNote[..96];
return r;
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, CharacterSortData d)
/// <summary>
/// Writes the character's file (temp file, then moved over the old one). <paramref name="backup"/>:
/// copy the old file to "&lt;file&gt;.bak" first (the one-time pack fix keeps one). Returns an error or null.
/// </summary>
public string? Save(string server, string character, CharacterSortData d, bool backup = false)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
if (backup && File.Exists(path)) File.Copy(path, path + ".bak", overwrite: true);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
@ -197,16 +254,29 @@ internal sealed class SortStore
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
// 3: a rule holds several classes and names. 2: rules carry packId / packNote, and
// packsFixed. Versions 1 and 2 still load (one class or name per rule).
w.WriteNumber("version", 3);
w.WriteStartArray("rules");
foreach (SortRule r in d.Rules)
{
w.WriteStartObject();
w.WriteBoolean("on", r.On);
w.WriteString("kind", r.Kind == RuleKind.Name ? "name" : "class");
w.WriteNumber("class", r.Class);
w.WriteString("text", r.Text ?? string.Empty);
w.WriteStartArray("classes");
foreach (int c in r.Classes) w.WriteNumberValue(c);
w.WriteEndArray();
w.WriteStartArray("names");
foreach (string n in r.Names) w.WriteStringValue(n);
w.WriteEndArray();
// The first entry the old way, for an older RynthSort reading this file (an empty
// rule as a blank name rule, which matches nothing there too).
bool firstIsName = r.Classes.Count == 0;
w.WriteString("kind", firstIsName ? "name" : "class");
w.WriteNumber("class", r.Classes.Count > 0 ? r.Classes[0] : ObjectClasses.SpellComponent);
w.WriteString("text", firstIsName && r.Names.Count > 0 ? r.Names[0] : string.Empty);
w.WriteNumber("pack", r.Pack);
if (r.PackId != 0) w.WriteNumber("packId", r.PackId);
if (r.PackNote.Length > 0) w.WriteString("packNote", r.PackNote);
w.WriteEndObject();
}
w.WriteEndArray();
@ -215,9 +285,12 @@ internal sealed class SortStore
w.WriteNumber("settleSec", d.Settings.SettleSec);
w.WriteNumber("gapMs", d.Settings.GapMs);
w.WriteBoolean("sortInCombat", d.Settings.SortInCombat);
w.WriteBoolean("orderInPacks", d.Settings.OrderInPacks);
w.WriteBoolean("orderKindFirst", d.Settings.OrderKindFirst);
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
w.WriteEndObject();
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
w.WriteBoolean("packsFixed", d.PacksFixed);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
@ -228,6 +301,14 @@ internal sealed class SortStore
? v.GetBoolean()
: fallback;
/// <summary>An object id (0 when missing, negative or odd).</summary>
private static uint UInt(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
}
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;

View file

@ -10,6 +10,12 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
/// worn and wielded items; each side pack's items come from GetContainerContents(pack). A side
/// pack is a container that holds items (ItemsCapacity above 0); foci hold none and are skipped,
/// as are worn and wielded items. Names, classes and stack limits are kept per item id once read.
/// GetContainerContents sorts by object id; with the engine's slot orders (API v80
/// GetContainerOrder: what the server sent at login and with every move) each pack's items are put
/// in their real slot order and the side packs in the pack column's order, top first, whenever
/// that order names exactly what was read (<see cref="SortPack.ApplyOrder"/>,
/// <see cref="SortInventory.ApplyPackOrder"/>). Without it the id order stays and nothing is
/// reordered inside packs.
/// </summary>
internal sealed class InventoryReader
{
@ -39,6 +45,7 @@ internal sealed class InventoryReader
private readonly Dictionary<uint, Known> _known = new();
private uint[] _buf = new uint[512];
private uint[] _order = new uint[128];
public void Reset() => _known.Clear();
@ -59,12 +66,17 @@ internal sealed class InventoryReader
foreach (uint id in top)
{
if (id == 0) continue;
if (Wielded(host, id)) continue;
uint type = host.TryGetItemType(id, out uint t) ? t : 0;
if ((type & ItemTypeContainer) != 0)
bool isContainer = (type & ItemTypeContainer) != 0;
int cap = 0;
bool capRead = isContainer && host.TryGetObjectIntProperty(id, IntItemsCapacity, out cap);
// Every container entry, foci too and before the wielded check: the Lua script's count.
if (isContainer) inv.Slots.Add(new SortSlot(id, capRead ? Math.Max(cap, 0) : -1));
if (Wielded(host, id)) continue;
if (isContainer)
{
// A side pack holds items; foci (containers that hold none) aren't packs or items.
if (host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) && cap > 0)
if (capRead && cap > 0)
{
var pack = new SortPack { Id = id, Capacity = cap, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty };
foreach (uint inner in Contents(host, id))
@ -80,9 +92,23 @@ internal sealed class InventoryReader
}
inv.Main.Items.Add(Item(host, id, type));
}
if (host.HasContainerOrder)
{
if (host.TryGetContainerOrder(player, false, ref _order, out int n)) inv.Main.ApplyOrder(_order, n);
foreach (SortPack p in inv.Packs)
if (host.TryGetContainerOrder(p.Id, false, ref _order, out n)) p.ApplyOrder(_order, n);
if (host.TryGetContainerOrder(player, true, ref _order, out n)) inv.ApplyPackOrder(_order, n);
}
return inv;
}
/// <summary>The slot <paramref name="itemId"/> holds in <paramref name="container"/> (the engine's slot order), or -1.</summary>
public int SlotOf(RynthCoreHost host, uint container, uint itemId)
{
if (!host.HasContainerOrder || !host.TryGetContainerOrder(container, false, ref _order, out int n)) return -1;
return Array.IndexOf(_order, itemId, 0, n);
}
private uint[] Contents(RynthCoreHost host, uint container)
{
int n = host.GetContainerContents(container, _buf);

View file

@ -23,6 +23,8 @@ internal struct MoveObservation
public uint Container;
public uint Wielder;
public int Stack;
/// <summary>Its slot in its container (the engine's slot order), or -1 when unknown. Read for reorders only.</summary>
public int Slot;
/// <summary>The engine's refusal counter (TryGetLastWeenieError seq; 0 when unknown).</summary>
public int ErrorSeq;
public uint Error;
@ -52,16 +54,35 @@ internal static class MoveTracker
/// <summary>The longest hold after refusals in a row.</summary>
public const long MaxBackoffMs = 30_000;
/// <summary>The container reads as this when the engine can't say (no ownership info).</summary>
public const uint UnknownContainer = 0xFFFFFFFF;
public const uint EventInventoryServerSaveFailed = 0x00A0;
public const uint ErrorYoureTooBusy = 0x001D;
public const uint ErrorTooManyActions = 0x0045;
/// <summary>
/// What the client says about the move so far. A move within one pack (a stack joined, a slot
/// changed) can't be judged by the item's container, which it never left: a join is answered
/// when the item is gone or smaller, a reorder when the item sits at its slot (or left the pack).
/// </summary>
public static MoveOutcome Observe(MoveInFlight m, in MoveObservation o, long nowMs)
{
SortMove mv = m.Move;
if (!o.Exists) return MoveOutcome.Done; // merged on arrival
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
switch (mv.Kind)
{
case MoveKind.Stack:
if (o.Stack < m.StackAtSend) return MoveOutcome.Done;
break;
case MoveKind.Reorder:
if (o.Container == mv.Dest.Id && o.Slot == mv.Placement) return MoveOutcome.Done;
if (o.Container != mv.Dest.Id && o.Container != UnknownContainer) return MoveOutcome.Done; // someone moved it away
break;
default:
if (o.Container == mv.Dest.Id && o.Wielder == 0) return MoveOutcome.Done;
if (mv.MergeInto != 0 && o.Stack < m.StackAtSend) return MoveOutcome.Done; // part of it joined the stack
break;
}
if (o.ErrorSeq != 0 && o.ErrorSeq != m.ErrorSeqAtSend)
{
if (o.Error == ErrorYoureTooBusy || o.Error == ErrorTooManyActions) return MoveOutcome.TooBusy;

View file

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// Ties rules to their packs' ids. Rules saved before RynthSort kept pack ids only had a number,
/// and the Lua script's numbers counted foci as packs (game.Character.Containers: every container
/// in the main pack, in the same order), so after a focus every imported number pointed one pack
/// too far. Once per character, on a settled read of the packs (<see cref="Apply"/>):
/// <list type="bullet">
/// <item>a rule still as the Lua script had it: Lua number n is the n-th container, foci counted.
/// A pack: the rule takes its id and its number among the real packs. A focus, or nothing there:
/// left as it was, and said so.</item>
/// <item>any other rule (picked in RynthSort's window, or the defaults): its number already counts
/// real packs only, so it takes that pack's id.</item>
/// </list>
/// Pure: the tests drive it with hand-made inventories.
/// </summary>
internal static class PackFix
{
/// <summary>Every side-slot entry's capacity was readable (a focus and a pack can be told apart).</summary>
public static bool Ready(SortInventory inv)
{
foreach (SortSlot s in inv.Slots)
if (s.Capacity < 0) return false;
return true;
}
/// <summary>The side-slot layout (ids and capacities): two reads alike mean the packs have settled.</summary>
public static string Layout(SortInventory inv)
{
var sb = new StringBuilder(inv.Slots.Count * 12);
foreach (SortSlot s in inv.Slots) sb.Append(s.Id.ToString("X8")).Append(':').Append(s.Capacity).Append(';');
return sb.ToString();
}
/// <summary>"Sack - Salvage, Gems".</summary>
public static string NoteOf(SortPack p) => $"{(p.Name.Length > 0 ? p.Name : "Pack")} - {p.Summary()}";
/// <summary>
/// The one-time fix over <paramref name="rules"/> (only rules without a pack id are looked at).
/// <paramref name="imported"/>: the rules came from the Lua script. <paramref name="luaRules"/>:
/// the Lua script's rules as they are in its file (null when it can't be read: every rule is
/// taken as imported). Returns one line per rule it looked at, saying what it did; changed
/// counts the rules it changed.
/// </summary>
public static List<string> Apply(IReadOnlyList<SortRule> rules, SortInventory inv, bool imported, IReadOnlyList<SortRule>? luaRules, out int changed)
{
var lines = new List<string>();
changed = 0;
for (int i = 0; i < rules.Count; i++)
{
SortRule r = rules[i];
if (r.PackId != 0) continue;
string who = $"rule {i + 1} ({SortRules.Describe(r)})";
if (imported && (luaRules == null || Contains(luaRules, r)))
{
int n = r.Pack;
if (n < 1 || n > inv.Slots.Count)
{
lines.Add($"{who}: the Lua script's pack {n} doesn't exist ({Count(inv)}); left as pack {n}");
continue;
}
SortSlot slot = inv.Slots[n - 1];
int idx = inv.IndexOf(slot.Id);
if (!slot.IsPack || idx == 0)
{
lines.Add($"{who}: the Lua script's pack {n} is {(slot.IsPack ? "not a side pack" : "a focus")} (0x{slot.Id:X8}); left as pack {n}");
continue;
}
SortPack p = inv.Packs[idx - 1];
r.PackId = p.Id;
r.Pack = idx;
r.PackNote = NoteOf(p);
changed++;
lines.Add($"{who}: the Lua script's pack {n} -> pack {idx}, {r.PackNote} (0x{p.Id:X8})");
}
else
{
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
{
lines.Add($"{who}: pack {r.Pack}, which you don't have; left as it is");
continue;
}
SortPack p = inv.Packs[r.Pack - 1];
r.PackId = p.Id;
r.PackNote = NoteOf(p);
changed++;
lines.Add($"{who}: pack {r.Pack} kept, now tied to {r.PackNote} (0x{p.Id:X8})");
}
}
return lines;
}
/// <summary>
/// Keeps each rule's number (and note) on its pack when that pack is carried, so the number
/// the window shows and the fallback stay right as packs come and go. True when one changed.
/// </summary>
public static bool Sync(IReadOnlyList<SortRule> rules, SortInventory inv)
{
bool any = false;
foreach (SortRule r in rules)
{
int idx = inv.IndexOf(r.PackId);
if (idx == 0) continue;
if (r.Pack != idx || r.PackNote.Length == 0)
{
r.Pack = idx;
r.PackNote = NoteOf(inv.Packs[idx - 1]);
any = true;
}
}
return any;
}
private static bool Contains(IReadOnlyList<SortRule> list, SortRule r)
{
foreach (SortRule o in list)
if (o.SameAs(r)) return true;
return false;
}
private static string Count(SortInventory inv)
{
int foci = 0;
foreach (SortSlot s in inv.Slots) if (!s.IsPack) foci++;
return $"{inv.Packs.Count} pack{(inv.Packs.Count == 1 ? "" : "s")} and {foci} foc{(foci == 1 ? "us" : "i")}";
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>
/// The order items keep inside a pack, and the moves that get a pack there. Pure: the tests drive it.
///
/// The order: by name A-Z (any case, then exact), so like items sit together; the same name with
/// another kind of stack (class id) next; then by object id, which never changes. Optionally by
/// kind first (the class's label: "Armor", "Gem", ...), then the same. It is a total order on the
/// items, so a pack has exactly one target order however its items got there.
///
/// The moves: one item at a time to a slot (the engine's PutItemInContainer, API v80: placement =
/// the index it should end at, counted without it, which is how ACE inserts). The items already in
/// order relative to each other (a longest increasing run of target ranks) stay; one of the others
/// is put right after the last of those that comes before it. That run grows by at least one with
/// every move, so a pack of n items is in order after at most n - (longest run) moves, and an
/// item that arrived in the right place costs none.
/// </summary>
internal static class PackOrder
{
/// <summary>The target order (see the class summary). <paramref name="kindFirst"/>: by class label first.</summary>
public static int Compare(SortItem a, SortItem b, bool kindFirst)
{
if (ReferenceEquals(a, b)) return 0;
if (kindFirst && a.ObjectClass != b.ObjectClass)
{
int k = string.Compare(ObjectClasses.Label(a.ObjectClass), ObjectClasses.Label(b.ObjectClass), StringComparison.OrdinalIgnoreCase);
if (k != 0) return k;
k = a.ObjectClass.CompareTo(b.ObjectClass);
if (k != 0) return k;
}
string an = a.Name ?? string.Empty, bn = b.Name ?? string.Empty;
int c = string.Compare(an, bn, StringComparison.OrdinalIgnoreCase);
if (c != 0) return c;
c = string.CompareOrdinal(an, bn);
if (c != 0) return c;
c = a.Wcid.CompareTo(b.Wcid);
return c != 0 ? c : a.Id.CompareTo(b.Id);
}
/// <summary>Every item has a name: an item the client hasn't described yet would sort as "" and move again once named.</summary>
public static bool AllNamed(IReadOnlyList<SortItem> items)
{
foreach (SortItem it in items)
if (string.IsNullOrEmpty(it.Name)) return false;
return true;
}
/// <summary>Each item's place in the target order (0 = first), in the items' current order.</summary>
public static int[] Ranks(IReadOnlyList<SortItem> items, bool kindFirst)
{
int n = items.Count;
var idx = new int[n];
for (int i = 0; i < n; i++) idx[i] = i;
Array.Sort(idx, (x, y) => Compare(items[x], items[y], kindFirst));
var rank = new int[n];
for (int r = 0; r < n; r++) rank[idx[r]] = r;
return rank;
}
/// <summary>
/// Which positions are in a longest increasing run of <paramref name="rank"/> (they stay put).
/// O(n^2) over a pack (at most ~100 items); the earliest-ending run is kept, so the answer is
/// the same for the same list.
/// </summary>
public static bool[] Kept(int[] rank)
{
int n = rank.Length;
var len = new int[n];
var prev = new int[n];
int best = -1;
for (int i = 0; i < n; i++)
{
len[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++)
if (rank[j] < rank[i] && len[j] + 1 > len[i]) { len[i] = len[j] + 1; prev[i] = j; }
if (best < 0 || len[i] > len[best]) best = i;
}
var kept = new bool[n];
for (int i = best; i >= 0; i = prev[i]) kept[i] = true;
return kept;
}
/// <summary>How many items are out of place (would move): 0 = in order.</summary>
public static int OutOfPlace(IReadOnlyList<SortItem> items, bool kindFirst)
{
if (items.Count < 2) return 0;
bool[] kept = Kept(Ranks(items, kindFirst));
int n = 0;
foreach (bool k in kept) if (!k) n++;
return n;
}
/// <summary>
/// The next move that puts the pack in order: the out-of-place item with the lowest target rank
/// that <paramref name="movable"/> allows, and the slot it goes to (counted without it). False
/// when the pack is in order, or only items that can't move now are out of place.
/// </summary>
public static bool NextMove(IReadOnlyList<SortItem> items, bool kindFirst, Func<SortItem, bool> movable, out SortItem item, out int placement)
{
item = null!;
placement = -1;
int n = items.Count;
if (n < 2) return false;
int[] rank = Ranks(items, kindFirst);
bool[] kept = Kept(rank);
int pick = -1;
for (int i = 0; i < n; i++)
if (!kept[i] && movable(items[i]) && (pick < 0 || rank[i] < rank[pick])) pick = i;
if (pick < 0) return false;
// Right after the last kept item that comes before it in the target order.
int after = -1;
for (int i = 0; i < n; i++)
if (kept[i] && rank[i] < rank[pick]) after = i; // kept items rise with i: the last one wins
item = items[pick];
placement = after < 0 ? 0 : (after > pick ? after : after + 1);
return true;
}
/// <summary>
/// The slot an item arriving in a pack should take so it lands where the order wants it: after
/// every item there that comes before it. In a pack already in order that is its final place.
/// </summary>
public static int InsertAt(IReadOnlyList<SortItem> items, SortItem arriving, bool kindFirst)
{
int at = 0;
for (int i = 0; i < items.Count; i++)
if (Compare(items[i], arriving, kindFirst) < 0) at = i + 1;
return at;
}
/// <summary>
/// The list after moving <paramref name="item"/> to <paramref name="placement"/> as ACE does it
/// (taken out, the others close up, put in at that index, clamped to the end). For the tests'
/// pretend server and the planner's checks.
/// </summary>
public static void Apply(List<SortItem> items, SortItem item, int placement)
{
items.Remove(item);
items.Insert(Math.Clamp(placement, 0, items.Count), item);
}
}

View file

@ -11,19 +11,36 @@ internal interface ISortWorld
SortInventory? ReadInventory();
/// <summary>The "stay out of the way" inputs now.</summary>
GateInputs ReadGate(bool sortInCombat, long nowMs);
/// <summary>Sends the move to the client (merge or plain move). False = the engine refused it.</summary>
/// <summary>Sends the move to the client (merge, move to a slot, or plain move). False = the engine refused it.</summary>
bool SendMove(in SortMove move);
/// <summary>The moved item and the server's last refusal.</summary>
MoveObservation Observe(uint itemId);
/// <summary>The moved item (its slot too, for a reorder) and the server's last refusal.</summary>
MoveObservation Observe(in SortMove move);
/// <summary>The engine's refusal counter now (0 when the engine can't say).</summary>
int ErrorSeqNow();
/// <summary>What this engine lets the planner do beyond moving items to their packs.</summary>
SortAbilities Abilities { get; }
}
/// <summary>What the engine can do for RynthSort (the plugin asks the host; the tests say).</summary>
internal struct SortAbilities
{
/// <summary>Slot orders are readable (API v80 GetContainerOrder).</summary>
public bool ReadOrder;
/// <summary>A move can name its slot (API v80 PutItemInContainer, bound on this client).</summary>
public bool PlaceMoves;
/// <summary>Stacks can be merged (MergeStackInternal).</summary>
public bool Merge;
public static SortAbilities All => new() { ReadOrder = true, PlaceMoves = true, Merge = true };
}
/// <summary>
/// The sorting loop, one step per plugin tick: one move at a time, each waited on until the
/// server answers it (the item lands, or it is refused, or the time limit passes), then a gap.
/// Auto-sort moves new main-pack items after the settle time, one per gap; a job asked for
/// (Sort now, Tidy, Clean, Unpack) goes as fast as the server answers. Nothing is sent while the
/// Auto-sort keeps every pack tidy (<see cref="SortScope.All"/>): new main-pack items go to their
/// packs after the settle time, misplaced side-pack items to theirs, then stacks are joined and
/// items put in order inside each pack, one move per gap; a job asked for (Sort now, Clean,
/// Unpack) goes as fast as the server answers. Nothing is sent while the
/// gate says why not (<see cref="SortGate"/>). An item that fails is left alone for a minute, and
/// failures in a row hold every move off longer and longer (<see cref="MoveTracker.BackoffMs"/>).
/// </summary>
@ -52,16 +69,25 @@ internal sealed class SortController
public RynthAiActivity? LastBot { get; private set; }
/// <summary>The last few moves and job results, newest first.</summary>
public readonly List<string> Log = new();
/// <summary>What the engine allowed at the last tick (the window says when ordering isn't possible).</summary>
public SortAbilities Abilities { get; private set; }
public int Moved { get; private set; }
public int Failed { get; private set; }
/// <summary>Settings changed by a command (auto-sort off for Unpack): the plugin saves.</summary>
public Action? SettingsChanged;
/// <summary>The one-time pack fix ran (<see cref="PackFix"/>): its lines and how many rules it changed. The plugin logs and saves.</summary>
public Action<List<string>, int>? PacksFixed;
/// <summary>How long the side-slot layout must read the same before the one-time pack fix runs.</summary>
public const long FixSettleMs = 3000;
private MoveInFlight? _inFlight;
private long _nextStepMs;
private long _nextViewMs;
private int _failuresInARow;
private string? _fixLayout;
private long _fixLayoutSince;
public bool HasMoveOut => _inFlight != null;
@ -73,6 +99,7 @@ internal sealed class SortController
_inFlight = null;
_nextStepMs = _nextViewMs = 0;
_failuresInARow = 0;
_fixLayout = null;
Job = null;
UnpackWhich = null;
LastBot = null;
@ -107,6 +134,25 @@ internal sealed class SortController
SettingsChanged?.Invoke();
}
// Items put in order in one pack go in the log as one line that counts up.
private string? _reorderRunLine;
private int _reorderRunPack = -1, _reorderRunCount;
private void NoteReorderRun(in SortMove m)
{
if (_reorderRunLine != null && _reorderRunPack == m.DestIndex && Log.Count > 0 && ReferenceEquals(Log[0], _reorderRunLine))
{
_reorderRunCount++;
Log[0] = _reorderRunLine = $"{_reorderRunCount} items put in order in {m.DestLabel}";
return;
}
_reorderRunPack = m.DestIndex;
_reorderRunCount = 1;
string name = m.Item.Name.Length > 0 ? m.Item.Name : $"0x{m.Item.Id:X8}";
Note($"{name} {m.Done}");
_reorderRunLine = Log[0];
}
public void Note(string line)
{
Log.Insert(0, line);
@ -117,9 +163,10 @@ internal sealed class SortController
public void Tick(ISortWorld world, long nowMs)
{
Abilities = world.Abilities;
if (_inFlight != null)
{
MoveObservation o = world.Observe(_inFlight.Move.Item.Id);
MoveObservation o = world.Observe(in _inFlight.Move);
MoveOutcome outcome = MoveTracker.Observe(_inFlight, in o, nowMs);
if (outcome == MoveOutcome.Pending) return;
Finish(_inFlight.Move, outcome, nowMs);
@ -128,12 +175,12 @@ internal sealed class SortController
}
if (nowMs < _nextStepMs) return;
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.Main : null);
SortScope? scope = Job ?? (Data.Settings.Auto ? SortScope.All : null);
if (scope == null)
{
Status = "off";
LastBot = null;
RefreshView(world, SortScope.Main, nowMs);
RefreshView(world, SortScope.All, nowMs);
_nextStepMs = nowMs + PollMs;
return;
}
@ -157,9 +204,17 @@ internal sealed class SortController
return;
}
_nextViewMs = nowMs + ViewMs;
if (!AfterRead(inv, nowMs))
{
// Rules not tied to their packs yet: nothing moves by a number that may be wrong.
Status = "reading your packs";
Planner.Plan(inv, Data.Rules, SortScope.Main, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
_nextStepMs = nowMs + PollMs;
return;
}
List<SortMove> moves = scope == SortScope.Unpack
? Planner.PlanUnpack(inv, UnpackWhich, nowMs)
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000);
: Planner.Plan(inv, Data.Rules, scope.Value, force: Job != null, nowMs, Data.Settings.SettleSec * 1000, Options(world));
if (moves.Count == 0)
{
@ -174,12 +229,26 @@ internal sealed class SortController
Status = scope == SortScope.Unpack ? "unpacking" : "sorting";
SortMove m = moves[0];
int seq = world.ErrorSeqNow();
int stack = m.Item.Stack; // as read before the send (a merge's answer is a smaller stack)
if (!world.SendMove(in m))
{
Finish(m, MoveOutcome.Refused, nowMs, "the engine refused the move");
return;
}
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = m.Item.Stack };
_inFlight = new MoveInFlight { Move = m, SentMs = nowMs, ErrorSeqAtSend = seq, StackAtSend = stack };
}
/// <summary>What the planner may do: the engine's abilities and the settings.</summary>
internal PlanOptions Options(ISortWorld world)
{
SortAbilities a = world.Abilities;
return new PlanOptions
{
Order = a.ReadOrder && a.PlaceMoves && Data.Settings.OrderInPacks,
KindFirst = Data.Settings.OrderKindFirst,
Place = a.ReadOrder && a.PlaceMoves,
Merge = a.Merge,
};
}
private void NoteJobDone(SortScope job)
@ -189,7 +258,7 @@ internal sealed class SortController
{
case SortScope.Unpack: Note(v.MainFull ? "Main pack is full: unpacking stopped" : "Side packs emptied"); break;
case SortScope.Clean: Note(v.MainFull ? "Main pack is full: some strays left" : "Packs cleaned"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs tidied ({v.Waiting} can't move yet)" : "Packs tidied"); break;
case SortScope.All: Note(v.Waiting > 0 ? $"Packs sorted ({v.Waiting} can't move yet)" : "Packs sorted"); break;
default: Note(v.Waiting > 0 ? $"Main pack sorted ({v.Waiting} can't move yet)" : "Main pack sorted"); break;
}
}
@ -203,7 +272,16 @@ internal sealed class SortController
case MoveOutcome.Done:
Moved++;
_failuresInARow = 0;
Note($"{name} -> {m.DestLabel}");
if (m.Kind == MoveKind.Reorder)
{
Planner.NoteReorder(m.Item.Id, nowMs);
NoteReorderRun(m);
}
else
{
_reorderRunLine = null;
Note($"{name} {m.Done}");
}
_nextStepMs = nowMs + gap;
return;
case MoveOutcome.TooBusy:
@ -223,6 +301,32 @@ internal sealed class SortController
}
}
/// <summary>
/// After each read: the one-time pack fix once the side slots have read the same for
/// <see cref="FixSettleMs"/> (a pack whose capacity isn't readable yet could pass for a focus),
/// then each rule's number kept on its pack. False while imported rules still wait for the fix
/// (their numbers may name the wrong pack); rules saved by RynthSort meant what they say and
/// sort on meanwhile.
/// </summary>
private bool AfterRead(SortInventory inv, long nowMs)
{
if (!Data.PacksFixed)
{
bool hold = Data.ImportedFrom.Length > 0;
if (!PackFix.Ready(inv)) { _fixLayout = null; return !hold; }
string layout = PackFix.Layout(inv);
if (layout != _fixLayout) { _fixLayout = layout; _fixLayoutSince = nowMs; return !hold; }
if (nowMs - _fixLayoutSince < FixSettleMs) return !hold;
List<string> lines = PackFix.Apply(Data.Rules, inv, hold, Data.LuaRules, out int changed);
Data.PacksFixed = true;
Data.LuaRules = null;
if (hold) Note($"Imported pack numbers fixed: {changed} of {lines.Count} rules");
PacksFixed?.Invoke(lines, changed);
}
if (PackFix.Sync(Data.Rules, inv)) SettingsChanged?.Invoke();
return true;
}
/// <summary>Re-reads the packs for the window now and then while nothing moves.</summary>
private void RefreshView(ISortWorld world, SortScope scope, long nowMs)
{
@ -230,7 +334,8 @@ internal sealed class SortController
_nextViewMs = nowMs + ViewMs;
SortInventory? inv = world.ReadInventory();
if (inv == null) return;
AfterRead(inv, nowMs);
if (scope == SortScope.Unpack) Planner.PlanUnpack(inv, UnpackWhich, nowMs);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000);
else Planner.Plan(inv, Data.Rules, scope, force: false, nowMs, Data.Settings.SettleSec * 1000, Options(world));
}
}

View file

@ -99,7 +99,10 @@ internal sealed class LootWatch
{
if (containerId != 0)
{
if (containerId != _id || itemCount != _count)
// An unreadable count (-1) is not a change: a count read that flickered between -1 and
// the real number made a corpse left open look like it was being looted for ever
// ("paused: looting" while standing still, 2026-10-11).
if (containerId != _id || (itemCount >= 0 && itemCount != _count))
{
_id = containerId;
_count = itemCount;

View file

@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthSort.Sorting;
@ -24,11 +26,140 @@ internal sealed class SortPack
/// <summary>How many items it holds (ItemsCapacity; 102 for the main pack and 24 for a side pack when unknown).</summary>
public int Capacity;
public readonly List<SortItem> Items = new();
/// <summary>
/// <see cref="Items"/> are in the pack's real slot order (slot 0 first: the engine's
/// GetContainerOrder, API v80, agreed with the contents read). False: object-id order, and
/// nothing is reordered in this pack.
/// </summary>
public bool OrderKnown;
/// <summary>
/// Puts <see cref="Items"/> in <paramref name="order"/> (the pack's slot order) when that names
/// exactly the items read, each once; else leaves them and <see cref="OrderKnown"/> false (a
/// list a move behind the contents, or a pack the server hasn't listed: never guessed).
/// </summary>
public bool ApplyOrder(IReadOnlyList<uint> order, int count)
{
OrderKnown = false;
if (count != Items.Count) return false;
var byId = new Dictionary<uint, SortItem>(Items.Count);
foreach (SortItem it in Items)
if (!byId.TryAdd(it.Id, it)) return false;
var sorted = new List<SortItem>(count);
for (int i = 0; i < count; i++)
{
if (!byId.Remove(order[i], out SortItem? it)) return false; // unknown here, or listed twice
sorted.Add(it);
}
Items.Clear();
Items.AddRange(sorted);
OrderKnown = true;
return true;
}
/// <summary>
/// What is in it, in a few words: the 2-3 commonest kinds of item ("Salvage, Gems"), by
/// class, or by name for the classes that say little (Misc, Unknown); "empty" when empty.
/// </summary>
public string Summary(int most = 3)
{
if (Items.Count == 0) return "empty";
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
var order = new List<string>();
foreach (SortItem it in Items)
{
string key = KindOf(it);
if (key.Length == 0) continue;
if (counts.TryGetValue(key, out int n)) counts[key] = n + 1;
else { counts[key] = 1; order.Add(key); }
}
if (order.Count == 0) return "unknown items";
// Commonest first; a tie keeps the order the kinds were met in.
var ranked = new List<string>(order);
ranked.Sort((a, b) => counts[a] != counts[b] ? counts[b].CompareTo(counts[a]) : order.IndexOf(a).CompareTo(order.IndexOf(b)));
var sb = new StringBuilder();
for (int i = 0; i < ranked.Count && i < most; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(ranked[i]);
}
return sb.ToString();
}
/// <summary>The kind an item counts as in <see cref="Summary"/>.</summary>
internal static string KindOf(SortItem it)
{
int c = it.ObjectClass;
if (c == ObjectClasses.Misc || c == ObjectClasses.Unknown || c == ObjectClasses.Bundle)
return Shorten(it.Name);
return ObjectClasses.Plural(c);
}
private static string Shorten(string? name)
{
string n = (name ?? string.Empty).Trim();
return n.Length <= 24 ? n : n[..23] + "~";
}
}
/// <summary>The character's packs: the main pack and the side packs in order, top to bottom (pack 1 first).</summary>
/// <summary>A side-slot thing in the main pack (a side pack or a focus), in the client's list order.</summary>
internal readonly struct SortSlot
{
public readonly uint Id;
/// <summary>ItemsCapacity: above 0 for a side pack, 0 for a focus, -1 when it couldn't be read.</summary>
public readonly int Capacity;
public SortSlot(uint id, int capacity)
{
Id = id;
Capacity = capacity;
}
public bool IsPack => Capacity > 0;
}
/// <summary>
/// The character's packs: the main pack and the side packs, pack 1 first. With the engine's slot
/// order (API v80) that is the pack column on screen, top first (<see cref="PackOrderKnown"/>);
/// else GetContainerContents' order, by object id. Rules keep the pack's id either way, so a
/// pack keeps its rules whatever its number.
/// </summary>
internal sealed class SortInventory
{
public SortPack Main = new();
public readonly List<SortPack> Packs = new();
/// <summary>
/// Every container entry in the main pack, foci included, in object-id order (what the Lua
/// script numbered its packs by: game.Character.Containers). Never reordered: the one-time
/// fix of imported Lua pack numbers (<see cref="PackFix"/>) reads the Lua numbers through it.
/// </summary>
public readonly List<SortSlot> Slots = new();
/// <summary><see cref="Packs"/> are in the pack column's order, top first.</summary>
public bool PackOrderKnown;
/// <summary>
/// Puts <see cref="Packs"/> in the pack column's order: <paramref name="order"/> is the main
/// pack's side-slot list (packs and foci, top first). Only when it names every pack read; else
/// the packs keep their order and <see cref="PackOrderKnown"/> is false.
/// </summary>
public bool ApplyPackOrder(IReadOnlyList<uint> order, int count)
{
PackOrderKnown = false;
var rank = new Dictionary<uint, int>(count);
for (int i = 0; i < count; i++) rank.TryAdd(order[i], i);
foreach (SortPack p in Packs)
if (!rank.ContainsKey(p.Id)) return false;
Packs.Sort((a, b) => rank[a.Id].CompareTo(rank[b.Id]));
PackOrderKnown = true;
return true;
}
/// <summary>The 1-based number of side pack <paramref name="id"/>, or 0 when it isn't carried.</summary>
public int IndexOf(uint id)
{
if (id == 0) return 0;
for (int i = 0; i < Packs.Count; i++)
if (Packs[i].Id == id) return i + 1;
return 0;
}
}

View file

@ -6,9 +6,13 @@ namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>What a planning pass looks at.</summary>
internal enum SortScope
{
/// <summary>Only the main pack; an item moves once it has sat there for the settle time (unless forced).</summary>
/// <summary>Only the main pack's items to their packs; an item moves once it has sat there for the settle time (unless forced).</summary>
Main,
/// <summary>Every pack, no settling: items in the wrong side pack move to theirs too ("Tidy").</summary>
/// <summary>
/// Every pack: main-pack items to their packs (after the settle time unless forced), items in the
/// wrong side pack to theirs, then (with <see cref="PlanOptions"/>) stacks joined and items put
/// in order inside each pack. Auto-sort ("keep every pack tidy"), and Sort now (forced).
/// </summary>
All,
/// <summary>As <see cref="All"/>, and side-pack items no rule wants go back to the main pack ("Clean").</summary>
Clean,
@ -16,6 +20,17 @@ internal enum SortScope
Unpack,
}
/// <summary>What a move does.</summary>
internal enum MoveKind : byte
{
/// <summary>To another pack (maybe joining a stack there, maybe at a slot).</summary>
Route,
/// <summary>Joins another stack of the same kind in its own pack (<see cref="SortMove.MergeInto"/>).</summary>
Stack,
/// <summary>To another slot in its own pack (<see cref="SortMove.Placement"/>).</summary>
Reorder,
}
/// <summary>One move: <see cref="Item"/> into <see cref="Dest"/> (pack <see cref="DestIndex"/>, 0 = main pack).</summary>
internal readonly struct SortMove
{
@ -24,24 +39,78 @@ internal readonly struct SortMove
public readonly int DestIndex;
/// <summary>A stack in <see cref="Dest"/> the item joins (a merge), or 0 for a plain move.</summary>
public readonly uint MergeInto;
/// <summary>The slot in <see cref="Dest"/> it should end at (counted without it), or -1: the first empty slot.</summary>
public readonly int Placement;
public readonly MoveKind Kind;
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto)
public SortMove(SortItem item, SortPack dest, int destIndex, uint mergeInto, int placement = -1, MoveKind kind = MoveKind.Route)
{
Item = item;
Dest = dest;
DestIndex = destIndex;
MergeInto = mergeInto;
Placement = placement;
Kind = kind;
}
/// <summary>The item is already in <see cref="Dest"/> (a stack joined or a slot changed there).</summary>
public bool InPlace => Kind != MoveKind.Route;
public string DestLabel => DestIndex == 0 ? "main pack" : "pack " + DestIndex;
/// <summary>What the log says it did: "-> pack 2", "stacked in pack 2", "put in order in pack 2".</summary>
public string Done => Kind switch
{
MoveKind.Stack => "stacked in " + DestLabel,
MoveKind.Reorder => "put in order in " + DestLabel,
_ => "-> " + DestLabel,
};
}
/// <summary>What a planning pass may do beyond moving items to their packs (what the engine and the settings allow).</summary>
internal struct PlanOptions
{
/// <summary>Put items in order inside each pack whose slot order is known (API v80 and the "order" setting).</summary>
public bool Order;
/// <summary>The order groups by kind (class) first, then name.</summary>
public bool KindFirst;
/// <summary>Moves can name a slot (API v80): an item going to a pack whose order is known lands in its place.</summary>
public bool Place;
/// <summary>Stacks of the same kind in one pack are joined (the engine can merge stacks).</summary>
public bool Merge;
/// <summary>Everything on: an engine with API v80 and the default settings.</summary>
public static PlanOptions Full => new() { Order = true, Place = true, Merge = true };
}
/// <summary>A side pack as the window lists it.</summary>
internal sealed class PackLine
{
public uint Id;
public string Name = string.Empty;
public int Used;
public int Capacity;
/// <summary>What is in it, in a few words (<see cref="SortPack.Summary"/>).</summary>
public string Summary = string.Empty;
/// <summary>Its slot order is known (it can be put in order).</summary>
public bool OrderKnown;
/// <summary>Items out of place in it (0 = in order; only counted when the order is known and ordering is on).</summary>
public int OutOfPlace;
/// <summary>"Sack (12/24) - Salvage, Gems".</summary>
public string Label => $"{Name} ({Used}/{Capacity}) - {Summary}";
/// <summary>"Sack - Salvage, Gems": what a rule remembers of its pack.</summary>
public string Note => $"{Name} - {Summary}";
}
/// <summary>A rule whose pack isn't carried: it goes nowhere (<see cref="UsedPack"/> 0) or to the pack its number names.</summary>
internal sealed class RulePackIssue
{
public SortRule Rule = null!;
/// <summary>1-based place in the rule list.</summary>
public int RuleNumber;
/// <summary>The side pack used instead (its number), or 0 when the rule has none.</summary>
public int UsedPack;
}
/// <summary>What the window shows about the packs after a planning pass.</summary>
@ -50,30 +119,54 @@ internal sealed class SortView
public readonly List<PackLine> Packs = new();
public int MainUsed;
public int MainCapacity;
/// <summary>The main pack as a line (its order state; Id is the player).</summary>
public PackLine Main = new();
/// <summary>The packs are numbered top to bottom as the pack column shows them (else by object id).</summary>
public bool PackOrderKnown;
/// <summary>The pass could put items in order (the engine reads slot orders and ordering is on).</summary>
public bool Ordering;
/// <summary>Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full).</summary>
public int Waiting;
/// <summary>Side packs (1-based) a rule wants to fill that are full.</summary>
public readonly SortedSet<int> Full = new();
/// <summary>Pack numbers rules use that the character doesn't have.</summary>
/// <summary>Pack numbers rules (that are on) use and the character doesn't have.</summary>
public readonly SortedSet<int> Missing = new();
/// <summary>Rules (that are on) whose pack isn't carried, in rule order.</summary>
public readonly List<RulePackIssue> Issues = new();
/// <summary>Clean or Unpack found the main pack full.</summary>
public bool MainFull;
}
/// <summary>
/// The sorting rules applied to the packs: which items move where, one planning pass at a time.
/// A port of the Lua script's plan/planUnpack: rules are tried in order and the first match wins;
/// worn and wielded items, packs and foci never move; a full pack is only used when the item
/// joins a stack there; an item that failed to move is left alone until its block runs out.
/// Each item has one place: the pack of the rule it follows (<see cref="SortRules.RuleFor"/>; the
/// pack its id names, else its number: <see cref="SortRules.Resolve"/>), or where it is when no
/// rule wants it (Clean: back to the main pack). Worn and wielded items, packs and foci never
/// move; a full pack is only used when the item joins a stack there; an item that failed to move
/// is left alone until its block runs out.
///
/// With <see cref="PlanOptions"/>, once nothing needs to change packs, every pack is tidied in
/// place: two stacks of one kind are joined, then items are put in order (<see cref="PackOrder"/>).
/// The main pack only once every item in it has settled.
///
/// It converges: a route takes an item to its one place and nothing sends it back (its place
/// depends on the rules and the packs carried, not on where it is); a join leaves one stack fewer
/// that isn't full; a reorder grows the run of items already in order. Each kind of move is
/// finite, so a fixed inventory runs out of moves. As a backstop, an item put in order
/// <see cref="MaxReorders"/> times within <see cref="ReorderWindowMs"/> isn't reordered again
/// until that window passes (an order the engine and the server see differently can't loop).
/// Pure (no host calls): the tests drive it with hand-made inventories.
/// </summary>
internal sealed class SortPlanner
{
public const int SideCapacityFallback = 24;
public const int MainCapacityFallback = 102;
public const int MaxReorders = 6;
public const long ReorderWindowMs = 10 * 60_000;
private readonly Dictionary<uint, long> _firstSeen = new();
private readonly Dictionary<uint, long> _blocked = new();
private readonly Dictionary<uint, (int Count, long Since)> _reorders = new();
public SortView View { get; private set; } = new();
@ -82,6 +175,7 @@ internal sealed class SortPlanner
{
_firstSeen.Clear();
_blocked.Clear();
_reorders.Clear();
View = new SortView();
}
@ -97,6 +191,17 @@ internal sealed class SortPlanner
return n;
}
/// <summary>An item was put in order (a reorder move landed).</summary>
public void NoteReorder(uint itemId, long nowMs)
{
if (_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs) _reorders[itemId] = (r.Count + 1, r.Since);
else _reorders[itemId] = (1, nowMs);
}
/// <summary>The item has been put in order <see cref="MaxReorders"/> times lately: not again for now.</summary>
public bool ReorderLimited(uint itemId, long nowMs) =>
_reorders.TryGetValue(itemId, out var r) && nowMs - r.Since < ReorderWindowMs && r.Count >= MaxReorders;
/// <summary>Worn and wielded items, packs and foci never move.</summary>
public static bool Sortable(SortItem it) =>
!it.Wielded && it.ObjectClass != ObjectClasses.Container && it.ObjectClass != ObjectClasses.Foci;
@ -119,24 +224,69 @@ internal sealed class SortPlanner
return 0;
}
private static bool SameKind(SortItem a, SortItem b) =>
internal static bool SameKind(SortItem a, SortItem b) =>
a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal) && a.Name.Length > 0;
private static bool HasRoom(SortItem it) => it.MaxStack > 1 && it.Stack < it.MaxStack;
/// <summary>
/// Two stacks of one kind in <paramref name="pack"/> that both have room: the smaller one
/// (<paramref name="from"/>) joins the larger (<paramref name="into"/>). The first such kind in
/// the pack's order; the same answer for the same pack. False when every kind has at most one
/// stack with room.
/// </summary>
public static bool StackJoin(SortPack pack, Func<SortItem, bool> movable, out SortItem from, out SortItem into)
{
from = into = null!;
List<SortItem> items = pack.Items;
var seen = new bool[items.Count];
for (int i = 0; i < items.Count; i++)
{
if (seen[i] || !HasRoom(items[i]) || !Sortable(items[i])) continue;
SortItem? small = null, big = null;
for (int j = i; j < items.Count; j++)
{
SortItem it = items[j];
if (j > i && (seen[j] || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it))) continue;
seen[j] = true;
if (big == null || it.Stack > big.Stack || (it.Stack == big.Stack && it.Id < big.Id)) big = it;
}
foreach (SortItem it in items)
{
if (ReferenceEquals(it, big) || !HasRoom(it) || !Sortable(it) || !SameKind(items[i], it) || !movable(it)) continue;
if (small == null || it.Stack < small.Stack || (it.Stack == small.Stack && it.Id > small.Id)) small = it;
}
if (small != null && big != null) { from = small; into = big; return true; }
}
return false;
}
/// <summary>The moves to make now (routes only, as before ordering existed). See the overload.</summary>
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs) =>
Plan(inv, rules, scope, force, nowMs, settleMs, default);
/// <summary>
/// The moves to make now for <paramref name="scope"/> (not <see cref="SortScope.Unpack"/>: see
/// <see cref="PlanUnpack"/>), first one first. Also refreshes <see cref="View"/> and the main
/// pack's settle clock (an item's time starts when a pass first sees it in the main pack).
/// <see cref="PlanUnpack"/>), first one first: items to their packs, then (All and Clean, with
/// <paramref name="opt"/>, when no item needs another pack) stacks joined, then items put in
/// order, a pack at a time. Also refreshes <see cref="View"/> and the main pack's settle clock
/// (an item's time starts when a pass first sees it in the main pack).
/// </summary>
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs)
public List<SortMove> Plan(SortInventory inv, IReadOnlyList<SortRule> rules, SortScope scope, bool force, long nowMs, int settleMs, PlanOptions opt)
{
bool everyPack = scope != SortScope.Main;
bool evict = scope == SortScope.Clean;
bool inPack = scope is SortScope.All or SortScope.Clean;
var moves = new List<SortMove>();
var view = new SortView();
var used = new int[inv.Packs.Count + 1];
for (int i = 0; i < inv.Packs.Count; i++) used[i + 1] = inv.Packs[i].Items.Count;
int mainUsed = inv.Main.Items.Count;
int mainCap = CapacityOf(inv.Main, MainCapacityFallback);
bool kindFirst = opt.KindFirst;
int PlaceIn(SortPack dest, SortItem wo, uint joins) =>
opt.Place && joins == 0 && dest.OrderKnown ? PackOrder.InsertAt(dest.Items, wo, kindFirst) : -1;
void Consider(SortItem wo, int from, bool settled)
{
@ -148,7 +298,7 @@ internal sealed class SortPlanner
uint joins = StackTarget(wo, inv.Main);
if (mainUsed < mainCap || joins != 0)
{
moves.Add(new SortMove(wo, inv.Main, 0, joins));
moves.Add(new SortMove(wo, inv.Main, 0, joins, PlaceIn(inv.Main, wo, joins)));
if (joins == 0) mainUsed++;
}
else
@ -158,18 +308,19 @@ internal sealed class SortPlanner
}
return;
}
if (r == null || r.Pack == from) return;
if (r.Pack < 1 || r.Pack > inv.Packs.Count)
if (r == null) return;
int to = SortRules.Resolve(r, inv, out _);
if (to == 0)
{
view.Missing.Add(r.Pack);
view.Waiting++;
view.Waiting++; // reported once per rule below (Issues / Missing)
return;
}
SortPack dest = inv.Packs[r.Pack - 1];
if (to == from) return;
SortPack dest = inv.Packs[to - 1];
uint into = StackTarget(wo, dest);
if (used[r.Pack] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
if (used[to] >= CapacityOf(dest, SideCapacityFallback) && into == 0)
{
view.Full.Add(r.Pack);
view.Full.Add(to);
view.Waiting++;
return;
}
@ -178,16 +329,19 @@ internal sealed class SortPlanner
view.Waiting++;
return;
}
moves.Add(new SortMove(wo, dest, r.Pack, into));
if (into == 0) used[r.Pack]++;
moves.Add(new SortMove(wo, dest, to, into, PlaceIn(dest, wo, into)));
if (into == 0) used[to]++;
}
var inMain = new HashSet<uint>();
bool mainSettled = true;
foreach (SortItem wo in inv.Main.Items)
{
inMain.Add(wo.Id);
if (!_firstSeen.TryGetValue(wo.Id, out long seen)) _firstSeen[wo.Id] = seen = nowMs;
Consider(wo, 0, force || everyPack || nowMs - seen >= settleMs);
bool settled = force || nowMs - seen >= settleMs;
if (!settled) mainSettled = false;
Consider(wo, 0, settled);
}
if (_firstSeen.Count > inMain.Count)
{
@ -201,7 +355,35 @@ internal sealed class SortPlanner
foreach (SortItem wo in inv.Packs[i].Items) Consider(wo, i + 1, true);
}
FillPacks(view, inv);
bool ordering = inPack && opt.Order;
if (inPack && moves.Count == 0)
{
// Nothing changes packs: tidy each pack in place. Side packs first, then the main pack
// once nothing in it is new (loot still settling there would be ordered twice).
bool Movable(SortItem it) => Sortable(it) && !IsBlocked(it.Id, nowMs);
var stacks = new List<SortMove>();
var reorders = new List<SortMove>();
for (int i = 0; i <= inv.Packs.Count; i++)
{
bool main = i == inv.Packs.Count;
if (main && !mainSettled) break;
SortPack pack = main ? inv.Main : inv.Packs[i];
int index = main ? 0 : i + 1;
if (opt.Merge && StackJoin(pack, Movable, out SortItem from, out SortItem into))
{
stacks.Add(new SortMove(from, pack, index, into.Id, -1, MoveKind.Stack));
continue;
}
if (ordering && pack.OrderKnown && PackOrder.AllNamed(pack.Items)
&& PackOrder.NextMove(pack.Items, kindFirst, it => Movable(it) && !ReorderLimited(it.Id, nowMs), out SortItem item, out int at))
reorders.Add(new SortMove(item, pack, index, 0, at, MoveKind.Reorder));
}
moves.AddRange(stacks);
moves.AddRange(reorders);
}
FillPacks(view, inv, ordering, kindFirst);
FillIssues(view, inv, rules);
View = view;
return moves;
}
@ -232,21 +414,44 @@ internal sealed class SortPlanner
}
}
var view = new SortView { Waiting = waiting, MainFull = waiting > 0 };
FillPacks(view, inv);
FillPacks(view, inv, false, false);
View = view;
return moves;
}
private static void FillPacks(SortView view, SortInventory inv)
private static PackLine LineOf(SortPack p, int capacityFallback, bool ordering, bool kindFirst) => new()
{
Id = p.Id,
Name = p.Name.Length > 0 ? p.Name : "Pack",
Used = p.Items.Count,
Capacity = CapacityOf(p, capacityFallback),
Summary = p.Summary(),
OrderKnown = p.OrderKnown,
OutOfPlace = ordering && p.OrderKnown ? PackOrder.OutOfPlace(p.Items, kindFirst) : 0,
};
private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst)
{
view.MainUsed = inv.Main.Items.Count;
view.MainCapacity = CapacityOf(inv.Main, MainCapacityFallback);
foreach (SortPack p in inv.Packs)
view.Packs.Add(new PackLine
{
Name = p.Name.Length > 0 ? p.Name : "Pack",
Used = p.Items.Count,
Capacity = CapacityOf(p, SideCapacityFallback),
});
view.Main = LineOf(inv.Main, MainCapacityFallback, ordering, kindFirst);
view.Main.Name = "Main pack";
view.PackOrderKnown = inv.PackOrderKnown;
view.Ordering = ordering;
foreach (SortPack p in inv.Packs) view.Packs.Add(LineOf(p, SideCapacityFallback, ordering, kindFirst));
}
/// <summary>Every rule that is on and whose pack isn't carried (whether or not an item wants it now).</summary>
private static void FillIssues(SortView view, SortInventory inv, IReadOnlyList<SortRule> rules)
{
for (int i = 0; i < rules.Count; i++)
{
SortRule r = rules[i];
if (!r.On) continue;
int to = SortRules.Resolve(r, inv, out bool fellBack);
if (to != 0 && !fellBack) continue;
if (to == 0) view.Missing.Add(r.Pack);
view.Issues.Add(new RulePackIssue { Rule = r, RuleNumber = i + 1, UsedPack = to });
}
}
}

View file

@ -1,35 +1,132 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.RynthSort.Sorting;
/// <summary>Which test a rule makes.</summary>
internal enum RuleKind
{
/// <summary>The item's ObjectClass equals <see cref="SortRule.Class"/>.</summary>
Class = 0,
/// <summary>The item's name contains <see cref="SortRule.Text"/> (any case).</summary>
Name = 1,
}
/// <summary>
/// One rule: items it matches go to side pack <see cref="Pack"/> (1 = the first side pack, top to
/// bottom). The same fields as the Lua script's rules: { on, kind = "class" | "name", class, text, pack }.
/// One rule: items whose class is one of <see cref="Classes"/>, or whose name contains one of
/// <see cref="Names"/> (any case), go to the side pack <see cref="PackId"/> names while it is
/// carried, else to side pack number <see cref="Pack"/> (1 = the top side pack when the pack
/// order is known). "Armor, Clothing, name has Shield -> pack 4" is one rule.
/// A rule saved before rules held several entries (the Lua script's { kind, class | text }, and
/// RynthSort's file versions 1 and 2) loads as a rule with one entry.
/// </summary>
internal sealed class SortRule
{
public const int MaxClasses = 32, MaxNames = 16, MaxNameLength = 64;
private static int _nextUid;
/// <summary>Stable for the session (never saved): the window's widget ids, so a rule keeps its row while the list resorts.</summary>
public readonly int Uid = Interlocked.Increment(ref _nextUid);
public bool On = true;
public RuleKind Kind = RuleKind.Class;
/// <summary>An ObjectClass number (<see cref="ObjectClasses"/>).</summary>
public int Class = ObjectClasses.SpellComponent;
public string Text = string.Empty;
/// <summary>ObjectClass numbers (<see cref="ObjectClasses"/>), each once.</summary>
public readonly List<int> Classes = new();
/// <summary>Parts of item names (any case), each once.</summary>
public readonly List<string> Names = new();
/// <summary>The pack's number: the fallback when <see cref="PackId"/> isn't carried (or is 0), and what the window shows.</summary>
public int Pack = 1;
/// <summary>The side pack's object id (0 = none yet: the number decides). Pack order and foci can't shift it.</summary>
public uint PackId;
/// <summary>What the pack was when it was picked ("Sack - Salvage, Gems"), for the warning when it's gone.</summary>
public string PackNote = string.Empty;
public SortRule Clone() => new() { On = On, Kind = Kind, Class = Class, Text = Text, Pack = Pack };
/// <summary>No class and no name: it matches nothing (a rule just added, before anything is put in it).</summary>
public bool IsEmpty => Classes.Count == 0 && Names.Count == 0;
public static SortRule ForClass(int cls, int pack) => new() { Kind = RuleKind.Class, Class = cls, Pack = pack };
public static SortRule ForName(string text, int pack) => new() { Kind = RuleKind.Name, Text = text, Pack = pack };
public bool HasClass(int cls) => Classes.Contains(cls);
public bool HasName(string text) => IndexOfName(text) >= 0;
private int IndexOfName(string text)
{
for (int i = 0; i < Names.Count; i++)
if (string.Equals(Names[i], text, StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
/// <summary>Adds a class (false when it's there already or the rule is full).</summary>
public bool AddClass(int cls)
{
if (cls < 0 || Classes.Contains(cls) || Classes.Count >= MaxClasses) return false;
Classes.Add(cls);
return true;
}
public bool RemoveClass(int cls) => Classes.Remove(cls);
/// <summary>Adds a name part, trimmed and cut to <see cref="MaxNameLength"/> (false when blank, there already, or the rule is full).</summary>
public bool AddName(string? text)
{
string t = Clean(text);
if (t.Length == 0 || IndexOfName(t) >= 0 || Names.Count >= MaxNames) return false;
Names.Add(t);
return true;
}
public bool RemoveName(string text)
{
int i = IndexOfName(text);
if (i < 0) return false;
Names.RemoveAt(i);
return true;
}
public static string Clean(string? text)
{
string t = (text ?? string.Empty).Trim();
return t.Length > MaxNameLength ? t[..MaxNameLength].TrimEnd() : t;
}
/// <summary>Everything of <paramref name="other"/>'s classes and names this rule doesn't have yet.</summary>
public void TakeEntriesOf(SortRule other)
{
foreach (int c in other.Classes) AddClass(c);
foreach (string n in other.Names) AddName(n);
}
public SortRule Clone()
{
var r = new SortRule { On = On, Pack = Pack, PackId = PackId, PackNote = PackNote };
r.Classes.AddRange(Classes);
r.Names.AddRange(Names);
return r;
}
/// <summary>The same classes and names (in any order, names any case) and the same pack number: what an untouched imported rule looks like.</summary>
public bool SameAs(SortRule o)
{
if (Pack != o.Pack || Classes.Count != o.Classes.Count || Names.Count != o.Names.Count) return false;
foreach (int c in Classes) if (!o.Classes.Contains(c)) return false;
foreach (string n in Names) if (!o.HasName(n)) return false;
return true;
}
public static SortRule ForClass(int cls, int pack)
{
var r = new SortRule { Pack = pack };
r.AddClass(cls);
return r;
}
public static SortRule ForName(string text, int pack)
{
var r = new SortRule { Pack = pack };
r.AddName(text);
return r;
}
/// <summary>A rule with several classes (and names): "Gem, Mana Stone, Key -> pack 3".</summary>
public static SortRule For(int pack, int[] classes, params string[] names)
{
var r = new SortRule { Pack = pack };
foreach (int c in classes) r.AddClass(c);
foreach (string n in names) r.AddName(n);
return r;
}
}
/// <summary>
@ -90,39 +187,130 @@ internal static class ObjectClasses
public static string Label(int cls) =>
cls >= 0 && cls < Names.Length ? Spaced(Names[cls]) : "class " + cls;
/// <summary>A class as a pack's contents read: "Components", "Gems", "Salvage".</summary>
public static string Plural(int cls) => cls switch
{
SpellComponent => "Components",
Salvage => "Salvage",
Gem => "Gems",
ManaStone => "Mana Stones",
Key => "Keys",
HealingKit => "Healing Kits",
Lockpick => "Lockpicks",
Food => "Food",
Scroll => "Scrolls",
TradeNote => "Trade Notes",
Money => "Money",
Plant => "Plants",
Jewelry => "Jewelry",
Armor => "Armor",
Clothing => "Clothing",
MeleeWeapon => "Melee Weapons",
MissileWeapon => "Missile Weapons",
WandStaffOrb => "Casters",
Book => "Books",
Journal => "Journals",
Ust => "Ust",
_ => Label(cls),
};
}
internal static class SortRules
{
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together.</summary>
/// <summary>The Lua script's defaults: components, salvage, then gems, stones and keys together (one rule).</summary>
public static List<SortRule> Defaults() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1),
SortRule.ForClass(ObjectClasses.Salvage, 2),
SortRule.ForClass(ObjectClasses.Gem, 3),
SortRule.ForClass(ObjectClasses.ManaStone, 3),
SortRule.ForClass(ObjectClasses.Key, 3),
SortRule.For(3, new[] { ObjectClasses.Gem, ObjectClasses.ManaStone, ObjectClasses.Key }),
};
public static bool Matches(SortRule r, SortItem item)
/// <summary>The item's name contains one of the rule's names (any case).</summary>
public static bool MatchesName(SortRule r, SortItem item)
{
if (!r.On) return false;
if (r.Kind == RuleKind.Name)
{
string t = r.Text ?? string.Empty;
return t.Length > 0 && (item.Name ?? string.Empty).Contains(t, StringComparison.OrdinalIgnoreCase);
}
return item.ObjectClass == r.Class;
string name = item.Name ?? string.Empty;
if (name.Length == 0) return false;
foreach (string t in r.Names)
if (t.Length > 0 && name.Contains(t, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>The first rule that matches (rules are tried in order), or null.</summary>
public static bool MatchesClass(SortRule r, SortItem item) => r.Classes.Contains(item.ObjectClass);
public static bool Matches(SortRule r, SortItem item) => r.On && (MatchesName(r, item) || MatchesClass(r, item));
/// <summary>
/// The rule an item follows, or null. A name match beats a class match (it is the more
/// specific: "Armor -> 4" and "name has Shield -> 5" send shields to 5, whatever the order);
/// between two rules that match the same way, the one saved first wins (the window warns
/// when two rules name the same class or name).
/// </summary>
public static SortRule? RuleFor(IReadOnlyList<SortRule> rules, SortItem item)
{
for (int i = 0; i < rules.Count; i++)
if (Matches(rules[i], item)) return rules[i];
if (rules[i].On && MatchesName(rules[i], item)) return rules[i];
for (int i = 0; i < rules.Count; i++)
if (rules[i].On && MatchesClass(rules[i], item)) return rules[i];
return null;
}
public static string Describe(SortRule r) =>
r.Kind == RuleKind.Name ? $"name has \"{r.Text}\"" : ObjectClasses.Label(r.Class);
/// <summary>"Gem, Key, Mana Stone, name has "Opal"": the classes (A-Z), then the names (A-Z).</summary>
public static string Describe(SortRule r)
{
if (r.IsEmpty) return "(empty: add a class or a name)";
var parts = new List<string>(r.Classes.Count + r.Names.Count);
foreach (string l in ClassLabels(r)) parts.Add(l);
foreach (string n in SortedNames(r)) parts.Add($"name has \"{n}\"");
return string.Join(", ", parts);
}
/// <summary>The rule's classes as labels, A-Z.</summary>
public static List<string> ClassLabels(SortRule r)
{
var labels = r.Classes.ConvertAll(ObjectClasses.Label);
labels.Sort(StringComparer.OrdinalIgnoreCase);
return labels;
}
/// <summary>The rule's classes ordered by label, A-Z.</summary>
public static List<int> SortedClasses(SortRule r)
{
var list = new List<int>(r.Classes);
list.Sort((a, b) => string.Compare(ObjectClasses.Label(a), ObjectClasses.Label(b), StringComparison.OrdinalIgnoreCase));
return list;
}
public static List<string> SortedNames(SortRule r)
{
var list = new List<string>(r.Names);
list.Sort(StringComparer.OrdinalIgnoreCase);
return list;
}
/// <summary>The order rules are listed in under their pack: by <see cref="Describe"/>, A-Z (empty rules last).</summary>
public static int CompareForList(SortRule a, SortRule b)
{
if (a.IsEmpty != b.IsEmpty) return a.IsEmpty ? 1 : -1;
int c = string.Compare(Describe(a), Describe(b), StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Uid.CompareTo(b.Uid);
}
/// <summary>
/// The side pack the rule sends items to: 1-based index into <paramref name="inv"/>'s packs, or 0
/// when it has none. The pack <see cref="SortRule.PackId"/> names when that is carried; else
/// pack number <see cref="SortRule.Pack"/> when there is one (<paramref name="fellBack"/>: its id was set but isn't carried).
/// </summary>
public static int Resolve(SortRule r, SortInventory inv, out bool fellBack)
{
fellBack = false;
int byId = inv.IndexOf(r.PackId);
if (byId > 0) return byId;
if (r.Pack >= 1 && r.Pack <= inv.Packs.Count)
{
fellBack = r.PackId != 0;
return r.Pack;
}
return 0;
}
}

View file

@ -30,6 +30,8 @@ internal static class UiFormat
public const byte OpSameLine = 0x11;
public const byte OpSpacing = 0x13;
public const byte OpDummy = 0x14;
public const byte OpIndent = 0x15;
public const byte OpUnindent = 0x16;
public const byte OpButton = 0x20;
public const byte OpCheckbox = 0x21;
public const byte OpSliderInt = 0x22;
@ -49,6 +51,9 @@ internal static class UiFormat
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)
@ -75,6 +80,8 @@ internal static class UiFormat
// InputText flags
public const uint InputAutoSelectAll = 4096;
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
public const uint InputEnterReturnsTrue = 32;
// CollapsingHeader flags
public const uint TreeDefaultOpen = 32;

View file

@ -42,6 +42,9 @@ internal sealed class UiWindow
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
@ -80,7 +83,8 @@ internal sealed class UiWindow
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0);
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
@ -208,6 +212,23 @@ internal sealed class UiWindow
EndOp(p);
}
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
public void Indent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpIndent);
F32(w);
EndOp(p);
}
public void Unindent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpUnindent);
F32(w);
EndOp(p);
}
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
{
if (!Room()) return;
@ -265,7 +286,11 @@ internal sealed class UiWindow
}
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0)
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
{
if (!Room()) return;
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
@ -277,7 +302,7 @@ internal sealed class UiWindow
U16((ushort)maxLen);
U32(flags);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text); };
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
}
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)

View file

@ -7,17 +7,23 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort.Views;
/// <summary>
/// The RynthSort window: the auto-sort box and status, the job buttons, warnings, the rule list
/// (first match wins: enable, select to edit, add, move up or down, remove) and the settings.
/// Recorded on the pump thread, replayed by the engine.
/// The RynthSort window: the auto-sort box and status, the job buttons, then one collapsing
/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding that
/// pack's warnings and its rules (A-Z), a section for rules whose pack isn't carried, and the
/// settings. A rule is one row (on/off box, its classes and names); selecting it opens its
/// editor beneath: the classes and names as chips (click one to take it out), a class picker and
/// a name box to add, the pack it sends to, and Remove. Recorded on the pump thread, replayed by
/// the engine.
/// </summary>
internal sealed class SortPanel
{
private static readonly string[] Kinds = { "Class", "Name has" };
private const float RowIndent = 6f, EditorIndent = 22f;
private const int ChipsPerLine = 3;
private readonly SortController _c;
private readonly Action _save;
private int _selected = -1;
private SortRule? _selected;
private string _nameDraft = string.Empty;
/// <summary>Extra warnings the plugin knows about (the Lua script set to start too).</summary>
public Func<IReadOnlyList<string>> Warnings = () => Array.Empty<string>();
@ -30,7 +36,8 @@ internal sealed class SortPanel
_save = save;
}
public int Selected => _selected;
/// <summary>The rule whose editor is open, or null.</summary>
public SortRule? Selected => _selected;
public void Draw(UiWindow w)
{
@ -41,47 +48,58 @@ internal sealed class SortPanel
}
SortSettings s = _c.Data.Settings;
List<SortRule> rules = _c.Data.Rules;
if (_selected != null && !rules.Contains(_selected)) _selected = null;
SortView view = _c.Planner.View;
w.Checkbox("Auto-sort", "auto", s.Auto, v => _c.SetAuto(v));
w.Tooltip("New items in the main pack go to their pack after the settle time");
w.Tooltip("Keeps every pack tidy: new items go to their pack after the settle time, items in the wrong pack move to theirs, "
+ "stacks of one kind are joined and items are put in order (A-Z) inside each pack");
w.SameLine();
w.TextColored(_c.Paused ? UiColors.Amber : UiColors.Grey, _c.Status);
if (_c.Planner.View.Waiting > 0)
if (view.Waiting > 0)
{
w.SameLine();
w.TextDisabled($"({_c.Planner.View.Waiting} waiting)");
w.TextDisabled($"({view.Waiting} waiting)");
}
w.Button("Sort main pack", "job.main", () => _c.StartJob(SortScope.Main));
w.Tooltip("Sort the main pack now, without waiting for items to settle");
w.Button("Sort now", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Sort every pack now, without waiting for new items to settle");
w.SameLine();
w.Button("Tidy all packs", "job.all", () => _c.StartJob(SortScope.All));
w.Tooltip("Also move items that are in the wrong side pack");
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Sort now, and side-pack items no rule wants go back to the main pack");
w.SameLine();
w.Button("Empty side packs", "job.unpack", () => _c.StartUnpack(null));
w.Tooltip("Move everything from your side packs into the main pack. Turns auto-sort off first, so nothing moves back.");
w.Button("Clean packs", "job.clean", () => _c.StartJob(SortScope.Clean));
w.Tooltip("Side-pack items no rule wants go to the main pack; items in the wrong side pack go to theirs");
SortView view = _c.Planner.View;
w.TextDisabled($"Main pack ({view.Main.Used}/{view.Main.Capacity}){OrderNote(view, view.Main, " - ")}");
w.Tooltip("Items no rule names stay in the main pack");
if (view.MainFull) w.TextColored(UiColors.Amber, "The main pack is full");
foreach (int p in view.Full) w.TextColored(UiColors.Amber, $"Pack {p} is full");
foreach (int p in view.Missing) w.TextColored(UiColors.Amber, $"A rule uses pack {p}, which you don't have");
if (s.Auto && _c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off");
foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning);
if (w.CollapsingHeader("Rules (first match wins)", "rules", defaultOpen: true))
DrawRules(w, rules, view);
Dictionary<int, List<SortRule>> byPack = Group(rules, view);
Dictionary<int, List<string>> conflicts = Conflicts(rules, view);
for (int i = 1; i <= view.Packs.Count; i++)
DrawPack(w, view, rules, i, byPack.TryGetValue(i, out List<SortRule>? list) ? list : new List<SortRule>(),
conflicts.TryGetValue(i, out List<string>? c) ? c : null);
if (byPack.TryGetValue(0, out List<SortRule>? missing)) DrawMissing(w, view, rules, missing);
if (view.Packs.Count == 0) w.TextDisabled("No side packs: items stay in the main pack.");
if (w.CollapsingHeader("Settings", "settings"))
{
w.SliderInt("Settle (s)", "settle", s.SettleSec, SortSettings.SettleMin, SortSettings.SettleMax, v => { s.SettleSec = v; _save(); });
w.Tooltip("How long a new item sits in the main pack before it is moved");
w.SliderInt("Gap (ms)", "gap", s.GapMs, SortSettings.GapMin, SortSettings.GapMax, v => { s.GapMs = v; _save(); });
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort, Tidy, Clean and Unpack don't wait.");
w.Tooltip("Auto-sort's pause between two moves, to leave the bot room. Sort now, Clean and Empty don't wait.");
w.Checkbox("Sort during fights", "combat", s.SortInCombat, v => { s.SortInCombat = v; _save(); });
w.Tooltip("Off: nothing moves while RynthAi fights. On: moves go between its attacks and casts (never while one is unanswered)");
w.Checkbox("Put items in order inside packs", "order", s.OrderInPacks, v => { s.OrderInPacks = v; _save(); });
w.Tooltip("Like items side by side, A-Z by name, in every pack. Off: items only go to their packs (and stacks are still joined).");
w.Checkbox("Group by kind first", "orderkind", s.OrderKindFirst, v => { s.OrderKindFirst = v; _save(); });
w.Tooltip("Order by kind (Armor, Gem, Spell Component ...) and then A-Z by name, instead of A-Z by name only");
if (!(_c.Abilities.ReadOrder && _c.Abilities.PlaceMoves))
w.TextWrapped("This RynthCore can't read the order inside packs (it needs plugin API 80): items go to their packs but aren't put in order.");
}
if (_c.Log.Count > 0)
@ -91,105 +109,319 @@ internal sealed class SortPanel
}
}
private void DrawRules(UiWindow w, List<SortRule> rules, SortView view)
// ── Pack sections ───────────────────────────────────────────────────────
private void DrawPack(UiWindow w, SortView view, List<SortRule> rules, int number, List<SortRule> packRules, List<string>? conflicts)
{
if (_selected >= rules.Count) _selected = rules.Count - 1;
for (int i = 0; i < rules.Count; i++)
PackLine p = view.Packs[number - 1];
bool full = view.Full.Contains(number);
List<string> warnings = FallbackWarnings(view, number);
if (conflicts != null) warnings.AddRange(conflicts);
bool attention = full || warnings.Count > 0;
if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true);
if (attention) w.PopStyleColor();
w.Tooltip(PackTooltip(view));
if (!open) return;
w.Indent(RowIndent);
if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are");
foreach (string line in warnings) w.TextColored(UiColors.Amber, line);
packRules.Sort(SortRules.CompareForList);
foreach (SortRule r in packRules) DrawRule(w, view, rules, r);
if (packRules.Count == 0) w.TextDisabled("No rules send items here.");
uint id = p.Id;
w.SmallButton("+ Add rule", $"add.{id:X8}", () => AddRule(rules, view, number));
w.Tooltip("A rule sends items to this pack: items of any of its classes, or with any of its names in their name. A name beats a class.");
int on = 0;
foreach (SortRule r in packRules) if (r.On && !r.IsEmpty) on++;
if (on >= 2)
{
SortRule r = rules[i];
int index = i;
w.Checkbox("", "on." + i, r.On, v => { r.On = v; _save(); });
w.Tooltip("Rule on or off");
w.SameLine();
string pack = r.Pack >= 1 && r.Pack <= view.Packs.Count ? $"pack {r.Pack} ({view.Packs[r.Pack - 1].Name})" : $"pack {r.Pack}";
w.Selectable($"{i + 1}. {SortRules.Describe(r)} -> {pack}", "row." + i, _selected == i,
() => _selected = _selected == index ? -1 : index);
w.SmallButton("Merge rules", $"merge.{id:X8}", () => MergeRules(rules, packRules));
w.Tooltip("Make this pack's rules (the ones that are on) one rule with all their classes and names");
}
if (rules.Count == 0) w.TextDisabled("No rules: nothing moves.");
string order = OrderNote(view, p, "");
if (order.Length > 0) w.TextDisabled(order);
w.Unindent(RowIndent);
}
w.Button("Add rule", "rule.add", () =>
private void DrawMissing(UiWindow w, SortView view, List<SortRule> rules, List<SortRule> missing)
{
w.PushStyleColor(UiFormat.ColText, UiColors.Amber);
bool open = w.CollapsingHeader($"Rules for packs you don't have ({missing.Count})", "missing", defaultOpen: true);
w.PopStyleColor();
if (!open) return;
w.Indent(RowIndent);
w.TextWrapped("Their items stay where they are. Pick one of your packs in a rule's editor, or remove the rule.");
var groups = new List<List<SortRule>>();
foreach (SortRule r in missing)
{
if (rules.Count >= SortStore.MaxRules) return;
rules.Add(SortRule.ForClass(ObjectClasses.SpellComponent, 1));
_selected = rules.Count - 1;
_save();
});
if (_selected < 0 || _selected >= rules.Count) return;
List<SortRule>? g = groups.Find(x => SamePackOf(x[0], r));
if (g == null) groups.Add(g = new List<SortRule>());
g.Add(r);
}
foreach (List<SortRule> g in groups)
{
SortRule first = g[0];
w.TextColored(UiColors.Amber, first.PackNote.Length > 0 ? $"A pack you don't have (it was {first.PackNote}):" : $"Pack {first.Pack}, which you don't have:");
g.Sort(SortRules.CompareForList);
foreach (SortRule r in g) DrawRule(w, view, rules, r);
}
w.Unindent(RowIndent);
}
int sel = _selected;
w.SameLine();
w.Button("Up", "rule.up", () =>
{
if (sel <= 0) return;
(rules[sel - 1], rules[sel]) = (rules[sel], rules[sel - 1]);
_selected = sel - 1;
_save();
});
w.SameLine();
w.Button("Down", "rule.down", () =>
{
if (sel >= rules.Count - 1) return;
(rules[sel + 1], rules[sel]) = (rules[sel], rules[sel + 1]);
_selected = sel + 1;
_save();
});
w.SameLine();
w.Button("Remove", "rule.remove", () =>
{
rules.RemoveAt(sel);
_selected = Math.Min(sel, rules.Count - 1);
_save();
});
private static bool SamePackOf(SortRule a, SortRule b) =>
a.PackId != 0 || b.PackId != 0 ? a.PackId == b.PackId : a.Pack == b.Pack;
SortRule rule = rules[sel];
w.SeparatorText($"Rule {sel + 1}");
w.Combo("Match", "rule.kind", rule.Kind == RuleKind.Name ? 1 : 0, Kinds, v =>
// ── Rules ───────────────────────────────────────────────────────────────
private void DrawRule(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Checkbox("", k + ".on", r.On, v => { r.On = v; _save(); });
w.Tooltip(r.On ? "Rule on: click to turn it off" : "Rule off: click to turn it on");
w.SameLine();
bool selected = ReferenceEquals(_selected, r);
w.Selectable(Shown(SortRules.Describe(r)), k + ".row", selected, () =>
{
rule.Kind = v == 1 ? RuleKind.Name : RuleKind.Class;
_selected = ReferenceEquals(_selected, r) ? null : r;
_nameDraft = string.Empty;
});
w.Tooltip(selected ? "Click to close the editor" : "Click to change this rule");
if (selected) DrawEditor(w, view, rules, r);
}
private void DrawEditor(UiWindow w, SortView view, List<SortRule> rules, SortRule r)
{
string k = "r" + r.Uid;
w.Indent(EditorIndent);
List<int> classes = SortRules.SortedClasses(r);
if (classes.Count > 0)
{
w.TextDisabled("Classes:");
for (int i = 0; i < classes.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
int cls = classes[i];
string label = ObjectClasses.Label(cls);
w.SmallButton(label + " x", $"{k}.c{cls}", () => { r.RemoveClass(cls); _save(); });
w.Tooltip($"Take {label} out of this rule");
}
}
var offered = new List<int>();
var labels = new List<string> { "Add a class..." };
foreach (int cls in ObjectClasses.Choices)
{
if (r.HasClass(cls)) continue;
offered.Add(cls);
labels.Add(ObjectClasses.Label(cls));
}
if (offered.Count > 0 && r.Classes.Count < SortRule.MaxClasses)
w.Combo("Class", k + ".addclass", 0, labels, v =>
{
if (v >= 1 && v <= offered.Count && r.AddClass(offered[v - 1])) _save();
});
List<string> names = SortRules.SortedNames(r);
if (names.Count > 0)
{
w.TextDisabled("Names:");
for (int i = 0; i < names.Count; i++)
{
if (i % ChipsPerLine != 0 || i == 0) w.SameLine();
string name = names[i];
w.SmallButton($"\"{Shown(name)}\" x", $"{k}.n{i}", () => { r.RemoveName(name); _save(); });
w.Tooltip($"Take \"{name}\" out of this rule");
}
}
if (r.Names.Count < SortRule.MaxNames)
{
w.InputText("Name has", k + ".draft", _nameDraft, SortRule.MaxNameLength, (text, enter) =>
{
_nameDraft = text;
if (enter) AddDraft(r);
}, UiFormat.InputEnterReturnsTrue);
w.Tooltip("Part of an item's name, any case: \"Opal\" takes every item with Opal in its name. Enter or Add puts it in the rule.");
w.SameLine();
w.SmallButton("Add", k + ".addname", () => AddDraft(r));
}
int shown = ShownPack(view, r);
w.Combo("Pack", k + ".pack", Math.Max((shown > 0 ? shown : r.Pack) - 1, 0), PackChoices(view, r.Pack), v =>
{
SetPack(r, view, v + 1);
_save();
});
if (rule.Kind == RuleKind.Name)
w.Tooltip("Where this rule sends items. " + PackTooltip(view));
w.SmallButton("Remove rule", k + ".remove", () =>
{
w.InputText("Name has", "rule.text", rule.Text, 64, v => { rule.Text = v; _save(); });
w.Tooltip("Part of the item's name, any case");
rules.Remove(r);
if (ReferenceEquals(_selected, r)) _selected = null;
_save();
});
w.Unindent(EditorIndent);
}
private void AddDraft(SortRule r)
{
if (r.AddName(_nameDraft)) _save();
_nameDraft = string.Empty;
}
private void AddRule(List<SortRule> rules, SortView view, int number)
{
if (rules.Count >= SortStore.MaxRules) return;
var added = new SortRule();
SetPack(added, view, number);
rules.Add(added);
_selected = added;
_nameDraft = string.Empty;
_save();
}
/// <summary>The pack's rules that are on become one (the first A-Z keeps its place in the list, so a tie still goes its way).</summary>
private void MergeRules(List<SortRule> rules, List<SortRule> packRules)
{
SortRule? keep = null;
foreach (SortRule r in rules)
{
if (!packRules.Contains(r) || !r.On || r.IsEmpty) continue;
if (keep == null) { keep = r; continue; }
keep.TakeEntriesOf(r);
}
if (keep == null) return;
rules.RemoveAll(r => !ReferenceEquals(r, keep) && packRules.Contains(r) && r.On && !r.IsEmpty);
_selected = keep;
_save();
}
/// <summary>Text as a label shows it: "##" would start ImGui's id part.</summary>
private static string Shown(string text) => text.Replace("##", "# #");
// ── Helpers (pure, for the tests) ───────────────────────────────────────
/// <summary>The pack tooltip: how packs are numbered and that a rule keeps its pack.</summary>
internal static string PackTooltip(SortView view) => view.PackOrderKnown ? PackTooltipTopDown : PackTooltipListOrder;
internal const string PackTooltipTopDown =
"Packs are numbered from the top of the pack column (foci don't count). "
+ "A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go.";
internal const string PackTooltipListOrder =
"A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go. "
+ "Pack numbers count your side packs (not foci) in the client's list order, oldest pack first, "
+ "which can differ from the pack column on screen: go by the name and what's in it.";
/// <summary>" - in order", " - 3 to put in order", " - order not known": a pack's order as the window says it (empty when ordering is off).</summary>
internal static string OrderNote(SortView view, PackLine p, string lead)
{
if (!view.Ordering) return string.Empty;
if (!p.OrderKnown) return lead + "order not known yet: not put in order";
if (p.OutOfPlace == 0) return lead + "in order";
return lead + (p.OutOfPlace == 1 ? "1 item to put in order" : $"{p.OutOfPlace} items to put in order");
}
/// <summary>Rules by the side pack they send to now (1-based; 0 = a pack that isn't carried).</summary>
internal static Dictionary<int, List<SortRule>> Group(IReadOnlyList<SortRule> rules, SortView view)
{
var map = new Dictionary<int, List<SortRule>>();
foreach (SortRule r in rules)
{
int n = ShownPack(view, r);
if (!map.TryGetValue(n, out List<SortRule>? list)) map[n] = list = new List<SortRule>();
list.Add(r);
}
return map;
}
/// <summary>
/// Classes and names that two rules (that are on) send to different packs, by the pack whose
/// rule loses: "Armor: also in a rule for pack 2, which wins". A name beats a class, so only
/// rules that match the same way compete; between those the rule saved first wins.
/// </summary>
internal static Dictionary<int, List<string>> Conflicts(IReadOnlyList<SortRule> rules, SortView view)
{
var map = new Dictionary<int, List<string>>();
void Add(int pack, string line)
{
if (!map.TryGetValue(pack, out List<string>? l)) map[pack] = l = new List<string>();
if (!l.Contains(line)) l.Add(line);
}
string Where(int pack) => pack > 0 ? "pack " + pack : "a pack you don't have";
var classWinner = new Dictionary<int, int>();
var nameWinner = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (SortRule r in rules)
{
if (!r.On) continue;
int pack = ShownPack(view, r);
foreach (int cls in r.Classes)
{
if (!classWinner.TryGetValue(cls, out int won)) classWinner[cls] = pack;
else if (won != pack) Add(pack, $"{ObjectClasses.Label(cls)}: also in a rule for {Where(won)}, which wins");
}
foreach (string n in r.Names)
{
if (!nameWinner.TryGetValue(n, out int won)) nameWinner[n] = pack;
else if (won != pack) Add(pack, $"\"{n}\": also in a rule for {Where(won)}, which wins");
}
}
return map;
}
/// <summary>
/// For side pack <paramref name="number"/>: rules that use it only because their own pack isn't
/// carried (their number names it): "Gem, Key: its pack (Sack - Gems) isn't carried, so this one is used".
/// </summary>
internal static List<string> FallbackWarnings(SortView view, int number)
{
var lines = new List<string>();
foreach (RulePackIssue issue in view.Issues)
{
if (issue.UsedPack != number) continue;
string note = issue.Rule.PackNote;
lines.Add($"{SortRules.Describe(issue.Rule)}: {(note.Length > 0 ? "its pack (" + note + ")" : "its pack")} isn't carried, so this one is used");
}
return lines;
}
/// <summary>Points <paramref name="rule"/> at side pack <paramref name="number"/> (1-based): that pack's id when it is carried.</summary>
internal static void SetPack(SortRule rule, SortView view, int number)
{
rule.Pack = Math.Clamp(number, 1, SortStore.MaxPack);
if (rule.Pack <= view.Packs.Count)
{
PackLine p = view.Packs[rule.Pack - 1];
rule.PackId = p.Id;
rule.PackNote = p.Note;
}
else
{
int ci = ObjectClasses.ChoiceIndex(rule.Class);
var labels = new List<string>(ObjectClasses.ChoiceLabels);
if (ci < 0)
{
// A class the editor doesn't offer (set by hand or by the Lua script): keep it selectable.
labels.Add(ObjectClasses.Label(rule.Class));
ci = labels.Count - 1;
}
int keep = rule.Class;
w.Combo("Class", "rule.class", ci, labels, v =>
{
rule.Class = v < ObjectClasses.Choices.Length ? ObjectClasses.Choices[v] : keep;
_save();
});
rule.PackId = 0;
rule.PackNote = string.Empty;
}
w.Combo("Pack", "rule.pack", Math.Max(rule.Pack - 1, 0), PackChoices(view, rule.Pack), v =>
{
rule.Pack = Math.Clamp(v + 1, 1, SortStore.MaxPack);
_save();
});
w.Tooltip("Pack numbers are your side packs in order, top to bottom");
}
/// <summary>"Pack 1: Name (used/cap)" for each side pack, then "(none)" up to at least 7.</summary>
/// <summary>The side pack the rule uses now (1-based), as the planner resolves it, or 0.</summary>
internal static int ShownPack(SortView view, SortRule r)
{
if (r.PackId != 0)
for (int i = 0; i < view.Packs.Count; i++)
if (view.Packs[i].Id == r.PackId) return i + 1;
return r.Pack >= 1 && r.Pack <= view.Packs.Count ? r.Pack : 0;
}
/// <summary>"Pack 1: Sack (12/24) - Salvage, Gems" for each side pack, then "(none)" up to at least 7.</summary>
internal static List<string> PackChoices(SortView view, int atLeast)
{
int n = Math.Min(Math.Max(Math.Max(view.Packs.Count, 7), atLeast), SortStore.MaxPack);
var list = new List<string>(n);
for (int i = 1; i <= n; i++)
{
if (i <= view.Packs.Count)
{
PackLine p = view.Packs[i - 1];
list.Add($"Pack {i}: {p.Name} ({p.Used}/{p.Capacity})");
}
if (i <= view.Packs.Count) list.Add($"Pack {i}: {view.Packs[i - 1].Label}");
else list.Add($"Pack {i} (none)");
}
return list;

View file

@ -579,6 +579,10 @@ internal static class ActionPacer
/// </summary>
public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false)
{
// No cast goes out with a held stop still waiting (2026-10-12): the stop is sent first. The
// engine runs a stop queued before a cast ahead of it, and sends its own pre-cast stop a
// server answer ahead of the cast, so the stop never rides in the cast's frame.
MoveAudit.FlushPendingStops(host, "before a cast", force: true);
int seq = UseDoneSeqNow(host);
bool ok = host.CastSpell(targetId, spellId);
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);

View file

@ -51,26 +51,28 @@ internal static class MoveAudit
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
{
if (on && HeldForUse(host, who, "SetAutoRun(True)")) return false;
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on)) return false;
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on, deferAs: on ? null : PendingStop.AutoRunOff())) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); }
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); else _pendingAutoRunOff = null; }
return host.SetAutoRun(on);
}
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
{
if (HeldForAction(host, who, "StopCompletely()", isStop: true)) return false;
if (HeldForAction(host, who, "StopCompletely()", isStop: true, deferAs: PendingStop.Complete())) return false;
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); }
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); ClearPendingLocked(); } // clears everything AC has on
return host.StopCompletely();
}
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
{
if (on && HeldForUse(host, who, $"SetMotion(0x{motion:X8}, True)")) return false;
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion)) return false;
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion, on ? null : PendingStop.MotionOff(motion))) return false;
if (on) FlushPendingStops(host, "before a start");
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else _motionsOn.Remove(motion); }
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else { _motionsOn.Remove(motion); _pendingMotionOff.Remove(motion); } }
return host.SetMotion(motion, on);
}
@ -78,6 +80,7 @@ internal static class MoveAudit
{
if (HeldForUse(host, who, $"DoMovement(0x{motion:X8})")) return false;
if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false;
FlushPendingStops(host, "before a start");
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); }
return host.DoMovement(motion, speed, holdKey);
@ -89,9 +92,16 @@ internal static class MoveAudit
// or a stop cancels the walk/turn to a used object, and a cast's end waits for its gesture.
// While ActionPacer has one outstanding:
// * starting to move or turning is held (returns false, one log line per action and caller);
// * a stop goes through only when RynthAi itself has the character moving (autorun, or the
// motion it turned on); a stop with nothing of ours moving would only send a redundant
// movement packet in the middle of the action, so it is held as well;
// * a stop goes through at once when RynthAi itself turned that movement on (autorun, or the
// motion it turned on) and has not turned it off since - however long ago (2026-10-12: the
// 3 s "fresh" window used to apply to stops too, so a nav stop more than 3 s after the
// last autorun-on that got through was taken as redundant while AC's autorun was still on);
// * any other stop waits, but is never dropped (2026-10-12): it is kept as a pending stop and
// sent as soon as nothing is outstanding (FlushPendingStops, every RynthAi tick, before the
// next start, and always before the next cast - CastSpellFor). RynthAi can't see AC's own
// motion state, and a stop left out leaves AC's autorun/motion on for the cast's
// FreeHandsAndCastSpell -> MaybeStopCompletely to flush in the cast's frame: the stray
// stop burst that came before every run of casts that never landed (flight 63260);
// * the deliberate kick for a held cast (Buff/Nudge), a macro stop and typed commands pass.
// Off unless ActionPacer.Enabled (RynthAi only).
@ -115,20 +125,25 @@ internal static class MoveAudit
get { lock (Gate) return (_autoRunOn || _motionsOn.Count > 0) && NowMs() - _lastStartMs < OwnMovementFreshMs; }
}
/// <summary>True when the call must wait for an unanswered paced action (internal for the tests).</summary>
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0)
/// <summary>
/// True when the call must wait for an unanswered paced action (internal for the tests). A stop
/// that waits is kept as <paramref name="deferAs"/> and sent later (FlushPendingStops): a stop is
/// never dropped.
/// </summary>
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0, PendingStop? deferAs = null)
{
if (!ActionPacer.Enabled || IsExemptFromActionHold(who)) return false;
if (isStop)
{
bool moving;
lock (Gate) moving = (motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0))
&& NowMs() - _lastStartMs < OwnMovementFreshMs;
if (moving) return false; // a real stop always goes through
lock (Gate) moving = motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0);
if (moving) return false; // a real stop always goes through, however old the start
}
var pending = ActionPacer.Current(host);
if (pending == null) return false;
if (!ActionPacer.HoldsMovement(host, out string what)) return false;
if (isStop && deferAs != null)
lock (Gate) AddPendingLocked(deferAs, who);
bool log;
lock (Gate)
{
@ -137,13 +152,152 @@ internal static class MoveAudit
}
if (log)
{
string kind = isStop ? "redundant stop, nothing of ours is moving" : "move/turn";
try { host.Log($"[Move] {PluginName}/{who} {call} held ({kind}): the server is still answering {what}"); }
string line = isStop
? $"[Move] {PluginName}/{who} {call} waits (nothing of ours is moving; sent once the server has answered, before any cast): the server is still answering {what}"
: $"[Move] {PluginName}/{who} {call} held (move/turn): the server is still answering {what}";
try { host.Log(line); }
catch { }
}
return true;
}
// ── Pending stops (2026-10-12) ──────────────────────────────────────────────
// A stop held by HeldForAction waits here until FlushPendingStops sends it. A StopCompletely
// covers everything else; an autorun-off and each motion-off are kept once (the last caller
// wins). A stop that goes through for real clears what it covers; a start that goes through
// sends the pending stops first, so the order the bot asked for is kept.
internal enum PendingStopKind { AutoRunOff, MotionOff, StopMovement, Complete }
/// <summary>One stop waiting to be sent.</summary>
internal sealed class PendingStop
{
public PendingStopKind Kind;
public uint Motion;
public int HoldKey;
public static PendingStop AutoRunOff() => new() { Kind = PendingStopKind.AutoRunOff };
public static PendingStop MotionOff(uint motion) => new() { Kind = PendingStopKind.MotionOff, Motion = motion };
public static PendingStop StopMovement(uint motion, int holdKey) => new() { Kind = PendingStopKind.StopMovement, Motion = motion, HoldKey = holdKey };
public static PendingStop Complete() => new() { Kind = PendingStopKind.Complete };
}
private static string? _pendingComplete; // who
private static string? _pendingAutoRunOff; // who
private static readonly System.Collections.Generic.Dictionary<uint, string> _pendingMotionOff = new();
private static readonly System.Collections.Generic.Dictionary<uint, (int holdKey, string who)> _pendingStopMovement = new();
private static long _pendingSinceMs;
private static long _deferredStopsSent;
/// <summary>Held stops sent later by FlushPendingStops (status, tests).</summary>
internal static long DeferredStopsSent { get { lock (Gate) return _deferredStopsSent; } }
/// <summary>True while a held stop is waiting to be sent.</summary>
internal static bool HasPendingStop
{
get { lock (Gate) return HasPendingLocked(); }
}
private static bool HasPendingLocked() =>
_pendingComplete != null || _pendingAutoRunOff != null || _pendingMotionOff.Count > 0 || _pendingStopMovement.Count > 0;
private static void AddPendingLocked(PendingStop stop, string who)
{
if (!HasPendingLocked()) _pendingSinceMs = NowMs();
switch (stop.Kind)
{
case PendingStopKind.Complete: _pendingComplete = who; break;
case PendingStopKind.AutoRunOff: _pendingAutoRunOff = who; break;
case PendingStopKind.MotionOff: _pendingMotionOff[stop.Motion] = who; break;
case PendingStopKind.StopMovement: _pendingStopMovement[stop.Motion] = (stop.HoldKey, who); break;
}
}
private static void ClearPendingLocked()
{
_pendingComplete = null;
_pendingAutoRunOff = null;
_pendingMotionOff.Clear();
_pendingStopMovement.Clear();
}
/// <summary>
/// Sends the held stops once nothing is outstanding (or at once with <paramref name="force"/>:
/// a cast is about to go out, and no cast goes out with a stop still held). RynthAi calls it
/// every tick; the starts and CastSpellFor call it first. Returns true when something was sent.
/// </summary>
internal static bool FlushPendingStops(RynthCoreHost host, string why, bool force = false)
{
lock (Gate) { if (!HasPendingLocked()) return false; }
if (!force && ActionPacer.Current(host) != null) return false;
string? complete, autoRunOff;
System.Collections.Generic.KeyValuePair<uint, string>[] motionOff;
System.Collections.Generic.KeyValuePair<uint, (int holdKey, string who)>[] stopMovement;
long waited;
lock (Gate)
{
if (!HasPendingLocked()) return false;
complete = _pendingComplete;
autoRunOff = _pendingAutoRunOff;
motionOff = new System.Collections.Generic.KeyValuePair<uint, string>[_pendingMotionOff.Count];
((System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<uint, string>>)_pendingMotionOff).CopyTo(motionOff, 0);
stopMovement = new System.Collections.Generic.KeyValuePair<uint, (int, string)>[_pendingStopMovement.Count];
((System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<uint, (int, string)>>)_pendingStopMovement).CopyTo(stopMovement, 0);
waited = NowMs() - _pendingSinceMs;
ClearPendingLocked();
}
var sent = new System.Collections.Generic.List<string>();
try
{
if (complete != null)
{
// StopCompletely clears autorun and every motion in AC: nothing else is needed.
if (host.HasStopCompletely)
{
host.StopCompletely();
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); _deferredStopsSent++; }
sent.Add($"StopCompletely() for {complete}");
}
else
{
autoRunOff ??= complete; // no StopCompletely on this engine: at least autorun off
}
}
if (complete == null || !host.HasStopCompletely)
{
if (autoRunOff != null)
{
host.SetAutoRun(false);
lock (Gate) { _autoRunOn = false; _deferredStopsSent++; }
sent.Add($"SetAutoRun(False) for {autoRunOff}");
}
foreach (var m in motionOff)
{
if (!host.HasSetMotion) break;
host.SetMotion(m.Key, false);
lock (Gate) { _motionsOn.Remove(m.Key); _deferredStopsSent++; }
sent.Add($"SetMotion(0x{m.Key:X8}, False) for {m.Value}");
}
foreach (var s in stopMovement)
{
if (!host.HasStopMovement) break;
host.StopMovement(s.Key, s.Value.holdKey);
lock (Gate) { _motionsOn.Remove(s.Key); _deferredStopsSent++; }
sent.Add($"StopMovement(0x{s.Key:X8}) for {s.Value.who}");
}
}
}
catch { }
if (sent.Count > 0 && Enabled)
{
try { host.Log($"[Move] {PluginName} held stop(s) sent {why} after {waited} ms: {string.Join(", ", sent)}"); }
catch { }
}
return sent.Count > 0;
}
// ── Hold while a door/corpse use is in flight (2026-10-06) ─────────────────────
// A move or a turn sent while the server is still walking/turning the character to a used
// door or corpse cancels that use (ACE stops its move-to chain on a client MoveToState).
@ -175,9 +329,9 @@ internal static class MoveAudit
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
{
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion)) return false;
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion, PendingStop.StopMovement(motion, holdKey))) return false;
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
lock (Gate) _motionsOn.Remove(motion);
lock (Gate) { _motionsOn.Remove(motion); _pendingStopMovement.Remove(motion); }
return host.StopMovement(motion, holdKey);
}
@ -243,6 +397,9 @@ internal static class MoveAudit
_lastStartMs = long.MinValue / 2;
_actionHoldLogged.Clear();
_actionHoldLoggedFor = long.MinValue;
ClearPendingLocked();
_pendingSinceMs = 0;
_deferredStopsSent = 0;
}
}
}

View file

@ -41,6 +41,9 @@ internal static unsafe class FakeHost
public static readonly Dictionary<uint, uint[]> SpellIds = new();
/// <summary>Data id properties (STypeDID): (object, key) -> value, e.g. a scroll's Spell 28.</summary>
public static readonly Dictionary<(uint Id, uint Key), uint> DataIds = new();
/// <summary>Instance id properties (STypeIID): (object, key) -> object id, e.g. a pet's PetOwner 44.
/// When it has entries at Create() time the host also gets GetObjectInstanceIdProperty (opt-in).</summary>
public static readonly Dictionary<(uint Id, uint Key), uint> InstanceIds = new();
public static readonly Dictionary<uint, uint[]> Palettes = new();
public static readonly HashSet<uint> KnownSpells = new();
public static readonly HashSet<uint> NotAttackable = new();
@ -98,6 +101,13 @@ internal static unsafe class FakeHost
public static bool StopCalls;
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
public static int Stops;
/// <summary>Opt-in: wires SetMotion; calls land in <see cref="MotionCalls"/>.</summary>
public static bool SetMotionCalls;
/// <summary>Every SetMotion (motion, on), in order (opt-in with <see cref="SetMotionCalls"/>).</summary>
public static readonly List<(uint Motion, bool On)> MotionCalls = new();
/// <summary>Movement and cast calls in the order they reached the engine ("autorun on/off", "stop",
/// "motion 0x.. on/off", "cast N").</summary>
public static readonly List<string> Sent = new();
/// <summary>Every UseObject (a wield, a use) and RequestId (an identify), in order.</summary>
public static readonly List<uint> Uses = new();
public static readonly List<uint> IdRequests = new();
@ -193,16 +203,19 @@ internal static unsafe class FakeHost
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
Skills.Clear(); SkillLevels.Clear(); Attributes.Clear();
SpellIds.Clear(); DataIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
SpellIds.Clear(); DataIds.Clear(); InstanceIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
Containers.Clear(); Wielders.Clear(); Bitfields.Clear();
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear(); GiveLands = true;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
// Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on
// the PC doesn't change results; the mana reserve tests set their own costs.
RynthCore.Plugin.RynthAi.BuffManager.ManaCostOverride = _ => 0;
WieldCalls = false; Wields.Clear();
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
@ -248,6 +261,8 @@ internal static unsafe class FakeHost
api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetObjectOwnershipInfo;
if (Bitfields.Count > 0)
api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
if (InstanceIds.Count > 0)
api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetObjectInstanceIdProperty;
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
@ -256,6 +271,8 @@ internal static unsafe class FakeHost
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
if (StopCalls)
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
if (SetMotionCalls)
api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&SetMotion;
if (Nav3DCalls)
{
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
@ -530,6 +547,14 @@ internal static unsafe class FakeHost
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectInstanceIdProperty(uint id, uint key, uint* v)
{
if (!InstanceIds.TryGetValue((id, key), out uint x)) return 0;
*v = x;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectDataIdProperty(uint id, uint key, uint* v)
{
@ -613,7 +638,10 @@ internal static unsafe class FakeHost
private static uint GetSelectedItemId() => SelectedItem;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); return 1; }
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; }
// The fake character turns instantly.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
@ -626,9 +654,9 @@ internal static unsafe class FakeHost
private static int TapJump() { TapJumps++; return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int StopCompletely() { Stops++; return 1; }
private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -20,6 +20,9 @@ internal static class Program
/// <summary>DungeonHazardStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveHazardFolder { get; private set; } = "";
/// <summary>CreatureProfileStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveCreatureFolder { get; private set; } = "";
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
@ -36,6 +39,9 @@ internal static class Program
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
SpellDatabase.Load();
@ -90,6 +96,9 @@ internal static class Program
CustomDebuffTests.Register(runner);
ProfileLoadTests.Register(runner);
ActivityInterfaceTests.Register(runner);
CastNoDamageTests.Register(runner);
ManaReserveTests.Register(runner);
DamageRowsTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -47,7 +47,10 @@ internal static class ActionPacingTests
{
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing: moves and turns wait while the server answers; a stop with nothing of ours moving waits too, is never dropped; a real stop and the cast nudge go through", MovesHeld);
r.Add("pacing (stop burst, flight 63260): a held stop goes out once the server answers, before the next start", HeldStopSentAfterAnswer);
r.Add("pacing (stop burst): no cast goes out while a stop is held - the stop is sent first", CastWaitsForHeldStop);
r.Add("pacing (stop burst): a stop for our own autorun goes through however long ago it was turned on", OldAutorunStopGoesThrough);
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
r.Add("pacing: heals (a plain heal waits for a corpse use's answer, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
@ -201,14 +204,17 @@ internal static class ActionPacingTests
Check.False(host.SetAutoRunBy("Nav", true), "nav can't start running");
Check.False(host.TurnToHeadingBy("Nav", 90f), "nor turn");
Check.False(host.SetMotionBy("Combat", 0x6500000D, true), "nor start a turn motion");
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving is a redundant movement packet: held");
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: held");
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving waits for the answer");
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: waits too");
Check.True(MoveAudit.HasPendingStop, "the stops are kept, not dropped");
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
Check.Eq(FakeHost.Stops, 0, "no stop either");
Check.Eq(FakeHost.Stops, 0, "no stop yet either");
Check.True(Logged("held (move/turn): the server is still answering the use of"), "the hold is logged");
Check.True(Logged("StopCompletely() waits (nothing of ours is moving; sent once the server has answered, before any cast)"), "the wait is logged");
Check.True(host.SetAutoRunBy("Buff/Nudge", true) && host.SetAutoRunBy("Buff/Nudge", false), "the held-cast nudge is deliberate: it goes through");
Check.True(host.StopCompletelyBy("MacroStop"), "a macro stop goes through");
Check.False(MoveAudit.HasPendingStop, "the macro StopCompletely covered the held ones");
FakeHost.UseDone(0);
Check.True(host.SetAutoRunBy("Nav", true), "answered: nav runs again");
@ -218,6 +224,55 @@ internal static class ActionPacingTests
Check.False(MoveAudit.OwnMovementActive, "and we are not moving any more");
});
private static void HeldStopSentAfterAnswer() => Paced(() =>
{
World();
FakeHost.SetMotionCalls = true;
var host = FakeHost.Create(Player);
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.False(host.SetAutoRunBy("Nav", false), "nav's stop with nothing of ours moving waits");
Check.False(host.SetMotionBy("Nav", 0x6500000D, false), "and its turn-off");
Check.False(MoveAudit.FlushPendingStops(host, "test"), "nothing is sent while the use is unanswered");
Check.Eq(FakeHost.Sent.Count, 0, "nothing reached the client");
FakeHost.UseDone(0);
Check.True(MoveAudit.FlushPendingStops(host, "once the server answered"), "answered: the held stops go out (RynthAi's tick)");
Check.True(FakeHost.Sent.SequenceEqual(new[] { "autorun off", "motion 0x6500000D off" }), $"autorun off, then the turn-off ({string.Join(", ", FakeHost.Sent)})");
Check.True(Logged("held stop(s) sent once the server answered"), "logged");
Check.False(MoveAudit.HasPendingStop, "nothing left");
// A start that goes through sends any held stop first, so the order is kept.
host.UseFor(CorpseB, "Loot", "open");
FakeHost.Names[CorpseB] = "Corpse of Olthoi Swarm Drone";
host.StopCompletelyBy("Arbiter");
FakeHost.UseDone(0);
FakeHost.Sent.Clear();
Check.True(host.SetAutoRunBy("Nav", true), "nav runs again");
Check.True(FakeHost.Sent.SequenceEqual(new[] { "stop", "autorun on" }), $"the held stop, then the start ({string.Join(", ", FakeHost.Sent)})");
});
private static void CastWaitsForHeldStop() => Paced(() =>
{
var host = World();
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.False(host.StopCompletelyBy("Arbiter"), "held while the use is unanswered");
// A player command (asked) casts over the unanswered use: the stop still goes first.
host.CastSpellFor(Corpse, 5367, "Command", "spell 5367 (/ra cast)", asked: true);
Check.True(FakeHost.Sent.SequenceEqual(new[] { "stop", "cast 5367" }), $"stop, then the cast ({string.Join(", ", FakeHost.Sent)})");
Check.False(MoveAudit.HasPendingStop, "nothing held after the cast");
Check.True(Logged("held stop(s) sent before a cast"), "logged");
});
private static void OldAutorunStopGoesThrough() => Paced(() =>
{
var host = World();
Check.True(host.SetAutoRunBy("Nav", true), "nav runs");
_t += 10_000; // nav's later autorun re-sends were held, or it simply ran on: well past the 3 s "fresh" window
host.UseFor(Corpse, "Loot", "open the claimed corpse");
Check.True(host.SetAutoRunBy("Nav", false), "our autorun is still on in AC: the stop goes through at once");
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "on, then off reached the client");
Check.False(MoveAudit.HasPendingStop, "nothing held");
});
private static void TimeLimits() => Paced(() =>
{
var host = World();

View file

@ -0,0 +1,200 @@
using System;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Casts that land nothing (player log, 2026-10-11): two Rampagers side by side, every Nether Arc
// VII a "predicted kill" on cast #1 (the learned casts-to-kill was 1), so the bot swapped to the
// other one and back for 30 minutes and the no-damage judge, which every swap resets, never ran.
// A monster swapped off as a predicted kill and then fought again is alive: no more predicted
// swaps off it. And each combat cast logs what the server said in the next few seconds.
internal static class CastNoDamageTests
{
private const uint Player = 0x50000D01;
private const uint Lb = 0x5B480000;
private const uint RampagerWcid = 16916;
private const uint Wand = 0x8008AB76;
private const int NetherArc7 = 5367;
public static void Register(Runner r)
{
r.Add("no-damage casts: a monster that survives a predicted kill is not predicted again", SurvivorNotPredictedAgain);
r.Add("no-damage casts: other monsters still get predicted kills; the memory lapses after 10 min", OthersStillPredicted);
r.Add("no-damage casts: the chat after a combat cast is logged, swings at us left out, capped, 4 s", CastChatTrace);
r.Add("no-damage casts (flight 63260): 3 magic casts landing nothing -> one short real sidestep, no cast meanwhile; a hit resets; 30 s apart", ResyncSidestep);
}
private sealed class Rig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
public readonly MonsterDamageStore Store = new();
public readonly CombatManager C;
public readonly uint A = 0x80165DA5, B = 0x80165DA6, D = 0x80165DA7, E = 0x801753EC;
public DateTime Now = new(2026, 10, 11, 10, 55, 34);
public Rig()
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x018D, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x018D, 96f, 96f, 0f);
uint[] mobs = { A, B, D, E };
for (int i = 0; i < mobs.Length; i++)
{
FakeHost.Names[mobs[i]] = "Rampager";
FakeHost.Positions[mobs[i]] = (Lb | 0x018D, 96f + i, 98.7f, 0f);
FakeHost.ItemTypes[mobs[i]] = 0x10;
FakeHost.Wcids[mobs[i]] = RampagerWcid;
}
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, mobs, null);
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, Store);
C.TargetClock = () => Now;
// What the player's store had learned: one Nether Arc VII kills a Rampager.
for (int i = 0; i < 3; i++)
Store.RecordKill(Wand, RampagerWcid, "Rampager", "Nether", 7, 1, 435);
Scan(mobs);
}
public void Scan(params uint[] ids) => C.SetScannedTargetsForTests(ids.Select(id => new CombatManager.ScannedTarget
{
Id = unchecked((int)id), Distance = 2.7, Angle = 0, Bearing = double.NaN, Name = "Rampager",
}));
public void Engage(uint id) => C.EngageForTest(unchecked((int)id));
public bool Cast() => C.CastAndPredictForTest(Wand, "Nether", 7);
public void Advance(double seconds) => Now = Now.AddSeconds(seconds);
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static void ResyncSidestep()
{
var rig = new Rig();
FakeHost.SetMotionCalls = true;
var host = FakeHost.Create();
var c = new CombatManager(host, rig.S, FakeHost.MakeCache(host, Player, new[] { rig.A, rig.B }, null));
c.SetPlayerId(Player);
c.TargetClock = () => rig.Now;
MoveAudit.Reset();
c.MagicMissForTest(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.B)); // a swap to the other monster doesn't reset the count
Check.False(c.ResyncActive, "two misses: nothing yet");
c.ReportDamageOnTarget(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.A));
c.MagicMissForTest(unchecked((int)rig.A));
Check.False(c.ResyncActive, "a hit reset the count");
c.MagicMissForTest(unchecked((int)rig.A));
Check.True(c.ResyncActive, "three in a row: a re-sync is wanted");
Check.Eq(rig.LogCount("one short sidestep to re-sync"), 1, "said once");
Check.True(c.TickResyncStep(), "first tick: the step starts, no cast");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (0x6500000Fu, true) }), "sidestep right key down");
rig.Advance(0.2);
Check.True(c.TickResyncStep(), "still stepping at 200 ms");
rig.Advance(0.1);
Check.True(c.TickResyncStep(), "300 ms: key up, settling");
Check.True(FakeHost.MotionCalls.SequenceEqual(new[] { (0x6500000Fu, true), (0x6500000Fu, false) }), "key up");
rig.Advance(0.4);
Check.False(c.TickResyncStep(), "settled: casting may go on");
Check.Eq(c.ResyncSteps, 1, "one step");
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)rig.A));
Check.False(c.ResyncActive, "within 30 s: no second step");
rig.Advance(30);
for (int i = 0; i < 3; i++) c.MagicMissForTest(unchecked((int)rig.A));
Check.True(c.ResyncActive, "30 s later: another one");
c.TickResyncStep();
Check.True(FakeHost.MotionCalls[2] == (0x65000010u, true), "the other side this time");
}
private static void SurvivorNotPredictedAgain()
{
var r = new Rig();
// The ping-pong as it ran: A predicted dead and swapped off, then B.
r.Engage(r.A);
Check.True(r.Cast(), "cast #1 at A: predicted kill (learned casts-to-kill 1)");
r.C.PredictedSwapForTest();
Check.Eq(r.LogCount("Predicted kill shot 0x80165DA5"), 1, "the swap off A is logged");
r.Advance(6.3);
r.Engage(r.B);
Check.True(r.Cast(), "cast #1 at B: predicted kill");
r.C.PredictedSwapForTest();
// A is fought again 13 s later: it didn't die.
r.Advance(6.3);
r.Engage(r.A);
Check.False(r.Cast(), "A survived its predicted kill: no predicted swap off it this time");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA5 'Rampager' didn't happen"), 1, "said once, naming A");
Check.True(r.LogCount("No more predicted swaps off it") == 1, "the line says what changes");
Check.False(r.Cast(), "cast #2 at A: still no predicted swap");
Check.False(r.Cast(), "cast #3 at A: still none");
Check.Eq(r.LogCount("didn't happen"), 1, "the line is not repeated per cast");
// B the same when it comes round.
r.Engage(r.B);
Check.False(r.Cast(), "B survived too: no predicted swap off it");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA6 'Rampager' didn't happen"), 1, "said once for B");
}
private static void OthersStillPredicted()
{
var r = new Rig();
r.Engage(r.A);
r.Cast();
r.C.PredictedSwapForTest();
r.Advance(6);
r.Engage(r.A);
Check.False(r.Cast(), "A survived: not predicted");
// D was never swapped off: its cast #1 is a predicted kill as before (E is there to swap to).
r.Engage(r.D);
Check.True(r.Cast(), "a monster that never survived a prediction still gets one");
Check.Eq(r.LogCount("Predicted kill of 0x80165DA7"), 0, "nothing said about D");
// Ten minutes on, A is forgotten (a respawn can reuse the id).
r.Advance(11 * 60);
r.Engage(r.A);
Check.True(r.Cast(), "after 10 min A gets predicted kills again");
}
private static void CastChatTrace()
{
var r = new Rig();
r.C.StartCastChatTrace(NetherArc7, unchecked((int)r.A));
r.Advance(0.25);
r.C.TraceCastChat("You say, \"Zhavik Malar\"", 17);
r.C.TraceCastChat("You evaded Rampager!", 21);
r.C.TraceCastChat("Rampager grazes your lower leg for 9 points of bludgeoning damage!", 21);
r.Advance(1.0);
r.C.TraceCastChat("Rampager resists your spell", 7);
Check.Eq(r.LogCount("[CombatChat]"), 2, "the incantation and the resist are logged, the swing and the evade are not");
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatChat] +250 ms after", StringComparison.Ordinal)
&& l.Contains("at 0x80165DA5: type=17", StringComparison.Ordinal)),
"the line has the time since the send, the target and the chat type");
Check.True(FakeHost.Logs.Any(l => l.Contains("+1250 ms", StringComparison.Ordinal) && l.Contains("'Rampager resists your spell'", StringComparison.Ordinal)),
"the server's answer is quoted");
for (int i = 0; i < 20; i++) r.C.TraceCastChat($"line {i}", 0);
Check.Eq(r.LogCount("[CombatChat]"), 8, "at most 8 lines per cast");
// A new cast starts a new trace; nothing is logged once its 4 s are up.
r.C.StartCastChatTrace(NetherArc7, unchecked((int)r.B));
r.Advance(4.1);
r.C.TraceCastChat("Your spell fizzled.", 7);
Check.Eq(r.LogCount("[CombatChat]"), 8, "a line 4.1 s after the send is not logged");
r.C.TraceCastChat("You cast Corruption VII on Rampager", 7);
Check.Eq(r.LogCount("[CombatChat]"), 8, "nor any later one until the next cast");
}
}

View file

@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The Damage tab's monster rows (2026-10-11, a player's screenshot):
// * the player's own character was a row (no HP, no "weak to", 0 kills). The object cache files
// any creature whose type reads first as a Monster - other players, and the character itself
// once something looked it up through the cache - and players are attackable, so the class
// and attackable checks let them into the nearby rows and the appraisal store;
// * two "Rampager" rows, one with the kills and one without: retail has five Rampager weenies
// (10810, 10811, 16916, 21526, 22599), and each wcid was a row. Now one row per name.
internal static class DamageRowsTests
{
private const uint Player = 0x50000C01, OtherPlayer = 0x50000C02, AdminPlayer = 0x50000C03;
private const uint Pet = 0x80001003, MonsterA = 0x80001001, MonsterB = 0x80001002;
private const uint RampagerA = 10810, RampagerB = 10811, PetWcid = 48000;
private const uint ItemTypeCreature = 0x10, BfPlayer = 0x8, BfAttackable = 0x10;
private const uint Wand = 0x80000401;
private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("damage rows: no player (you, another player, an admin, a pet) is listed or recorded", NoPlayerRows);
r.Add("damage rows: player rows already saved are dropped when the stores load", StoredPlayerRowsDropped);
r.Add("damage rows: two wcids sharing a name are one row, and an edit on it applies to both", SameNameOneRow);
r.Add("damage rows: one wcid from every source and difficulty tier is one row", OneWcidOneRow);
}
// ── Fixture ──────────────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly MonsterDamageStore Store = new();
public readonly CreatureProfileStore Creatures = new();
public Bot(RynthCoreHost host, string name)
{
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
Set("_playerId", Player);
string folder = Path.Combine(Program.TempRoot, "damage-rows", name);
if (Directory.Exists(folder)) Directory.Delete(folder, true);
Directory.CreateDirectory(folder);
Store.SetCharacter(folder);
Set("_damageStore", Store);
Set("_creatureStore", Creatures);
foreach (uint id in new[] { OtherPlayer, AdminPlayer, Pet, MonsterA, MonsterB })
cache.OnCreateObject(id);
cache.Tick();
// What put the character in the table: a lookup of it through the cache files it as
// a landscape Monster (the indexer's lazy classification doesn't skip the player).
_ = cache[unchecked((int)Player)];
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public HashSet<uint> Seen => (HashSet<uint>)typeof(RynthAiPlugin).GetField("_seenMonstersThisSession", Any)!.GetValue(P)!;
/// <summary>The monster rows of the Damage tab (the Default line left out).</summary>
public List<JsonElement> Rows()
{
using var doc = JsonDocument.Parse(P.BuildMonsterDamageJson());
return doc.RootElement.EnumerateArray()
.Where(e => !(e.TryGetProperty("isDefault", out var d) && d.GetBoolean()))
.Select(e => e.Clone()).ToList();
}
}
private static void World(bool withPet = true)
{
FakeHost.Reset();
var here = (Cell: 0xA9B40001u, X: 10f, Y: 10f, Z: 0f);
FakeHost.PlayerPose = here;
void Creature(uint id, string name, uint wcid, uint bitfield, float dx)
{
FakeHost.Names[id] = name;
FakeHost.Wcids[id] = wcid;
FakeHost.ItemTypes[id] = ItemTypeCreature;
FakeHost.Bitfields[id] = bitfield;
FakeHost.Positions[id] = (here.Cell, here.X + dx, here.Y, here.Z);
}
Creature(Player, "Drakkon", PlayerWeenies.Human, BfPlayer | BfAttackable, 0f);
Creature(OtherPlayer, "Lucy McJuicy", PlayerWeenies.Human, BfPlayer | BfAttackable, 2f);
Creature(AdminPlayer, "+Buffy", PlayerWeenies.Admin, BfPlayer | BfAttackable, 3f);
Creature(MonsterA, "Rampager", RampagerA, BfAttackable, 5f);
Creature(MonsterB, "Rampager", RampagerB, BfAttackable, 6f);
if (withPet)
{
Creature(Pet, "Fire Spirit", PetWcid, BfAttackable, 1f);
FakeHost.InstanceIds[(Pet, 44)] = Player; // PetOwner
}
}
private static uint[] Wcids(JsonElement row)
=> row.TryGetProperty("wcids", out var w) ? w.EnumerateArray().Select(x => (uint)x.GetInt64()).ToArray()
: new[] { (uint)row.GetProperty("wcid").GetInt64() };
// ── Tests ────────────────────────────────────────────────────────────────
private static void NoPlayerRows()
{
World();
var host = FakeHost.Create(Player);
var bot = new Bot(host, "no-player");
// Appraise everyone: each answer carries max health, which is what records a creature.
foreach (uint id in new[] { Player, OtherPlayer, AdminPlayer, Pet, MonsterA })
bot.P.OnUpdateHealth(id, 1f, 400, 435);
var rows = bot.Rows();
string[] names = rows.Select(r => r.GetProperty("name").GetString() ?? "").ToArray();
foreach (string who in new[] { "Drakkon", "Lucy McJuicy", "+Buffy", "Fire Spirit" })
Check.False(names.Contains(who), $"'{who}' is not a Damage-tab row (rows: {string.Join(", ", names)})");
Check.False(rows.SelectMany(Wcids).Any(PlayerWeenies.IsPlayerWcid), "no row under a player weenie (1, 4)");
Check.True(names.Contains("Rampager"), "the monsters nearby are rows");
Check.False(bot.Creatures.TryGetByWcid(PlayerWeenies.Human, out _), "no player in creatures.json (wcid 1)");
Check.False(bot.Creatures.TryGetByWcid(PlayerWeenies.Admin, out _), "no admin in creatures.json (wcid 4)");
Check.False(bot.Creatures.TryGetByName("Fire Spirit", out _), "no pet in creatures.json");
Check.True(bot.Creatures.TryGetByWcid(RampagerA, out _), "the monster is recorded");
Check.False(bot.Seen.Contains(PlayerWeenies.Human) || bot.Seen.Contains(PetWcid), "nor in this session's appraised list");
// The learned store refuses a player weenie whatever records it.
bot.Store.RecordHit(Wand, PlayerWeenies.Human, "Lucy McJuicy", "Fire", 7, 120, false);
bot.Store.RecordKill(Wand, PlayerWeenies.Human, "Lucy McJuicy", "Fire", 7, 3, 400);
bot.Store.RecordTaken(PlayerWeenies.Human, "Lucy McJuicy", "Fire", 50);
bot.Store.SetManualHp(PlayerWeenies.Admin, 999);
bot.Store.NoteCast(PlayerWeenies.Human, 7, "Lucy McJuicy");
Check.False(bot.Store.Snapshot().Any(r => PlayerWeenies.IsPlayerWcid(r.Wcid)), "monster_damage.txt never records a player");
Check.Eq(bot.Store.GetManualHp(PlayerWeenies.Admin), 0.0, "nor a setting on one");
}
private static void StoredPlayerRowsDropped()
{
World(withPet: false);
var host = FakeHost.Create(Player);
// monster_damage.txt with the character's own row and a monster's.
string folder = Path.Combine(Program.TempRoot, "damage-rows", "stored");
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, "monster_damage.txt");
File.WriteAllLines(file, new[]
{
"# RynthAi per-character monster damage learning (auto-generated).",
"M|1|Drakkon|0",
"D|1|Drakkon|0|Fire|0|0|0|1|2|0|0|0|0",
"T|4|+Buffy|Fire|3|20|30",
"H|10810|Rampager|420|4",
"D|10810|Rampager|2147487513|Fire|7|120|20|3.5|4|200|4|100|16",
});
var store = new MonsterDamageStore();
store.SetCharacter(folder);
Check.Eq(string.Join(",", store.Snapshot().Select(r => r.Wcid).Distinct()), "10810", "only the monster loads");
store.SaveIfDirty();
string saved = File.ReadAllText(file);
Check.False(saved.Contains("Drakkon") || saved.Contains("+Buffy"), "the file is saved without the player rows");
Check.True(saved.Contains("Rampager"), "and with the monster");
// creatures.json (Program points CreatureProfileStore.Folder at the scratch folder).
string cfile = Path.Combine(CreatureProfileStore.Folder, "creatures.json");
Directory.CreateDirectory(CreatureProfileStore.Folder);
File.WriteAllText(cfile,
"{\"Lucy McJuicy|1\":{\"Name\":\"Lucy McJuicy\",\"Wcid\":1,\"CreatureType\":31,\"MaxHealth\":340,\"KnownSpellIds\":[]},"
+ "\"+Buffy|4\":{\"Name\":\"+Buffy\",\"Wcid\":4,\"CreatureType\":31,\"MaxHealth\":335,\"KnownSpellIds\":[]},"
+ "\"Rampager|10810\":{\"Name\":\"Rampager\",\"Wcid\":10810,\"CreatureType\":0,\"MaxHealth\":280,\"KnownSpellIds\":[]}}");
var creatures = new CreatureProfileStore();
creatures.Load();
Check.False(creatures.TryGetByWcid(1, out _) || creatures.TryGetByWcid(4, out _), "players are not loaded as creatures");
Check.True(creatures.TryGetByWcid(RampagerA, out _), "the monster is");
creatures.SaveIfDirty();
string csaved = File.ReadAllText(cfile);
Check.False(csaved.Contains("Lucy McJuicy") || csaved.Contains("+Buffy"), "creatures.json is saved without them");
Check.True(csaved.Contains("Rampager"), "and keeps the monster");
File.Delete(cfile);
// And a bot that has them in memory lists none of them.
var bot = new Bot(host, "stored-bot");
bot.Set("_damageStore", store);
Check.False(bot.Rows().Any(r => Wcids(r).Any(PlayerWeenies.IsPlayerWcid)), "no player row in the Damage tab");
}
private static void SameNameOneRow()
{
World(withPet: false);
var host = FakeHost.Create(Player);
var bot = new Bot(host, "same-name");
// Rampager 10810: four kills. Rampager 10811: appraised and standing next to it, never killed.
// Both had a manual HP of 435 (the screenshot), set one row at a time.
for (int i = 0; i < 4; i++)
{
bot.Store.RecordHit(Wand, RampagerA, "Rampager", "Fire", 7, 145, false);
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 3, 435);
}
bot.Store.SetManualHp(RampagerA, 435);
bot.Store.SetManualHp(RampagerB, 435);
bot.P.OnUpdateHealth(MonsterB, 1f, 435, 435);
var rows = bot.Rows().Where(r => r.GetProperty("name").GetString() == "Rampager").ToList();
Check.Eq(rows.Count, 1, "one Rampager row");
var row = rows[0];
Check.Eq(string.Join(",", Wcids(row)), "10810,10811", "listing both kinds");
Check.Eq((uint)row.GetProperty("wcid").GetInt64(), RampagerA, "the row is the kind with the kills");
Check.Eq(row.GetProperty("kills").GetInt32(), 4, "with its kills");
Check.Eq(row.GetProperty("hp").GetInt32(), 435, "and the HP");
Check.True(row.GetProperty("hpManual").GetBoolean(), "set by hand");
Check.True(row.GetProperty("nearby").GetBoolean(), "nearby: both stand here");
// Edits on the row reach every kind.
bot.P.SetMonsterHp(RampagerA, 500);
Check.Eq(bot.Store.GetManualHp(RampagerB), 500.0, "an HP set on the row applies to the other kind");
bot.P.SetMonsterWeapon(RampagerA, Wand);
Check.Eq(bot.Store.GetManualWeapon(RampagerB), Wand, "so does a weapon");
bot.P.SetMonsterOffhand(RampagerA, 77);
Check.Eq(bot.Store.GetManualOffhand(RampagerB), 77u, "and an offhand");
bot.P.SetMonsterPet(RampagerA, "E:Fire");
Check.Eq(bot.Store.GetManualPet(RampagerB), "E:Fire", "and a pet");
Check.Eq(bot.Store.GetManualHp(RampagerA), 500.0, "the row's own kind too");
// Two kinds both fought: the kills add up, one drawer line per weapon/spell.
bot.Store.RecordKill(Wand, RampagerB, "Rampager", "Fire", 7, 5, 435);
row = bot.Rows().Single(r => r.GetProperty("name").GetString() == "Rampager");
Check.Eq(row.GetProperty("kills").GetInt32(), 5, "kills of both kinds");
var tiers = row.GetProperty("tiers").EnumerateArray().ToList();
Check.Eq(tiers.Count, 1, "one drawer line for the shared weapon and spell");
Check.Eq(tiers[0].GetProperty("kills").GetInt32(), 5, "with both kinds' kills");
Check.Eq(tiers[0].GetProperty("casts").GetDouble(), 3.4, "casts to kill weighted by kills ((4*3+5)/5)");
// Removing the row removes every kind.
Check.True(bot.P.DeleteMonsterRow(RampagerA.ToString()), "the row is removed");
Check.False(bot.Store.Snapshot().Any(r => r.Wcid == RampagerA || r.Wcid == RampagerB), "both kinds' learned data went");
Check.False(bot.Seen.Contains(RampagerB), "and the appraised kind with it");
}
private static void OneWcidOneRow()
{
World(withPet: false);
FakeHost.Positions.Remove(MonsterB); // only Rampager 10810 here
FakeHost.Names.Remove(MonsterB);
var host = FakeHost.Create(Player);
var bot = new Bot(host, "one-wcid");
// The same Rampager from every source: learned at real Dereth and at an Aelrynth
// difficulty tier (kept per (wcid, tier)), appraised this session, standing nearby,
// and in creatures.json under a differently cased name.
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 3, 435);
bot.Store.Difficulty = 2;
bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 4, 480);
bot.Store.Difficulty = 0;
bot.Creatures.Upsert(new CreatureProfile { Name = "rampager", Wcid = RampagerA, MaxHealth = 280 });
bot.P.OnUpdateHealth(MonsterA, 1f, 435, 435);
var rows = bot.Rows();
Check.Eq(rows.Count, 1, $"one row (rows: {string.Join(", ", rows.Select(r => r.GetProperty("name").GetString() + "/" + r.GetProperty("wcid")))})");
Check.Eq((uint)rows[0].GetProperty("wcid").GetInt64(), RampagerA, "the Rampager");
Check.False(rows[0].TryGetProperty("wcids", out _), "of one kind");
Check.Eq(rows[0].GetProperty("kills").GetInt32(), 1, "real Dereth's kill (the tier's are its own)");
}
}

View file

@ -57,6 +57,21 @@ internal static class ExpressionTests
r.Add("expr: list text saved before escaping reads the same", OldListTextReadsTheSame);
r.Add("expr: # takes a regex pattern without backticks, as documented", RegexOperatorUnquoted); // was a known failure; fixed by c34b39c
r.Add("expr: vitae[] reports no penalty when it cannot read vitae", VitaeWithoutHost); // was a known failure; fixed by 33f23f7
// UtilityBelt expression reference audit (2026-10-11): each test pins a documented
// behaviour we got wrong. The doc is Expressions.html (utilitybelt.gitlab.io/docs/expressions).
r.Add("expr doc: ; runs each expression in turn", DocSemicolon);
r.Add("expr doc: && and || skip the side that can't change the answer", DocShortCircuit);
r.Add("expr doc: unquoted text keeps its spaces, backslash escapes a character", DocStrings);
r.Add("expr doc: true and false are 1 and 0", DocTrueFalse);
r.Add("expr doc: @name and &name read pvars and gvars, $ takes an expression", DocVarShorthand);
r.Add("expr doc: {index}, {key} and slices on lists, dicts and text", DocIndexAndSlice);
r.Add("expr: $x = value assigns (UB syntax real metas use)", AssignmentSyntax);
r.Add("expr doc: listadd, listpop and friends change the list in its variable", DocListsChangeInPlace);
r.Add("expr doc: a dictionary kept in a variable lives on", DocDictsPersist);
r.Add("expr doc: iif, istrue, isfalse and getobjectinternaltype", DocLogicAndTypes);
r.Add("expr doc: name, regex, state and setting arguments may be expressions", DocTextArguments);
r.Add("expr doc: getheadingto across landblocks, casts of unknown spells, getknownspells", DocLiveState);
}
// ── Helpers ───────────────────────────────────────────────────────────────
@ -205,7 +220,7 @@ internal static class ExpressionTests
Is(e, "", "");
Is(e, " ", "");
Is(e, "1 2", "1"); // text after a complete expression is ignored
Is(e, "hello world", "hello"); // so a bare two-word value keeps only the first word
Is(e, "hello world", "hello world"); // text of letters and spaces is one value (reference)
Is(e, "@", "");
Is(e, "!1", ""); // there is no logical not; use ==0 or isfalse[]
Is(e, "a.b_c9", "a.b_c9"); // identifiers keep dots and underscores
@ -262,7 +277,7 @@ internal static class ExpressionTests
Is(e, "testvar[a]+testvar[b]", "0");
Is(e, "setvar[s, `two words`]", "two words");
Is(e, "$s", "two words");
Is(e, "setvar[t, two words]", "two"); // unquoted: only the first word
Is(e, "setvar[t, two words]", "two words"); // unquoted text keeps all its words
e.SetVariable("host_set", "7");
Is(e, "$host_set", "7");
}
@ -346,15 +361,18 @@ internal static class ExpressionTests
Is(e, "listgetitem[$l,3]", "b");
Is(e, "listgetitem[$l,4]", "");
Is(e, "listgetitem[$l,-1]", "");
Is(e, "listadd[$l,d]", "[a,b,c,b,d]");
Is(e, "$l", "[a,b,c,b]"); // lists are values: listadd returns a new one
Is(e, "listinsert[$l,z,0]", "[z,a,b,c,b]");
Is(e, "listinsert[$l,z,4]", "[a,b,c,b,z]");
Is(e, "listinsert[$l,z,5]", "0");
Is(e, "listremove[$l,b]", "[a,c,b]"); // first match only
Is(e, "listremove[$l,q]", "[a,b,c,b]");
Is(e, "listremoveat[$l,1]", "[a,c,b]");
Is(e, "listremoveat[$l,9]", "0");
// listcopy[...] is not a variable, so these give a changed copy and $l stays.
Is(e, "listadd[listcopy[$l],d]", "[a,b,c,b,d]");
Is(e, "$l", "[a,b,c,b]");
Is(e, "listinsert[listcopy[$l],z,0]", "[z,a,b,c,b]");
Is(e, "listinsert[listcopy[$l],z,4]", "[a,b,c,b,z]");
Is(e, "listinsert[listcopy[$l],z,5]", "0");
Is(e, "listremove[listcopy[$l],b]", "[a,c,b]"); // first match only
Is(e, "listremove[listcopy[$l],q]", "[a,b,c,b]");
Is(e, "listremoveat[listcopy[$l],1]", "[a,c,b]");
Is(e, "listremoveat[listcopy[$l],9]", "0");
Is(e, "listinsert[$l,z,5]", "0"); // a failed change leaves $l alone
Is(e, "$l", "[a,b,c,b]");
Is(e, "listcontains[$l,C]", "1"); // ignores case
Is(e, "listcontains[$l,q]", "0");
Is(e, "listindexof[$l,b]", "1");
@ -364,11 +382,11 @@ internal static class ExpressionTests
Is(e, "listcopy[$l]", "[a,b,c,b]");
Is(e, "listcopy[x]", "[]");
Is(e, "listreverse[$l]", "[b,c,b,a]");
Is(e, "listpop[$l]", "b");
Is(e, "listpop[$l,0]", "a");
Is(e, "listpop[$l,-5]", "b"); // any negative index means the last item
Is(e, "listpop[listcopy[$l]]", "b");
Is(e, "listpop[listcopy[$l],0]", "a");
Is(e, "listpop[listcopy[$l],-5]", "b"); // any negative index means the last item
Is(e, "listpop[listcreate[]]", "");
Is(e, "listclear[$l]", "[]");
Is(e, "listclear[listcopy[$l]]", "[]");
Is(e, "listfromrange[1,3]", "[1,2,3]");
Is(e, "listfromrange[3,1]", "[3,2,1]");
Is(e, "listfromrange[2,2]", "[2]");
@ -404,10 +422,10 @@ internal static class ExpressionTests
var e = Engine();
Is(e, "dictcreate[a,1,b,2]", "D:0");
Is(e, "dictgetitem[dictcreate[a,1,b,2],b]", "2");
Is(e, "setvar[d, dictcreate[a,1]] && dictadditem[$d,a,9]", "1"); // one evaluation: the handle is live
// Dicts last for one top-level evaluation; a handle kept in a variable goes dead.
Is(e, "dictgetitem[$d,a]", "");
Is(e, "dictsize[$d]", "0");
Is(e, "setvar[d, dictcreate[a,1]] && dictadditem[$d,a,9]", "1");
// A handle kept in a variable stays live in later evaluations (reference audit).
Is(e, "dictgetitem[$d,a]", "9");
Is(e, "dictsize[$d]", "1");
Is(e, "setvar[d, dictcreate[k,v]] && dictadditem[$d,n,1]==0 && dicthaskey[$d,n] && dictsize[$d]==2", "1");
Is(e, "setvar[d, dictcreate[k,v]] && dictremovekey[$d,k] && dictremovekey[$d,k]==0 && dictsize[$d]==0", "1");
Is(e, "listcount[dictkeys[dictcreate[a,1,b,2,c,3]]]", "3");
@ -415,7 +433,7 @@ internal static class ExpressionTests
Is(e, "dicthaskey[dictcreate[Key,1],key]", "0"); // dict keys are case-sensitive
Is(e, "setvar[d, dictcreate[a,1]] && setvar[c, dictcopy[$d]] && dictadditem[$c,z,1]==0 && dicthaskey[$d,z]==0", "1");
Is(e, "dictsize[dictclear[dictcreate[a,1]]]", "0");
Is(e, "dictcreate[a]", "D:0"); // odd argument count: the last key is dropped
Check.True(e.Evaluate("dictcreate[a]").StartsWith("D:"), "odd argument count: still a dict"); // the last key is dropped
Is(e, "dictsize[dictcreate[a]]", "0");
Is(e, "dictgetitem[D:99,a]", "");
}
@ -453,7 +471,8 @@ internal static class ExpressionTests
Is(e, "atan2[0,1]", "0");
Is(e, "cos[0]", "1");
Is(e, "isfalse[0]", "1");
Is(e, "istrue[2]", "1");
Is(e, "istrue[2]", "0"); // "equal to true (1)" (reference)
Is(e, "istrue[1]", "1");
Is(e, "istrue[abc]", "0"); // text is not a true number here, though ToBool says true
Is(e, "spellname[1332]", "Strength Self VI");
Is(e, "spellname[99999999]", "Unknown Spell (99999999)");
@ -473,8 +492,8 @@ internal static class ExpressionTests
Is(e, "testvar[b]", "0"); // the other branch never ran
Is(e, "iif[0, x]", "");
Is(e, "iif[1]", "");
Is(e, "iif[abc, yes, no]", "yes"); // lazy iif uses ToBool: text is true
Is(e, "iif[0.0, yes, no]", "yes"); // "0.0" is not "0"
Is(e, "iif[abc, yes, no]", "no"); // "false or not a number" takes the third (reference)
Is(e, "iif[0.0, yes, no]", "no"); // 0.0 is the number 0
Is(e, "if[1, setvar[c,1]]", "1");
Is(e, "if[0, setvar[d,1]]", "");
Is(e, "testvar[d]", "0");
@ -544,7 +563,7 @@ internal static class ExpressionTests
Is(e, "getobjectinternaltype[stopwatchcreate[]]", "7");
Is(e, "getobjectinternaltype[dictcreate[]]", "7");
Is(e, "getobjectinternaltype[`[WorldObject] 0x50000001: Sword`]", "7");
Is(e, "getobjectinternaltype[listcreate[1,2]]", "3"); // lists are text
Is(e, "getobjectinternaltype[listcreate[1,2]]", "7"); // a list is an object (reference audit)
Is(e, "raoptget[nope]", "0");
Is(e, "raoptset[mode, hunt]", "1");
@ -748,7 +767,7 @@ internal static class ExpressionTests
Is(e, "getgameticks[]", "27435600");
Is(e, "getgameyear[]", "10");
Is(e, "getgamemonth[]", "0");
Is(e, "getgameday[]", "0");
Is(e, "getgameday[]", "1"); // days are 1-30 (reference)
Is(e, "getgamehour[]", "7");
Is(e, "getisday[]", "1");
Is(e, "getisnight[]", "0");
@ -756,6 +775,9 @@ internal static class ExpressionTests
Is(e, "getminutesuntilday[]", "0");
Is(e, "getgamemonthname[0]", "Morningthaw");
Is(e, "getgamemonthname[11]", "Wintersebb");
Is(e, "getgamemonthname[6]", "Harvestgain"); // spelled as the reference lists it
Is(e, "getmonthname[1]", "Solclaim"); // the reference example's name
Is(e, "getgamehourname[1]", "Darktide-and-Half");
Is(e, "getgamemonthname[12]", "");
Is(e, "getgamemonthname[x]", "");
Is(e, "getgamehourname[0]", "Darktide");
@ -966,6 +988,324 @@ internal static class ExpressionTests
Check.Eq(e.Evaluate("getvar[lastchat] # killed.*olthoi"), "1", "getvar[lastchat] # killed.*olthoi");
}
// ── UtilityBelt reference audit ──────────────────────────────────────────
private static void DocSemicolon()
{
var e = Engine();
// The doc's own example (with listcreate, its createlist is a typo).
Is(e, "setvar[myList,listcreate[1,2,3]]; setvar[n,4]", "4");
Is(e, "$myList", "[1,2,3]");
Is(e, "getvar[n]", "4");
// The stopwatch pattern real metas use: the second half used to be dropped.
Is(e, "setvar[T, stopwatchcreate[]];stopwatchstart[getvar[T]]", "SW:0");
Is(e, "setvar[a,1];;setvar[b,2];", "2"); // empty parts are skipped
Is(e, "testvar[a]+testvar[b]", "2");
Is(e, "1+1; 2+2", "4"); // the value is the last expression's
// Inside a template, as in the doc's listsort example.
Is(e, "listmap[listcreate[1,2], `setvar[t,$1*10];$t+1`]", "[11,21]");
Is(e, "getvar[a] # 1;setvar[c,3]", "3"); // an unquoted # pattern ends at ;
}
private static void DocShortCircuit()
{
var e = Engine();
Is(e, "0 && setvar[x,1]", "0");
Is(e, "testvar[x]", "0"); // the right side never ran
Is(e, "1 || setvar[y,1]", "1");
Is(e, "testvar[y]", "0");
Is(e, "1 && setvar[z,1]", "1");
Is(e, "testvar[z]", "1");
Is(e, "0 || setvar[w,5]", "1");
Is(e, "getvar[w]", "5");
// Real meta idiom: cond && action, with nested calls and backticks in the skipped part.
Is(e, "setvar[debug,0]; $debug>=2&&setvar[said, `[x], y`]", "0");
Is(e, "testvar[said]", "0");
Is(e, "0 && (setvar[p,1] || setvar[q,1]) || setvar[r,1]", "1");
Is(e, "testvar[p]+testvar[q]", "0");
Is(e, "getvar[r]", "1");
Is(e, "0 && 1 || 1", "1"); // results are as before
Is(e, "1 && 0", "0");
}
private static void DocStrings()
{
var e = Engine();
// The reference's examples: "123 test" escaped as \1\2\3 test, "p@cMan$)" as p\@cMan\$\).
Is(e, "setvar[a, \\1\\2\\3 test]", "123 test");
Is(e, "setvar[b, p\\@cMan\\$\\)]", "p@cMan$)");
Is(e, "setvar[c, some example string]", "some example string");
Is(e, "strlen[some example string]", "19");
// Real meta text: an escaped '!' and comma, a chat command joined with +.
Is(e, "setvar[m, Not in a fellowship\\!]", "Not in a fellowship!");
Is(e, "listcount[listcreate[a\\,b, c]]", "2"); // \, is a comma, not a separator
e.Evaluate("setvar[nav, Hunt Loop]");
Is(e, "\\/vt nav load +getvar[nav]", "/vt nav load Hunt Loop");
Is(e, "\\/t +getvar[nav]+\\, Removed as bell user\\.", "/t Hunt Loop, Removed as bell user.");
Is(e, "\\/ub jumpw 180 +cstr[750-5]", "/ub jumpw 180 745");
Is(e, "getvar[nav] == Hunt Loop && 1", "1"); // compared as the whole text
Is(e, "setvar[d, ILT Mega.met]", "ILT Mega.met");
Is(e, "1 2", "1"); // a number is one word
Is(e, "abc def[] ghi", "abc"); // a function name is not text
Is(e, "listcount[listcreate[`a]`, b]]", "2"); // a ']' inside backticks is text
Is(e, "echo[`x`, 1] ; strlen[`a\\`b`]", "3"); // \` inside backticks still works
// Inside backticks \\ is one backslash (real metas nest templates this way); any other
// \x stays, as in the reference's getregexmatch[`test 123`,`\d+`].
Is(e, "getregexmatch[`test 123`,`\\d+`]", "123");
Is(e, "getregexmatch[`test 123`,`\\\\d+`]", "123"); // `\\d+` is the regex \d+
Is(e, "exec[`setvar[cmd, \\\\/vt forcebuff]`]", "/vt forcebuff");
Is(e, "strlen[`a\\\\b`]", "3");
}
private static void DocTrueFalse()
{
var e = Engine();
Is(e, "true", "1");
Is(e, "false", "0");
Is(e, "True == 1", "1");
Is(e, "FALSE == 0", "1");
Is(e, "setvar[flag, False]", "0");
Is(e, "iif[true, yes, no]", "yes");
Is(e, "true story", "true story"); // only the word on its own
Is(e, "`true`", "true"); // and not in backticks
}
private static void DocVarShorthand()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Sunnuj";
var e = Engine(FakeHost.Create(), playerId: Player);
Is(e, "setpvar[myPersistentVariable, 5]", "5");
Is(e, "@myPersistentVariable", "5");
Is(e, "@myPersistentVariable * 2", "10");
Is(e, "@unsetPvar", "0");
Is(e, "setgvar[myGlobalVariable, hi]", "hi");
Is(e, "&myGlobalVariable", "hi");
Is(e, "&unsetGvar", "0");
Is(e, "7&3", "3"); // & between values is still bitwise
Is(e, "6 & 3", "2");
Is(e, "1 && &myGlobalVariable == hi", "1");
// "$wobjectgetname[wobjectgetplayer[]]" is getvar[wobjectgetname[wobjectgetplayer[]]].
Is(e, "setvar[Sunnuj, mine]", "mine");
Is(e, "$wobjectgetname[0x50000A01]", "mine");
Is(e, "setvar[which, Sunnuj]", "Sunnuj");
Is(e, "$getvar[which]", "mine");
Is(e, "@", ""); // a stray sigil reads nothing, as before
}
private static void DocIndexAndSlice()
{
var e = Engine();
e.Evaluate("setvar[list, listcreate[a,b,c,d]]");
Is(e, "$list{0}", "a");
Is(e, "$list{3}", "d");
Is(e, "$list{-1}", "d");
Is(e, "$list{9}", "");
Is(e, "$list{:-1}", "[a,b,c]"); // the reference's slice example
Is(e, "$list{1:3}", "[b,c]");
Is(e, "$list[1:3]", "[b,c]"); // its other spelling
Is(e, "$list{2:}", "[c,d]");
Is(e, "$list{3:1}", "[]");
Is(e, "listcount[$list{1:}]", "3");
Is(e, "test[1:]", "est"); // "Strings support slices like arrays"
Is(e, "test[:-1]", "tes");
Is(e, "`hello`{1}", "e");
Is(e, "setvar[i, 2]; $list{$i}", "c"); // the index is an expression
Is(e, "listcreate[x,y]{1}", "y");
// A dict by key, in one evaluation (keeping dicts across evaluations is a separate test).
Is(e, "setvar[d, dictcreate[a,2,params,p]]; $d{a}+$d{params}", "2p");
Is(e, "setvar[d, dictcreate[c, dictcreate[name,Bob]]]; $d{c}{name}", "Bob");
Is(e, "nosuchfn[1]", ""); // no ':' : still an unknown function
}
private static void AssignmentSyntax()
{
FakeHost.Reset();
var e = Engine(FakeHost.Create());
Is(e, "$x=5", "5");
Is(e, "$x", "5");
Is(e, "$x == 5", "1"); // == is still a comparison
Is(e, "$x = $x + 1", "6");
Is(e, "@TotalWins=@TotalWins+1", "1");
Is(e, "@TotalWins=@TotalWins+1", "2");
Is(e, "&g = hello", "hello");
Is(e, "getgvar[g]", "hello");
// Real meta: the value stops at &&, so the list is stored and then counted.
Is(e, "$found=listcreate[a,b] && listcount[$found]>0", "1");
Is(e, "$found", "[a,b]");
Is(e, "1 && $later=7", "1");
Is(e, "$later", "7");
Is(e, "0 && $never=1", "0");
Is(e, "testvar[never]", "0");
Is(e, "$a=1;$b=$a+1;$b", "2");
}
private static void DocListsChangeInPlace()
{
FakeHost.Reset();
FakeHost.Names[Player] = "List Toon";
var e = Engine(FakeHost.Create(), playerId: Player);
// The reference's overview example.
Is(e, "setvar[myList,listcreate[1,2,3]]; listadd[$myList,4]", "[1,2,3,4]");
Is(e, "$myList", "[1,2,3,4]");
// Real meta: no setvar around it.
e.Evaluate("setvar[CharList, listcreate[]]");
e.Evaluate("listadd[getvar[CharList], Drakkon]");
e.Evaluate("listadd[getvar[CharList], Lucy McJuicy]");
Is(e, "$CharList", "[Drakkon,Lucy McJuicy]");
Is(e, "listinsert[getvar[CharList], Zed, 0]", "[Zed,Drakkon,Lucy McJuicy]");
Is(e, "listremove[$CharList, Drakkon]", "[Zed,Lucy McJuicy]");
Is(e, "listremoveat[$CharList, 0]", "[Lucy McJuicy]");
Is(e, "$CharList", "[Lucy McJuicy]");
// listpop removes and returns; with no index, the last item.
e.Evaluate("setvar[q, listcreate[a,b,c]]");
Is(e, "listpop[$q]", "c");
Is(e, "listpop[getvar[q],0]", "a");
Is(e, "$q", "[b]");
Is(e, "listclear[$q]", "[]");
Is(e, "$q", "[]");
Is(e, "listpop[$q]", ""); // empty: nothing to pop
// pvars and gvars too, and setvar around it still works.
e.Evaluate("setpvar[pl, listcreate[x]]");
e.Evaluate("listadd[@pl, y]");
Is(e, "getpvar[pl]", "[x,y]");
e.Evaluate("setgvar[gl, listcreate[1]]");
e.Evaluate("listadd[getgvar[gl], 2]");
Is(e, "&gl", "[1,2]");
Is(e, "setvar[s, listadd[$myList, 5]]", "[1,2,3,4,5]");
Is(e, "$s", "[1,2,3,4,5]");
// Not a variable, or not a list: nothing is written.
Is(e, "setvar[n, 7]; listadd[$n, 1]", "0");
Is(e, "$n", "7");
Is(e, "listadd[getvar[q]+x, 1]", "0");
}
private static void DocDictsPersist()
{
var e = Engine();
Is(e, "setvar[myDict,dictcreate[]]", "D:0");
Is(e, "dictadditem[getvar[myDict],foo,1]", "0");
Is(e, "dictadditem[getvar[myDict],foo,2]", "1"); // overwrote
Is(e, "dictgetitem[getvar[myDict],foo]", "2");
Is(e, "$myDict{foo}", "2");
Is(e, "dictsize[dictcreate[a,b,c,d]]", "2"); // the reference's example
Is(e, "dicthaskey[$myDict,foo]", "1");
// A new dict never takes a stored dict's id (they used to restart at D:0 each time).
string other = e.Evaluate("dictcreate[x,1]");
Check.True(other != "D:0", $"new dict {other} is not D:0");
Is(e, "dictsize[$myDict]", "1");
Is(e, "setvar[cfg, dictcreate[inner, dictcreate[name,Bob]]]; 1", "1");
Is(e, "$cfg{inner}{name}", "Bob");
Is(e, "setvar[copy, dictcopy[$myDict]]; dictadditem[$copy,bar,1]; dictsize[$myDict]", "1");
Is(e, "dictsize[$copy]", "2");
// Unreferenced dicts are swept once there are many; referenced ones (also nested) stay.
for (int i = 0; i < 400; i++) e.Evaluate("dictcreate[t,1]");
e.Evaluate("1");
Is(e, "dictgetitem[$myDict,foo]", "2");
Is(e, "$cfg{inner}{name}", "Bob");
Is(e, "dictsize[$copy]", "2");
Check.True(e.Evaluate("dictgetitem[D:5,t]") == "", "an unreferenced dict was swept");
}
private static void DocLogicAndTypes()
{
var e = Engine();
Is(e, "iif[1,2,3]", "2"); // the reference's example
Is(e, "iif[0,2,3]", "3");
Is(e, "iif[abc,2,3]", "3"); // not a number: the third
Is(e, "iif[``,2,3]", "3");
Is(e, "iif[-1,2,3]", "2");
Is(e, "isfalse[0]", "1"); // the reference's examples
Is(e, "istrue[1]", "1");
Is(e, "isfalse[abc]", "0"); // text is not false (0)...
Is(e, "istrue[abc]", "0"); // ...nor true (1)
Is(e, "istrue[2]", "0");
Is(e, "isfalse[1]", "0");
Is(e, "istrue[3<10]", "1");
Is(e, "getobjectinternaltype[``]", "0"); // 0=none, 1=number, 3=string, 7=object
Is(e, "getobjectinternaltype[5]", "1");
Is(e, "getobjectinternaltype[test]", "3");
Is(e, "getobjectinternaltype[listcreate[]]", "7");
Is(e, "getobjectinternaltype[coordinateparse[`1.2N, 3.4E`]]", "7");
Is(e, "getobjectinternaltype[dictcreate[]]", "7");
Is(e, "getobjectinternaltype[`1|2`]", "3");
}
private static void DocTextArguments()
{
FakeHost.Reset();
const uint kit = 0x60000001, key = 0x60000002, token = 0x60000003, essence = 0x60000004;
FakeHost.Names[kit] = "Healing Kit";
FakeHost.Names[key] = "The Baron's Key";
FakeHost.Names[token] = "High-Stakes Gambling Token";
FakeHost.Names[essence] = "Wisp Essence";
FakeHost.Ints[(kit, 12)] = 5;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { kit, key, token, essence }, new Dictionary<uint, float>());
var e = Engine(host, playerId: Player, settings: new LegacyUiSettings { EnableCombat = true });
e.SetObjectCache(cache);
// Expressions are evaluated (they used to be searched for as typed).
e.Evaluate("setvar[itemname, Healing Kit]");
Is(e, "wobjectfindininventorybyname[$itemname]", "[WorldObject] 0x60000001: Healing Kit");
Is(e, "wobjectfindininventorybyname[getvar[itemname]]", "[WorldObject] 0x60000001: Healing Kit");
Is(e, "getitemcountininventorybyname[$itemname]", "5");
Is(e, "getitemcountininventorybynamerx[`^`+$itemname+`$`]", "5");
Is(e, "wobjectfindininventorybynamerx[\\(Knight\\|Wisp\\)\\.\\+Essence]", "[WorldObject] 0x60000004: Wisp Essence");
Is(e, "listcount[wobjectfindallinventorybynamerx[getvar[itemname]]]", "1");
// Plain text with punctuation is still taken as typed.
Is(e, "wobjectfindininventorybyname[The Baron's Key]", "[WorldObject] 0x60000002: The Baron's Key");
Is(e, "wobjectfindininventorybyname[High-Stakes Gambling Token]", "[WorldObject] 0x60000003: High-Stakes Gambling Token");
Is(e, "wobjectfindininventorybynamerx[(Essence)]", "[WorldObject] 0x60000004: Wisp Essence");
Is(e, "listcount[wobjectfindallinventorybynamerx[Wis[p]]]", "1"); // a regex that looks like a call
Check.False(FakeHost.Logs.Exists(l => l.Contains("unknown expression function 'wis'")), "and isn't logged as an unknown function");
Is(e, "getitemcountininventorybyname[Healing Kit]", "5");
// Meta state and setting names, and the cstrf format.
e.Evaluate("setvar[next, Turn In]");
Is(e, "vtsetmetastate[getvar[next]]", "1");
Is(e, "vtgetmetastate[]", "Turn In");
Is(e, "vtsetmetastate[Hunt - Phase 2]", "1"); // typed text with a '-'
Is(e, "vtgetmetastate[]", "Hunt - Phase 2");
e.Evaluate("setvar[opt, EnableCombat]");
Is(e, "vtgetsetting[$opt]", "1");
Is(e, "vtsetsetting[$opt, 0]", "1");
Is(e, "vtgetsetting[EnableCombat]", "0");
e.Evaluate("setvar[fmt, N3]");
Is(e, "cstrf[3.14159,$fmt]", "3.142");
Is(e, "cstrf[3.14159,`N3`]", "3.142"); // the reference's example
}
private static void DocLiveState()
{
FakeHost.Reset();
const uint north = 0x80000021, east = 0x80000022, near = 0x80000023;
FakeHost.PlayerPose = (0xA9B4001Cu, 96f, 96f, 0f);
FakeHost.Positions[north] = (0xA9B50001u, 96f, 10f, 0f); // the landblock to the north, low y
FakeHost.Positions[east] = (0xAAB40001u, 10f, 96f, 0f); // the landblock to the east, low x
FakeHost.Positions[near] = (0xA9B4001Cu, 96f, 150f, 0f);
FakeHost.KnownSpells.Add(2931);
FakeHost.Spellbook.AddRange(new uint[] { 2931, 1 });
var e = Engine(FakeHost.Create(), playerId: Player);
// "heading in degrees (0-360 clockwise, 0 is north) from your player to the target"
Is(e, "getheadingto[0x80000021]", "0"); // was 180: the local y alone is south
Is(e, "getheadingto[0x80000022]", "90"); // was 270
Is(e, "getheadingto[0x80000023]", "0");
Is(e, "getheadingto[0]", "0");
// "2 if the attempt is impossible": a spell the character doesn't know.
Is(e, "actiontrycastbyid[1]", "2");
Is(e, "actiontrycastbyidontarget[1, 0x80000023]", "2");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast for an unknown spell");
Is(e, "actiontrycastbyid[2931]", "0"); // known: not in magic mode yet, one step taken
Is(e, "getknownspells[]", "[2931,1]");
Is(e, "listcontains[getknownspells[], 2931]", "1");
Is(Engine(), "getknownspells[]", "[]"); // no host
}
private static void VitaeWithoutHost()
{
Check.Eq(Engine().Evaluate("vitae[]"), "0", "no host: no known penalty");

View file

@ -194,7 +194,9 @@ internal static class HealLatencyTests
Check.Eq(FakeHost.Casts.Count, 2, "...but Stamina to Mana, so the mana comes back");
Check.Eq(r.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
Check.True(r.Logged("not enough mana; resting the family 15s"), "a non-heal still rests 15 s");
// Stamina to Mana is a vital too (the mana reserve, 2026-10-11): 2 s, not the 15 s a buff rests.
Check.Eq(FakeHost.Logs.Count(l => l.Contains("not enough mana; resting the family 2s", StringComparison.Ordinal)), 2,
"Stamina to Mana rests 2 s as well, not 15 s");
System.Threading.Thread.Sleep(2100);
r.V.CurrentMana = 60;
Check.True(r.B.CheckVitals(), "2 s later, mana back");

View file

@ -114,11 +114,11 @@ internal static class InstallPathsTests
Check.Eq(RynthCore.Plugin.RynthAi.Loot.LootEditorBridge.LootFolder, @"C:\Games\RynthSuite\RynthAi\LootProfiles", "loot profiles");
Check.Eq(RynthCore.Plugin.RynthAi.Vendor.AutoVendorManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoVendor", "AutoVendor");
Check.Eq(RynthCore.Plugin.RynthAi.Trade.AutoTradeManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoTrade", "AutoTrade");
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureWeakness.WeaknessFile, @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json", "weakness file");
Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons");
// The tests point the store at their scratch folder (Program.Main); this is its value before that.
Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards");
Check.Eq(Program.LiveCreatureFolder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
}
private static string? PrivateStatic(Type type, string field)

View file

@ -0,0 +1,273 @@
using System;
using System.Linq;
using System.Reflection;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// The mana reserve (2026-10-11). A void mage, Life Magic 304, at 1/383 mana and 289/383 stamina
// against Rampagers: "You don't have enough Mana to cast this spell", and RynthAi kept casting
// Corruption instead of Stamina to Mana. Combat had drained mana under what Stamina to Mana costs,
// its refusal parked it 15 s, and with no mana potion nothing held the arbiter for vitals. Now a
// caster keeps ManaReserveFactor x Stamina to Mana's cost: under it Stamina to Mana goes first and
// combat holds its casts; under the cost, the highest level it can pay for goes, or mana
// regenerates while attacks wait, and a mana refusal rests the vital only briefly.
internal static class ManaReserveTests
{
private const uint Player = 0x50000B21;
private const uint STypeLife = 33;
private const uint STypeVoid = 43;
private const int Target = 0x7000A021;
private const string NotEnoughMana = "You don't have enough Mana to cast this spell.";
public static void Register(Runner r)
{
r.Add("mana reserve: under 1.5x Stamina to Mana's cost, Stamina to Mana is chosen over an attack", ReserveChoosesStaminaToMana);
r.Add("mana reserve: under Stamina to Mana's cost, no attack spam and no 15 s park on 'not enough Mana'", StarvedNoSpamNoPark);
r.Add("mana reserve: as mana regenerates, the level it can pay for goes, then attacks resume", RecoversAsManaRegenerates);
r.Add("mana reserve: stamina too low for Stamina to Mana - stamina is refilled first", StaminaFirst);
r.Add("mana reserve: combat holds an attack it can't pay for, and casts once mana is back", CombatHoldsCast);
r.Add("mana reserve: a melee fighter's attacks aren't held; Get Mana At off means no reserve", MeleeAndOff);
r.Add("mana reserve: the dat's BaseMana is read (when this PC has a portal.dat)", DatBaseMana);
}
private static int Family(string name) => SpellTableStub.GetById(SpellTable.Named(name).First().Id)!.Family;
private static int Id(string name) => SpellTable.Named(name).First().Id;
private static string NameOf(int id) => SpellTableStub.GetById(id)?.Name ?? $"#{id}";
private static int CostByLevel(int id) => (SpellTableStub.GetById(id)?.Level ?? 0) * 10;
private static int FamilyOfCast(int i) => SpellTableStub.GetById(FakeHost.Casts[i].SpellId)?.Family ?? 0;
private sealed class Rig
{
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public bool InCombat = true;
public Rig(uint mana, uint stamina = 289, int getManaAt = 20, int combatMode = 0)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = combatMode == 0 ? CombatMode.Magic : combatMode;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (304, 2);
FakeHost.Skills[(Player, STypeVoid)] = (400, 3);
BuffManager.ManaCostOverride = CostByLevel; // level x 10: I 10 ... VII 70, VIII 80
var host = FakeHost.Create();
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
GetManaAt = getManaAt, TopOffMana = getManaAt, RestamAt = 0, TopOffStam = 0, UsePotions = false,
EnableBuffing = false,
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache { MaxHealth = 400, CurrentHealth = 400, MaxStamina = 383, CurrentStamina = stamina, MaxMana = 383, CurrentMana = mana };
B = new BuffManager(host, S, sm, V);
B.SetCharacterSkills(skills);
B.InCombatOverride = () => InCombat;
}
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static BotActivity Arbiter(BuffManager b)
{
var inputs = new ArbiterInputs(true, b.PendingSpellId != 0 || b.WantsVitalRecharge, wantCombat: true,
wantLooting: false, wantSalvaging: false, wantNav: true, combatEngaged: true);
return ActivityArbiter.Decide(in inputs);
}
private static void ReserveChoosesStaminaToMana()
{
// Over Get Mana At 20% (77 of 383), but under 1.5x the top Stamina to Mana's cost.
var r = new Rig(mana: 300);
int corruption = Id("Corruption VII");
int reserve = r.B.ManaReserve();
Check.True(reserve > 77, $"the reserve ({reserve}) is over Get Mana At's 77 points");
r.V.CurrentMana = (uint)(reserve - 5);
Check.True(r.V.ManaPct >= 20, $"{r.V.CurrentMana}/383 is over Get Mana At");
Check.True(r.B.WantsManaNow(), "under the reserve, in combat: vitals want the tick");
Check.True(r.B.WantsVitalRecharge, "...which is what the arbiter reads");
Check.Eq(Arbiter(r.B), BotActivity.Buffing, "the arbiter gives vitals the tick over combat");
string? hold = r.B.OffensiveCastHold(corruption);
Check.True(hold != null && hold.Contains("reserve"), $"combat's Corruption VII waits ({hold})");
Check.True(r.B.CheckVitals(), "vitals act");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
Check.Eq(FamilyOfCast(0), Family("Stamina to Mana Self I"), $"it is Stamina to Mana ({NameOf(FakeHost.Casts[0].SpellId)})");
int cost = CostByLevel(FakeHost.Casts[0].SpellId);
Check.Eq(r.B.ManaReserve(), (int)Math.Ceiling(cost * BuffManager.ManaReserveFactor), "the reserve is 1.5x that level's cost");
// Plenty of mana: nothing held.
r.V.CurrentMana = 300;
Check.False(r.B.WantsManaNow(), "300/383: no hold");
Check.Null(r.B.OffensiveCastHold(corruption), "300/383: combat casts");
}
private static void StarvedNoSpamNoPark()
{
// The report: 1/383 mana. No Stamina to Mana level costs 1 or less.
var r = new Rig(mana: 1);
int corruption = Id("Corruption VII");
for (int i = 0; i < 5; i++)
Check.True(r.B.CheckVitals(), $"check {i}: vitals hold the tick (mana regenerating)");
Check.Eq(FakeHost.Casts.Count, 0, "no Stamina to Mana sent that the server would refuse");
Check.Eq(r.LogCount("is under"), 1, "logged once");
Check.True(r.LogCount("attacks wait, regenerating") == 1, "the log says attacks wait");
Check.True(r.B.WantsManaNow(), "vitals keep the tick while it regenerates");
Check.Eq(Arbiter(r.B), BotActivity.Buffing, "combat doesn't get it");
string? hold = r.B.OffensiveCastHold(corruption);
Check.True(hold != null && hold.Contains("Corruption VII's cost"), $"an attack under its own cost waits ({hold})");
Check.Eq(r.B.BuffingLabel, BuffManager.LabelMana, "the slot reads Restoring mana");
// Costs unknown (no dat): Stamina to Mana is tried; refused for mana it rests 2 s, not 15 s,
// and mana regenerates meanwhile with attacks still held.
var u = new Rig(mana: 50);
BuffManager.ManaCostOverride = _ => 0;
Check.True(u.B.CheckVitals(), "50/383 under Get Mana At: Stamina to Mana goes");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
u.B.OnChatWindowText(NotEnoughMana, 0);
Check.True(FakeHost.Logs.Any(l => l.Contains("not enough mana; resting the family 2s", StringComparison.Ordinal)), "rested 2 s, not 15 s");
Check.True(u.B.CheckVitals(), "inside the rest: vitals still hold (regenerating)");
Check.Eq(FakeHost.Casts.Count, 1, "no re-cast inside the rest");
Check.True(u.B.WantsManaNow(), "the short rest doesn't let combat in");
System.Threading.Thread.Sleep(2100);
u.V.CurrentMana = 70;
Check.True(u.B.CheckVitals(), "2 s later");
Check.Eq(FakeHost.Casts.Count, 2, "Stamina to Mana is cast again");
Check.Eq(FamilyOfCast(1), Family("Stamina to Mana Self I"), "Stamina to Mana");
}
private static void RecoversAsManaRegenerates()
{
var r = new Rig(mana: 1);
Check.True(r.B.CheckVitals(), "1 mana: waiting");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast");
r.V.CurrentMana = 15; // pays for level I (10), nothing higher
Check.True(r.B.CheckVitals(), "15 mana");
Check.Eq(FakeHost.Casts.Count, 1, "a Stamina to Mana goes");
Check.True(CostByLevel(FakeHost.Casts[0].SpellId) <= 15, $"the level it can pay for ({NameOf(FakeHost.Casts[0].SpellId)})");
r.V.CurrentMana = (uint)(r.B.ManaReserve() - 1); // the top level is payable again; still under the reserve
Check.True(r.B.CheckVitals(), "just under the reserve");
Check.Eq(FakeHost.Casts.Count, 2, "Stamina to Mana again");
int top = r.B.ManaReserve();
Check.True(CostByLevel(FakeHost.Casts[1].SpellId) * BuffManager.ManaReserveFactor >= top - 1,
$"the top level this time ({NameOf(FakeHost.Casts[1].SpellId)})");
r.V.CurrentMana = 300;
Check.False(r.B.WantsManaNow(), "300 mana: vitals let go");
Check.Null(r.B.OffensiveCastHold(Id("Corruption VII")), "attacks resume");
Check.False(r.B.CheckVitals(), "nothing for vitals to do");
}
private static void StaminaFirst()
{
// 50 mana (under Get Mana At 20% = 77) and 10% stamina: Stamina to Mana can't go (stamina
// under 15%), so Revitalize first - at a level 50 mana pays for.
var r = new Rig(mana: 50, stamina: 38);
Check.True(r.B.CheckVitals(), "vitals act");
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), $"Revitalize ({NameOf(FakeHost.Casts[0].SpellId)})");
Check.True(CostByLevel(FakeHost.Casts[0].SpellId) <= 50, "a level the mana pays for");
Check.Eq(r.B.BuffingLabel, BuffManager.LabelStamina, "Restoring stamina");
Check.False(r.B.WantsManaNow(), "with no stamina kit or potion, attacks aren't held for mana (Revitalize costs mana too)");
// Re-stam At off and Stamina to Mana unaffordable doesn't matter: stamina goes first all the same.
var off = new Rig(mana: 50, stamina: 38);
off.S.RestamAt = 0;
Check.True(off.B.CheckVitals(), "Re-stam At 0: still refilled for Stamina to Mana");
Check.Eq(FamilyOfCast(0), Family("Revitalize Self I"), "Revitalize");
}
private static void CombatHoldsCast()
{
FakeHost.Reset();
foreach (string n in new[] { "Flame Bolt VI" })
foreach (var row in SpellTable.Named(n)) FakeHost.Spellbook.Add((uint)row.Id);
var s = new LegacyUiSettings { IsMacroRunning = true, GetManaAt = 20, TopOffMana = 20, UsePotions = false, RingRange = 0 };
s.MinSkillLevelTier1 = 0; s.MinSkillLevelTier2 = 0; s.MinSkillLevelTier3 = 0; s.MinSkillLevelTier4 = 0;
s.MinSkillLevelTier5 = 0; s.MinSkillLevelTier6 = 0; s.MinSkillLevelTier7 = 10000; s.MinSkillLevelTier8 = 10000;
s.MonsterRules.Add(new MonsterRule { Name = "Rampager", DamageType = "Fire", UseBolt = true });
FakeHost.PlayerPose = (0x0101001Bu, 0f, 0f, 0f);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 10f, 0f);
FakeHost.Names[(uint)Target] = "Rampager";
FakeHost.CombatModeValue = CombatMode.Magic;
BuffManager.ManaCostOverride = CostByLevel;
var host = FakeHost.Create(Player);
var cache = FakeHost.MakeCache(host, Player, new[] { (uint)Target });
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
var sm = new SpellManager(host, s);
sm.InitializeNatively();
sm.RefreshKnownSpells();
c.SetSpellManager(sm);
var v = new PlayerVitalsCache { MaxHealth = 400, CurrentHealth = 400, MaxStamina = 383, CurrentStamina = 289, MaxMana = 383, CurrentMana = 1 };
var b = new BuffManager(host, s, sm, v);
b.InCombatOverride = () => true;
c.ManaReserveHold = id => b.OffensiveCastHold(id);
c.activeTargetId = Target;
var target = new WorldObject(Target, "Rampager");
MethodInfo attack = typeof(CombatManager).GetMethod("AttackWithMagic", BindingFlags.NonPublic | BindingFlags.Instance)!;
FieldInfo held = typeof(CombatManager).GetField("_manaCastHeld", BindingFlags.NonPublic | BindingFlags.Instance)!;
for (int i = 0; i < 3; i++) attack.Invoke(c, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 0, "1 mana: Flame Bolt VI (60) isn't sent");
Check.True((bool)held.GetValue(c)!, "held for mana");
Check.Eq(c.LastCombatSkipReason, "mana-reserve", "the skip reason says so");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatCast] attacks wait: mana 1/383 is under Flame Bolt VI's cost (60)", StringComparison.Ordinal)), 1, "logged once");
v.CurrentMana = 300;
attack.Invoke(c, new object[] { target });
Check.Eq(FakeHost.Casts.Count, 1, "mana back: the bolt goes");
Check.Eq(NameOf(FakeHost.Casts[0].SpellId), "Flame Bolt VI", "Flame Bolt VI");
Check.False((bool)held.GetValue(c)!, "not held");
Check.True(FakeHost.Logs.Any(l => l.Contains("attacks resume", StringComparison.Ordinal)), "and says attacks resume");
}
private static void MeleeAndOff()
{
// A melee fighter (no combat manager: the stance decides) at low mana: no reserve, no hold.
var melee = new Rig(mana: 1, combatMode: CombatMode.Melee);
Check.False(melee.B.WantsManaNow(), "melee: vitals don't hold the fight for mana");
melee.V.CurrentMana = 85; // 22%: over Get Mana At 20%, under a caster's reserve (90)
Check.False(melee.B.ManaUnderLine(true, out int line), $"melee: only Get Mana At ({line})");
// Get Mana At 0 (mana recharge off in combat): no reserve, nothing held.
var off = new Rig(mana: 100, getManaAt: 0);
Check.False(off.B.WantsManaNow(), "Get Mana At 0: no hold");
Check.Null(off.B.OffensiveCastHold(Id("Corruption VII")), "Get Mana At 0: combat casts (it can pay)");
Check.False(off.B.CheckVitals(), "and vitals do nothing for mana");
}
private static void DatBaseMana()
{
var saved = BuffManager.ManaCostOverride;
BuffManager.ManaCostOverride = null;
try
{
int s2m1 = Id("Stamina to Mana Self I");
if (!ComponentDatabase.TryGetSpellBaseMana(s2m1, out int m1))
{
Console.WriteLine(" (no portal.dat on this PC: BaseMana not checked)");
return;
}
string[] names = { "Stamina to Mana Self I", "Stamina to Mana Self IV", "Stamina to Mana Self VI",
"Revitalize Self VI", "Heal Self VI", "Corruption VII", "Flame Bolt VI" };
string line = string.Join(", ", names.Select(n => $"{n} {BuffManager.SpellManaCost(Id(n))}"));
Console.WriteLine(" dat BaseMana: " + line);
Check.True(m1 > 0, $"Stamina to Mana Self I costs something ({m1})");
Check.True(BuffManager.SpellManaCost(Id("Stamina to Mana Self VI")) > m1, "level VI costs more than level I");
}
finally { BuffManager.ManaCostOverride = saved; }
}
}

View file

@ -62,6 +62,8 @@ internal static class MetaTests
r.Add("meta edit: a saved rule keeps CallState's return state and ChatCapture's colours", EditKeepsHiddenFields);
r.Add("meta edit: the editor's Set current text matches the landblock / landcell", SetCurrentMatches);
r.Add("meta edit: a new state's Never -> None rule keeps it through a save and reload", NewStateSurvivesReload);
r.Add("meta: rule names survive a save and reload (.af \"~~ @name\")", RuleNamesRoundTrip);
r.Add("meta edit: an update without a name (an engine without rule names) keeps the rule's name", UpdateKeepsName);
}
private static void SetCurrentMatches()
@ -109,6 +111,71 @@ internal static class MetaTests
Check.False(rig.Has("x"), "its Never rule never fires");
}
private static void RuleNamesRoundTrip()
{
var named = Rule("Hunt", C.Always, "", A.ChatCommand, "/vt start");
named.Name = "Start hunting";
var both = Rule("Hunt", C.Never, "", A.None, "");
both.Name = " Parked " + "\r\n" + " rule "; // trimmed, kept on one line
both.Enabled = false;
var plain = Rule("Hunt", C.Always, "", A.None, "");
var rules = new List<MetaRule> { named, both, plain };
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
Check.True(text.Contains("~~ @name Start hunting"), "written as a ~~ @name line");
var back = AfFileParser.LoadFromText(text);
Check.Eq(back.Rules.Count, 3, "every rule back");
Check.Eq(back.Warnings.Count, 0, "no warnings");
if (back.Rules.Count == 3)
{
Check.Eq(back.Rules[0].Name, "Start hunting", "the name");
Check.Eq(back.Rules[1].Name, "Parked rule", "one line, trimmed");
Check.False(back.Rules[1].Enabled, "a name and @disabled together");
Check.Eq(back.Rules[2].Name, "", "a name belongs to one rule only");
}
// Hand-written: either marker order; "@names" and an empty "@name" are just comments.
var hand = AfFileParser.LoadFromText(string.Join("\n", new[]
{
"STATE: {Default} ~~ {",
"\t~~ @disabled",
"\t~~ @name Second",
"\tIF:\tAlways",
"\t\tDO:\tNone",
"\t~~ @names are just a comment",
"\tIF:\tNever",
"\t\tDO:\tNone",
"\t~~ @name",
"\tIF:\tNever",
"\t\tDO:\tNone",
"~~ }",
}));
Check.Eq(hand.Rules.Count, 3, "three rules");
if (hand.Rules.Count == 3)
{
Check.Eq(hand.Rules[0].Name, "Second", "name after @disabled");
Check.False(hand.Rules[0].Enabled, "still disabled");
Check.Eq(hand.Rules[1].Name, "", "@names is a comment");
Check.Eq(hand.Rules[2].Name, "", "an empty @name is a comment");
}
}
private static void UpdateKeepsName()
{
var rule = Rule("Default", C.Always, "", A.None, "");
rule.Name = "Keep me";
var rules = new List<MetaRule> { rule };
MetaRuleEdits.Replace(rules, 0, Rule("Default", C.Never, "", A.None, ""), keepName: true);
Check.Eq(rules[0].Name, "Keep me", "an engine without names doesn't wipe it");
Check.Eq(rules[0].Condition, C.Never, "the edit applied");
var renamed = Rule("Default", C.Never, "", A.None, "");
renamed.Name = "New name";
MetaRuleEdits.Replace(rules, 0, renamed);
Check.Eq(rules[0].Name, "New name", "a sent name replaces it");
MetaRuleEdits.Replace(rules, 0, Rule("Default", C.Never, "", A.None, ""));
Check.Eq(rules[0].Name, "", "a sent empty name clears it");
}
// ── Panel edits on a running meta (MetaRuleEdits, update_rule; 2026-10-05 autosave) ─────
private static void EditKeepsRunningMeta()
@ -936,6 +1003,21 @@ internal static class MetaTests
RunAction(rig, A.EmbeddedNavRoute, "__rynthai_offline_test_no_such_route__");
Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "unknown route: nothing loaded");
Check.True(FakeHost.Chat.Exists(c => c.Contains("Route missing")), "unknown route reported");
// "Patrol" (the Meta panel's first route choice): the dungeon patrol, as /ra dunnav-patrol.
rig.Ra.Clear();
RunAction(rig, A.EmbeddedNavRoute, "Patrol");
Check.Eq(string.Join("|", rig.Ra), "/ra dunnav-patrol", "Patrol starts the dungeon patrol");
Check.Eq(rig.S.CurrentRoute.Points.Count, 0, "...and loads no route itself");
rig.Ra.Clear();
RunAction(rig, A.EmbeddedNavRoute, "patrol");
Check.Eq(rig.Ra.Count, 1, "any case");
// A meta's own route called Patrol wins.
rig.Ra.Clear();
rig.S.EmbeddedNavs["Patrol"] = once;
RunAction(rig, A.EmbeddedNavRoute, "Patrol");
Check.Eq(rig.Ra.Count, 0, "an embedded route named Patrol is used instead");
Check.Eq(rig.S.CurrentNavPath, "<embedded:Patrol>", "...and loaded");
}
private static void Watchdog()

View file

@ -49,6 +49,7 @@ internal static class WeaponTests
r.Add("slayer: the element follows the chosen weapon", SlayerElement);
r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight);
r.Add("weapon swap: no flip-flop between two weapons", SwapNoFlipFlop);
r.Add("weapon swap: a server refusal counts as a failed try", SwapRefused);
@ -666,6 +667,37 @@ internal static class WeaponTests
}
}
private static void MissingFromPack()
{
// 2026-10-11: Drakkon's buff wand left his pack and the Items slot still just said "Wand".
const int InPack = 0x7000A001, InHand = 0x7000A002, Gone = 0x7000A003, Unknown = 0x7000A004;
var known = new Dictionary<int, WorldObject>
{
[InPack] = new WorldObject(InPack, "Silver Wand", AcObjectClass.WandStaffOrb),
[InHand] = new WorldObject(InHand, "Ken", AcObjectClass.MeleeWeapon),
[Gone] = new WorldObject(Gone, "Wand", AcObjectClass.WandStaffOrb), // the client still knows it
};
WorldObject? Look(int id) => known.TryGetValue(id, out var wo) ? wo : null;
var rules = new List<ItemRule>
{
new() { Id = InPack, Name = "Silver Wand" },
new() { Id = InHand, Name = "Ken" },
new() { Id = Gone, Name = "Wand" },
new() { Id = Unknown, Name = "Old Bow" },
new() { Id = 0, Name = "never resolved" },
};
var pack = new[] { known[InPack], new WorldObject(0x7000A0FF, "Pyreal", AcObjectClass.Money) };
var missing = WeaponList.MissingIds(rules, pack, Look, wo => wo.Id == InHand);
Check.True(!missing.Contains(InPack), "in the pack: carried");
Check.True(!missing.Contains(InHand), "wielded (not in the pack list): carried");
Check.True(missing.Contains(Gone), "left the pack, the client still knows it: missing");
Check.True(missing.Contains(Unknown), "the client doesn't know it at all: missing");
Check.Eq(missing.Count, 2, "only those two (id 0 is never reported)");
missing = WeaponList.MissingIds(rules, Array.Empty<WorldObject>(), Look, _ => false);
Check.Eq(missing.Count, 0, "inventory not known yet (empty, logging in): nothing reported missing");
}
private static void UnlistedNeverPicked()
{
var rig = new Rig(1535, "Ethereal Wisp");
@ -683,10 +715,23 @@ internal static class WeaponTests
var cache = FakeHost.MakeCache(FakeHost.Create(), Player, new[] { ListedWand, FireWand, NamedJunk });
WorldObject? Look(int id) => cache[id];
var inv = new[] { cache[unchecked((int)FireWand)]!, cache[unchecked((int)NamedJunk)]! };
int got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: true, out bool unlisted);
Check.Eq(unchecked((uint)got), ListedWand, "a wand is listed: that one, never the pack's");
var invWithListed = new[] { cache[unchecked((int)ListedWand)]!, cache[unchecked((int)FireWand)]!, cache[unchecked((int)NamedJunk)]! };
int got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, invWithListed, allowUnlisted: true, out bool unlisted);
Check.Eq(unchecked((uint)got), ListedWand, "a wand is listed and carried: that one, never another from the pack");
Check.False(unlisted, "not from the pack");
// 2026-10-11: the listed wand left the pack (the client still knows the object). It is
// not returned - the server ignores a wield of it and every buff was parked.
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: false, out _);
Check.Eq(got, 0, "listed wand not carried, setting off: no wand (buffs go bare-handed), not the gone one");
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, inv, allowUnlisted: true, out unlisted);
Check.Eq(unchecked((uint)got), FireWand, "listed wand not carried, setting on: a caster from the pack");
got = WeaponList.FindWand(rig.S.ItemRules, Look, wo => wo.Id == unchecked((int)ListedWand), inv, allowUnlisted: false, out _);
Check.Eq(unchecked((uint)got), ListedWand, "a listed wand in hand counts as carried");
var sameName = new WorldObject(0x7000ABCD, cache[unchecked((int)ListedWand)]!.Name, AcObjectClass.WandStaffOrb);
got = WeaponList.FindWand(rig.S.ItemRules, Look, _ => false, new[] { sameName }, allowUnlisted: false, out _);
Check.Eq(got, 0x7000ABCD, "listed wand gone: another of the same name in the pack stands in");
var none = new List<ItemRule>();
got = WeaponList.FindWand(none, Look, _ => false, new[] { cache[unchecked((int)NamedJunk)]! }, allowUnlisted: true, out _);
Check.Eq(got, 0, "no wand listed: a jewel named 'Fire Wand' is never taken (no name match)");

View file

@ -0,0 +1,500 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
namespace RynthSort.Tests
{
// RynthSort v3: rules with several classes and names (and their migration), the order inside
// packs, the side packs' top-to-bottom order, stacks joined in place, and that auto-sort runs out
// of moves on a fixed inventory instead of moving items back and forth.
internal static partial class Program
{
// ── Rules with several entries ──────────────────────────────────────
private static void MultiRules()
{
var armor = It(1, "Gold Breastplate", ObjectClasses.Armor);
var shirt = It(2, "Flared Shirt", ObjectClasses.Clothing);
var sword = It(3, "Tachi", ObjectClasses.MeleeWeapon);
var shield = It(4, "Kite Shield", ObjectClasses.Armor);
var opal = It(5, "Black Opal", ObjectClasses.Gem);
var gear = SortRule.For(4, new[] { ObjectClasses.Armor, ObjectClasses.Clothing, ObjectClasses.MeleeWeapon });
Check(SortRules.Matches(gear, armor) && SortRules.Matches(gear, shirt) && SortRules.Matches(gear, sword), "one rule, three classes: any of them matches");
Check(!SortRules.Matches(gear, opal), "not the others");
var mixed = SortRule.For(5, new[] { ObjectClasses.Gem }, "Shield", "Pyreal");
Check(SortRules.Matches(mixed, shield) && SortRules.Matches(mixed, opal), "classes and names in one rule: either matches");
var rules = new List<SortRule> { gear, mixed };
Eq(SortRules.RuleFor(rules, shield)?.Pack, 5, "the shield's name beats the armor class");
Eq(SortRules.RuleFor(rules, armor)?.Pack, 4, "other armor by class");
Check(!gear.AddClass(ObjectClasses.Armor) && gear.Classes.Count == 3, "a class is in a rule once");
Check(mixed.AddName(" Mote ") && mixed.HasName("mote") && !mixed.AddName("MOTE") && !mixed.AddName(" "), "names trimmed, once in any case, never blank");
Check(mixed.RemoveName("PYREAL") && !mixed.HasName("Pyreal"), "removed in any case");
Check(SortRule.Clean(new string('x', 80)).Length == SortRule.MaxNameLength, "names cut to 64");
Eq(SortRules.Describe(gear), "Armor, Clothing, Melee Weapon", "described A-Z");
Eq(SortRules.Describe(mixed), "Gem, name has \"Mote\", name has \"Shield\"", "classes first, then names, A-Z");
Eq(SortRules.Describe(new SortRule()), "(empty: add a class or a name)", "an empty rule");
Check(!SortRules.Matches(new SortRule(), opal), "an empty rule matches nothing");
Check(gear.SameAs(SortRule.For(4, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "same entries in another order: the same rule");
Check(!gear.SameAs(SortRule.For(5, new[] { ObjectClasses.MeleeWeapon, ObjectClasses.Armor, ObjectClasses.Clothing })), "another pack: not the same");
SortRule copy = mixed.Clone();
copy.AddClass(ObjectClasses.Key);
Check(!mixed.HasClass(ObjectClasses.Key) && copy.Uid != mixed.Uid, "a clone is its own rule");
var list = new List<SortRule> { SortRule.ForName("Zircon", 1), new SortRule { Pack = 1 }, SortRule.ForClass(ObjectClasses.Armor, 1), SortRule.ForClass(ObjectClasses.Gem, 1) };
list.Sort(SortRules.CompareForList);
Check(SortRules.Describe(list[0]) == "Armor" && SortRules.Describe(list[1]) == "Gem" && list[2].HasName("Zircon") && list[3].IsEmpty, "listed A-Z under a pack, empty last");
Eq(SortRules.Defaults().Count, 3, "defaults: components, salvage, and gems/stones/keys as one rule");
Check(SortRules.Defaults()[2].Classes.Count == 3, "the third default rule holds three classes");
}
private static void RuleMigration()
{
SortStore st = TempStore("migration");
string own = st.PathFor("S", "Old");
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
// A version 2 file (2026-10-11): one class or name per rule, ids, the fix done.
File.WriteAllText(own, "{\"version\":2,\"rules\":["
+ "{\"on\":true,\"kind\":\"class\",\"class\":12,\"text\":\"\",\"pack\":1,\"packId\":1073741825,\"packNote\":\"Sack - Components\"},"
+ "{\"on\":false,\"kind\":\"name\",\"class\":12,\"text\":\"Ink of\",\"pack\":2,\"packId\":1073741826},"
+ "{\"on\":true,\"kind\":\"name\",\"class\":12,\"text\":\"\",\"pack\":3}],"
+ "\"settings\":{\"auto\":true},\"packsFixed\":true}");
CharacterSortData d = st.Load("S", "Old", out string? problem);
Check(problem == null && d.Rules.Count == 3 && d.PacksFixed, "version 2 loads");
Check(d.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.SpellComponent }) && d.Rules[0].Names.Count == 0
&& d.Rules[0].PackId == 0x40000001 && d.Rules[0].PackNote == "Sack - Components", "a class rule: one class, its pack kept");
Check(d.Rules[1].Names.SequenceEqual(new[] { "Ink of" }) && d.Rules[1].Classes.Count == 0 && !d.Rules[1].On && d.Rules[1].PackId == 0x40000002,
"a name rule: one name (not its unused class), off stays off");
Check(d.Rules[2].IsEmpty, "a blank name rule matched nothing and still doesn't");
Check(d.Settings.OrderInPacks && !d.Settings.OrderKindFirst, "the order settings at their defaults");
// Saved as version 3, with the old fields too (an older RynthSort reads the first entry).
d.Rules[0].AddClass(ObjectClasses.Salvage);
d.Rules[0].AddName("Taper");
Check(st.Save("S", "Old", d) == null, "saved");
string json = File.ReadAllText(own);
Check(json.Contains("\"version\": 3") && json.Contains("\"classes\"") && json.Contains("\"names\""), "version 3 with lists");
using (var doc = System.Text.Json.JsonDocument.Parse(json))
{
var r0 = doc.RootElement.GetProperty("rules")[0];
Check(r0.GetProperty("kind").GetString() == "class" && r0.GetProperty("class").GetInt32() == ObjectClasses.SpellComponent, "old fields: the first class");
var r2 = doc.RootElement.GetProperty("rules")[2];
Check(r2.GetProperty("kind").GetString() == "name" && r2.GetProperty("text").GetString() == "", "an empty rule reads as a blank name rule to an older RynthSort");
var r1 = doc.RootElement.GetProperty("rules")[1];
Check(r1.GetProperty("kind").GetString() == "name" && r1.GetProperty("text").GetString() == "Ink of", "a name-only rule: its name the old way");
}
CharacterSortData back = st.Load("S", "Old", out problem);
Check(problem == null && back.Rules[0].Classes.Count == 2 && back.Rules[0].HasClass(ObjectClasses.Salvage) && back.Rules[0].HasName("taper"), "version 3 reads back whole");
// Odd lists: non-numbers and bad strings skipped, duplicates once, the old fields ignored when lists are there.
File.WriteAllText(own, "{\"version\":3,\"rules\":[{\"classes\":[11,\"x\",11,-3,13.0],\"names\":[\"Opal\",5,\"opal\",\" \"],\"kind\":\"class\",\"class\":39,\"pack\":2}]}");
CharacterSortData odd = st.Load("S", "Old", out _);
Check(odd.Rules[0].Classes.SequenceEqual(new[] { ObjectClasses.Gem, ObjectClasses.Key }) && odd.Rules[0].Names.SequenceEqual(new[] { "Opal" }), "lists cleaned; old fields ignored");
// The Lua script's rules read the same way (one entry each) and still compare as its own.
SortStore imp = TempStore("migration-lua");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(fresh.Rules.All(x => x.Classes.Count == 1 && x.Names.Count == 0) && fresh.Rules[0].SameAs(fresh.LuaRules![0]), "Lua rules: one class each, SameAs their file");
}
// ── Order inside a pack ─────────────────────────────────────────────
private static List<SortItem> Items(params string[] names)
{
var list = new List<SortItem>();
for (int i = 0; i < names.Length; i++) list.Add(It(100 + (uint)i, names[i], ObjectClasses.Misc));
return list;
}
private static string Names(IEnumerable<SortItem> items) => string.Join(",", items.Select(i => i.Name));
/// <summary>Runs NextMove (every item movable) until it stops; the moves it took.</summary>
private static int SortByMoves(List<SortItem> items, bool kindFirst, Dictionary<uint, int>? perItem = null, int limit = 1000)
{
int moves = 0;
while (moves < limit && PackOrder.NextMove(items, kindFirst, _ => true, out SortItem it, out int at))
{
PackOrder.Apply(items, it, at);
moves++;
if (perItem != null) perItem[it.Id] = perItem.TryGetValue(it.Id, out int n) ? n + 1 : 1;
}
return moves;
}
private static bool InOrder(IReadOnlyList<SortItem> items, bool kindFirst)
{
for (int i = 1; i < items.Count; i++)
if (PackOrder.Compare(items[i - 1], items[i], kindFirst) > 0) return false;
return true;
}
private static void InPackOrder()
{
// The order: A-Z any case; like names together; then the stack kind; then the id.
var a = It(5, "black opal", ObjectClasses.Gem, wcid: 2);
var b = It(4, "Black Opal", ObjectClasses.Gem, wcid: 2);
var c2 = It(3, "Black Opal", ObjectClasses.Gem, wcid: 1);
var d = It(9, "Amber", ObjectClasses.Misc);
var list = new List<SortItem> { a, b, c2, d };
list.Sort((x, y) => PackOrder.Compare(x, y, false));
Eq(string.Join(",", list.Select(i => i.Id)), "9,3,4,5", "Amber; then the Black Opals: same name together, by kind, by id");
var armor = It(20, "Zircon Plate", ObjectClasses.Armor);
var gem = It(21, "Agate", ObjectClasses.Gem);
Check(PackOrder.Compare(armor, gem, false) > 0 && PackOrder.Compare(armor, gem, true) < 0, "kind first: Armor before Gem whatever the names");
// One item that arrived at the end: one move puts it in its place.
var items = Items("Amber", "Bone", "Coal", "Dust", "Agate");
Check(PackOrder.NextMove(items, false, _ => true, out SortItem it, out int at) && it.Name == "Agate" && at == 0, "Agate to slot 0");
PackOrder.Apply(items, it, at);
Check(InOrder(items, false) && !PackOrder.NextMove(items, false, _ => true, out _, out _), "then in order: no move");
// One item at the top that belongs at the bottom: one move, not four.
items = Items("Zinc", "Amber", "Bone", "Coal", "Dust");
Eq(SortByMoves(items, false), 1, "Zinc to the end in one move");
Eq(Names(items), "Amber,Bone,Coal,Dust,Zinc", "in order");
// Reversed: n - 1 moves.
items = Items("E", "D", "C", "B", "A");
Eq(SortByMoves(items, false), 4, "reversed five: four moves");
Check(InOrder(items, false), "in order");
// A move "counted without it": moving down past others.
items = Items("B", "A", "C");
Check(PackOrder.NextMove(items, false, _ => true, out it, out at), "a move");
PackOrder.Apply(items, it, at);
Eq(Names(items), "A,B,C", $"{it.Name} to {at}");
// Where an arriving item goes.
items = Items("Amber", "Coal", "Dust");
Eq(PackOrder.InsertAt(items, It(1, "Bone", ObjectClasses.Misc), false), 1, "Bone between Amber and Coal");
Eq(PackOrder.InsertAt(items, It(1, "Zinc", ObjectClasses.Misc), false), 3, "Zinc at the end");
Eq(PackOrder.InsertAt(items, It(1, "Aaa", ObjectClasses.Misc), false), 0, "Aaa first");
Eq(PackOrder.InsertAt(new List<SortItem>(), It(1, "X", ObjectClasses.Misc), false), 0, "an empty pack");
// An item that can't move now isn't picked; another is.
items = Items("C", "B", "A");
Check(PackOrder.NextMove(items, false, x => x.Name != "A", out it, out _) && it.Name != "A", "a blocked item is skipped");
Check(!PackOrder.NextMove(Items("B", "A"), false, x => false, out _, out _), "nothing movable: no move");
Eq(PackOrder.OutOfPlace(Items("Zinc", "Amber", "Bone"), false), 1, "one out of place");
Eq(PackOrder.OutOfPlace(Items("Amber", "Bone"), false), 0, "in order");
Check(!PackOrder.AllNamed(new List<SortItem> { It(1, "", ObjectClasses.Misc) }), "an unnamed item: wait for its name");
// Every order of up to 7 items: in order after at most n - (longest run) moves, each item moved at most twice.
int worstPerItem = 0;
for (int n = 1; n <= 7; n++)
{
foreach (int[] perm in Permutations(n))
{
var p = perm.Select(i => It(100 + (uint)i, ((char)('A' + i)).ToString(), ObjectClasses.Misc)).ToList();
bool[] kept = PackOrder.Kept(PackOrder.Ranks(p, false));
int bound = kept.Count(x => !x);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, false, per);
if (!InOrder(p, false) || moves > bound) { Check(false, $"order {string.Join("", perm)}: {moves} moves (bound {bound}), in order {InOrder(p, false)}"); goto done; }
worstPerItem = Math.Max(worstPerItem, per.Values.DefaultIfEmpty(0).Max());
}
}
Check(true, "every order of 1-7 items sorts within n - (longest run) moves");
done:
Check(worstPerItem <= 2, $"no item moved more than twice ({worstPerItem})");
// Bigger packs, shuffled the same way every run.
var rnd = new Random(1234);
for (int round = 0; round < 40; round++)
{
int n = 10 + rnd.Next(93);
var p = Enumerable.Range(0, n).Select(i => It(1000 + (uint)i, "Item " + rnd.Next(60).ToString("D2"), ObjectClasses.Misc, wcid: (uint)rnd.Next(3))).OrderBy(_ => rnd.Next()).ToList();
int bound = PackOrder.OutOfPlace(p, round % 2 == 0);
var per = new Dictionary<uint, int>();
int moves = SortByMoves(p, round % 2 == 0, per);
if (!InOrder(p, round % 2 == 0) || moves > bound || per.Values.DefaultIfEmpty(0).Max() >= SortPlanner.MaxReorders)
{
Check(false, $"round {round}: {n} items, {moves} moves (bound {bound}), most per item {per.Values.DefaultIfEmpty(0).Max()}");
break;
}
}
Check(true, "40 shuffled packs of 10-102 items sort within the bound, under the per-item backstop");
}
private static IEnumerable<int[]> Permutations(int n)
{
var a = Enumerable.Range(0, n).ToArray();
yield return (int[])a.Clone();
while (true)
{
int i = n - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i < 0) yield break;
int j = n - 1;
while (a[j] <= a[i]) j--;
(a[i], a[j]) = (a[j], a[i]);
Array.Reverse(a, i + 1, n - i - 1);
yield return (int[])a.Clone();
}
}
private static void SlotOrders()
{
var pack = new SortPack { Id = 0x40000001 };
pack.Items.AddRange(Items("A", "B", "C")); // ids 100, 101, 102 (id order)
Check(pack.ApplyOrder(new uint[] { 102, 100, 101 }, 3) && pack.OrderKnown, "a list naming exactly the items read");
Eq(string.Join(",", pack.Items.Select(i => i.Id)), "102,100,101", "items in slot order");
Check(!pack.ApplyOrder(new uint[] { 102, 100 }, 2) && !pack.OrderKnown, "one short (a move behind): not known");
Check(!pack.ApplyOrder(new uint[] { 102, 100, 999 }, 3) && !pack.OrderKnown, "an id not read: not known");
Check(!pack.ApplyOrder(new uint[] { 102, 102, 100 }, 3) && !pack.OrderKnown, "an id twice: not known");
Eq(pack.Items.Count, 3, "a refused list leaves the items");
Check(pack.ApplyOrder(new uint[] { 100, 101, 102, 7 }, 3), "only the count given is read");
// The side packs, top first; foci in the list are fine.
SortInventory inv = Inv(3); // ids ...01, 02, 03 (id order)
Check(inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, 0x40000002 }, 4) && inv.PackOrderKnown, "pack column order");
Eq(string.Join(",", inv.Packs.Select(p => p.Id & 0xF)), "3,1,2", "pack 1 is the top pack");
SortInventory inv2 = Inv(3);
Check(!inv2.ApplyPackOrder(new uint[] { 0x40000003, 0x40000001 }, 2) && !inv2.PackOrderKnown, "a pack missing from the list: not known");
Eq(string.Join(",", inv2.Packs.Select(p => p.Id & 0xF)), "1,2,3", "id order kept");
// A rule's number follows its pack to its new place; the Lua fix still reads id order.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
rule.PackId = 0x40000003;
Check(PackFix.Sync(new List<SortRule> { rule }, inv) && rule.Pack == 1, "the top pack is now pack 1");
}
// ── The planner keeping every pack tidy ─────────────────────────────
private static void PlanInPack()
{
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 1) };
// A route into a pack whose order is known names the item's slot there.
SortInventory inv = Inv(1);
inv.Packs[0].Items.AddRange(new[] { It(50, "Agate", ObjectClasses.Gem), It(51, "Opal", ObjectClasses.Gem) });
inv.Packs[0].OrderKnown = true;
inv.Main.Items.Add(It(10, "Jet", ObjectClasses.Gem));
List<SortMove> m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route && m[0].Placement == 1, "Jet goes between Agate and Opal");
inv.Packs[0].OrderKnown = false;
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Placement == -1, "order unknown: the first empty slot");
m = new SortPlanner().Plan(inv, rules, SortScope.All, true, 0, 0);
Check(m.Count == 1 && m[0].Placement == -1, "without the options: as before");
// Nothing to route: stacks first, then order.
inv = Inv(1);
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.AddRange(new[]
{
It(60, "Opal", ObjectClasses.Gem, wcid: 7, stack: 3, max: 10),
It(61, "Agate", ObjectClasses.Gem),
It(62, "Opal", ObjectClasses.Gem, wcid: 7, stack: 5, max: 10),
});
var p = new SortPlanner();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count >= 1 && m[0].Kind == MoveKind.Stack && m[0].Item.Id == 60 && m[0].MergeInto == 62 && m[0].Dest.Id == inv.Packs[0].Id,
"the smaller Opal stack joins the larger, in its pack");
Check(m.Count == 1, "one tidy move per pack per pass");
inv.Packs[0].Items.RemoveAt(0);
inv.Packs[0].Items[1].Stack = 8;
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 0, "Agate, Opal: in order, one stack: nothing");
inv.Packs[0].Items.Reverse();
m = p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].InPlace && m[0].Placement >= 0, "out of order: a reorder in place");
Eq(p.View.Packs[0].OutOfPlace, 1, "the view counts it");
Check(p.View.Ordering && p.View.Packs[0].OrderKnown, "the view knows ordering is on");
// Not without the options, not for Main or Unpack, not for an unknown order, not with an unnamed item.
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000).Count, 0, "no options: no tidying");
Eq(p.Plan(inv, rules, SortScope.Main, false, 0, 5000, PlanOptions.Full).Count, 0, "Main: routes only");
inv.Packs[0].OrderKnown = false;
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "order unknown: not reordered");
inv.Packs[0].OrderKnown = true;
inv.Packs[0].Items.Add(It(70, "", ObjectClasses.Gem));
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "an unnamed item: wait");
inv.Packs[0].Items.RemoveAt(2);
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, new PlanOptions { Order = false, Merge = true }).Count, 0, "ordering off: no reorder");
// A route waits for nothing in place: routes first.
inv.Main.Items.Add(It(11, "Zircon", ObjectClasses.Gem));
m = p.Plan(inv, rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Route, "a route goes before any tidying");
// The main pack is put in order only once nothing in it is new.
inv = Inv(0);
inv.Main.OrderKnown = true;
inv.Main.Items.AddRange(new[] { It(80, "Zinc", ObjectClasses.Misc), It(81, "Amber", ObjectClasses.Misc) });
p = new SortPlanner();
Eq(p.Plan(inv, rules, SortScope.All, false, 0, 5000, PlanOptions.Full).Count, 0, "new items settling in the main pack: not yet");
m = p.Plan(inv, rules, SortScope.All, false, 5000, 5000, PlanOptions.Full);
Check(m.Count == 1 && m[0].Kind == MoveKind.Reorder && m[0].DestIndex == 0, "settled: the main pack is put in order");
Check(m[0].Done == "put in order in main pack", "logged as such");
// The backstop: an item put in order too often lately isn't again until the window passes.
for (int i = 0; i < SortPlanner.MaxReorders; i++) p.NoteReorder(80, 6000 + i);
Check(p.ReorderLimited(80, 7000), "limited after too many");
m = p.Plan(inv, rules, SortScope.All, false, 7000, 5000, PlanOptions.Full);
Check(m.All(x => x.Item.Id != 80), "not moved again");
Check(!p.ReorderLimited(80, 6000 + SortPlanner.ReorderWindowMs), "the window passes");
}
private static void MoveAnswersInPlace()
{
var item = It(10, "Opal", ObjectClasses.Gem, stack: 5);
var pack = new SortPack { Id = 0x40000001 };
var reorder = new MoveInFlight { Move = new SortMove(item, pack, 1, 0, 2, MoveKind.Reorder), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Pending,
"in its pack but not at its slot yet: still waiting (its container says nothing)");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "at its slot");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = Me, Slot = 0, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "moved away by someone: stop waiting");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = -1, ErrorSeq = 7 }, 1000 + MoveTracker.TimeoutMs), MoveOutcome.TimedOut, "no answer");
Eq(MoveTracker.Observe(reorder, new MoveObservation { Exists = true, Container = pack.Id, Slot = 0, ErrorSeq = 8, ErrorEventType = 0xA0, ErrorObject = 10 }, 1500),
MoveOutcome.Refused, "refused");
var join = new MoveInFlight { Move = new SortMove(item, pack, 1, 50, -1, MoveKind.Stack), SentMs = 1000, ErrorSeqAtSend = 7, StackAtSend = 5 };
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 5, ErrorSeq = 7 }, 1500), MoveOutcome.Pending, "a join: still whole");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = true, Container = pack.Id, Stack = 2, ErrorSeq = 7 }, 1500), MoveOutcome.Done, "part of it joined");
Eq(MoveTracker.Observe(join, new MoveObservation { Exists = false }, 1500), MoveOutcome.Done, "all of it joined");
}
// ── Convergence ─────────────────────────────────────────────────────
/// <summary>A messy character: loot in the main pack, items in the wrong packs, packs out of order, split stacks.</summary>
private static SortInventory Messy()
{
SortInventory inv = Inv(3, cap: 24);
foreach (SortPack p in inv.Packs) p.OrderKnown = true;
inv.Main.OrderKnown = true;
uint id = 1000;
SortItem Add(SortPack p, string name, int cls, uint wcid = 0, int stack = 1, int max = 1)
{
var it = It(id++, name, cls, wcid, stack, max);
p.Items.Add(it);
return it;
}
// Main pack: loot of every kind, and things no rule wants.
Add(inv.Main, "Lead Scarab", ObjectClasses.SpellComponent, 691, 3, 100);
Add(inv.Main, "Salvaged Iron", ObjectClasses.Salvage);
Add(inv.Main, "Black Opal", ObjectClasses.Gem, 2401, 1, 1);
Add(inv.Main, "Zircon Plate", ObjectClasses.Armor);
Add(inv.Main, "Ashcoal", ObjectClasses.Misc);
Add(inv.Main, "Healing Kit", ObjectClasses.HealingKit, 628, 1, 1);
Add(inv.Main, "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 40, 100);
Add(inv.Main, "Amber Ring", ObjectClasses.Jewelry);
// Pack 1 (components): out of order, split stacks, a gem that belongs in pack 3.
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 70, 100);
Add(inv.Packs[0], "Hyssop", ObjectClasses.SpellComponent, 650, 5, 100);
Add(inv.Packs[0], "Agate", ObjectClasses.Gem, 2394, 1, 1);
Add(inv.Packs[0], "Prismatic Taper", ObjectClasses.SpellComponent, 20631, 90, 100);
Add(inv.Packs[0], "Copper Scarab", ObjectClasses.SpellComponent, 690, 1, 100);
Add(inv.Packs[0], "Lead Scarab", ObjectClasses.SpellComponent, 691, 99, 100);
Add(inv.Packs[0], "Birch", ObjectClasses.SpellComponent, 660, 10, 100);
// Pack 2 (salvage): reversed.
foreach (string s in new[] { "Salvaged Steel", "Salvaged Granite", "Salvaged Gold", "Salvaged Ebony", "Salvaged Copper" })
Add(inv.Packs[1], s, ObjectClasses.Salvage);
// Pack 3 (gems, stones, keys): a component that belongs in pack 1, and stray misc.
Add(inv.Packs[2], "Mana Stone", ObjectClasses.ManaStone);
Add(inv.Packs[2], "Legendary Key", ObjectClasses.Key);
Add(inv.Packs[2], "Gold Scarab", ObjectClasses.SpellComponent, 693, 2, 100);
Add(inv.Packs[2], "Pyreal Mote", ObjectClasses.Misc);
Add(inv.Packs[2], "Diamond", ObjectClasses.Gem);
return inv;
}
private static void Converges()
{
foreach (bool kindFirst in new[] { false, true })
foreach (SortScope scope in new[] { SortScope.All, SortScope.Clean })
{
string what = $"{scope}{(kindFirst ? ", kind first" : "")}";
SortInventory inv = Messy();
List<SortRule> rules = SortRules.Defaults();
var opt = PlanOptions.Full;
opt.KindFirst = kindFirst;
var planner = new SortPlanner();
var seen = new HashSet<string>();
int passes = 0, moved = 0;
bool repeated = false;
// The planner on the same inventory, each pass's first move done as the server does it.
for (; passes < 500; passes++)
{
List<SortMove> moves = planner.Plan(inv, rules, scope, false, 10_000 + passes, 0, opt);
if (moves.Count == 0) break;
SortMove m = moves[0];
string state = Snapshot(inv) + "|" + m.Item.Id + ">" + m.Dest.Id + "@" + m.Placement + "+" + m.MergeInto;
if (!seen.Add(state)) repeated = true;
ServerApply(inv, m);
if (m.Kind == MoveKind.Reorder) planner.NoteReorder(m.Item.Id, 10_000 + passes);
moved++;
}
Console.WriteLine($" {what}: {moved} moves to tidy the messy inventory");
Check(passes < 500, $"{what}: runs out of moves ({moved} moves)");
Check(!repeated, $"{what}: never the same move from the same state twice");
Check(moved <= 60, $"{what}: in a sensible number of moves ({moved})");
for (int i = 0; i < 50; i++)
if (planner.Plan(inv, rules, scope, false, 20_000 + i * 1000, 0, opt).Count != 0) { Check(false, $"{what}: stays still afterwards"); break; }
Check(true, $"{what}: 50 more passes, no move");
// And it is tidy: every item in its pack, packs in order, one stack with room per kind.
foreach (SortItem it in inv.Main.Items.Concat(inv.Packs.SelectMany(p => p.Items)))
{
SortRule? r = SortRules.RuleFor(rules, it);
SortPack where = inv.Packs.Prepend(inv.Main).First(p => p.Items.Contains(it));
if (r != null) Check(where.Id == inv.Packs[r.Pack - 1].Id, $"{what}: {it.Name} in its rule's pack");
else if (scope == SortScope.Clean) Check(where == inv.Main, $"{what}: {it.Name} (no rule) back in the main pack");
}
foreach (SortPack pk in inv.Packs.Prepend(inv.Main))
{
Check(InOrder(pk.Items, kindFirst), $"{what}: {pk.Name} in order ({Names(pk.Items)})");
Check(!SortPlanner.StackJoin(pk, _ => true, out _, out _), $"{what}: {pk.Name} has no two stacks to join");
}
Eq(inv.Packs[0].Items.Count(i => i.Name == "Prismatic Taper"), 2, $"{what}: tapers 200 = 100 + 100");
}
}
private static string Snapshot(SortInventory inv) =>
string.Join(";", inv.Packs.Prepend(inv.Main).Select(p => string.Join(",", p.Items.Select(i => i.Id + "x" + i.Stack))));
private static void ConvergesInTheLoop()
{
// The controller with auto-sort on, against a pretend server that does what ACE does.
var w = new FakeWorld { Inv = Messy(), Can = SortAbilities.All };
SortController c = Controller(auto: true, gapMs: 300, settleSec: 1);
Ticks(c, w, 0, 120_000);
int sent = w.Sent.Count;
if (Environment.GetEnvironmentVariable("RSORT_DEBUG") == "1") foreach (SortMove dm in w.Sent) Console.WriteLine($" {dm.Kind} {dm.Item.Name} x{dm.Item.Stack} -> {dm.DestLabel} @{dm.Placement} +{dm.MergeInto}");
Console.WriteLine($" auto-sort: {sent} moves ({w.Sent.Count(m => m.Kind == MoveKind.Route)} to packs, {w.Sent.Count(m => m.Kind == MoveKind.Stack)} stacks joined, {w.Sent.Count(m => m.Kind == MoveKind.Reorder)} reorders)");
Check(sent > 20 && sent < 80, $"auto-sort tidied everything ({sent} moves)");
Eq(c.Status, "watching", "then watching");
Eq(c.Failed, 0, "no move failed or timed out on the way");
Check(c.Log.Any(l => l.Contains("put in order")), $"reorders logged ({string.Join(" / ", c.Log)})");
Ticks(c, w, 120_000, 600_000);
Eq(w.Sent.Count, sent, "eight minutes more: not one move (nothing moves back and forth)");
foreach (SortPack pk in w.Inv.Packs.Prepend(w.Inv.Main)) Check(InOrder(pk.Items, false), $"{pk.Name} in order");
// New loot: routed into its place after the settle time, nothing else stirs.
w.Inv.Main.Items.Add(It(5000, "Cobalt Scarab", ObjectClasses.SpellComponent, 6000, 1, 100));
Ticks(c, w, 600_000, 700_000);
Eq(w.Sent.Count, sent + 1, "one new item: one move");
SortMove last = w.Sent[^1];
Check(last.Kind == MoveKind.Route && last.Placement >= 0 && last.Dest.Id == w.Inv.Packs[0].Id, "into pack 1 at its slot");
Check(InOrder(w.Inv.Packs[0].Items, false), "pack 1 still in order (it landed in its place)");
// An engine before API v80: items still go to their packs; nothing is reordered.
var old = new FakeWorld { Inv = Messy(), Can = new SortAbilities { Merge = true } };
SortController c2 = Controller(auto: true, settleSec: 0);
Ticks(c2, old, 0, 120_000);
Check(old.Sent.All(m => m.Kind != MoveKind.Reorder && m.Placement == -1), "no slots, no reorders");
Check(old.Inv.Packs[2].Items.All(i => i.ObjectClass != ObjectClasses.SpellComponent), "but the misplaced component left pack 3");
int oldSent = old.Sent.Count;
Ticks(c2, old, 120_000, 300_000);
Eq(old.Sent.Count, oldSent, "and it stays still too");
}
}
}

View file

@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthSort;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Views;
namespace RynthSort.Tests
{
// Rules tied to pack ids, the one-time fix of imported Lua pack numbers, the pack picker's labels
// and spell component classification.
internal static partial class Program
{
private const uint FocusA = 0x40000F01, FocusB = 0x40000F02;
/// <summary>
/// A main pack whose side slots are, in the client's list order: a focus, pack A, a focus,
/// pack B, pack C. The Lua script numbered those 1-5; RynthSort's packs are A, B, C (1-3).
/// </summary>
private static SortInventory WithFoci()
{
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Main.Name = "Main pack";
inv.Main.Capacity = 102;
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusB, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
inv.Packs[0].Items.Add(It(500, "Salvaged Iron", ObjectClasses.Salvage));
inv.Packs[1].Items.Add(It(501, "Black Opal", ObjectClasses.Gem));
inv.Packs[2].Items.Add(It(502, "Lead Scarab", ObjectClasses.SpellComponent));
return inv;
}
private static void ClassifyComponents()
{
// ItemType SpellComponents (0x1000) on ACE: the scarabs (Lead 691 .. Platinum 8897, Mana
// Scarab 37155) and Prismatic Taper (20631, weenie type SpellComponent) all have 4096.
foreach (string name in new[] { "Lead Scarab", "Platinum Scarab", "Mana Scarab", "Dark Scarab", "Prismatic Taper", "Red Taper", "Hyssop", "Ink of Formation" })
{
Eq(InventoryReader.ClassifyFrom(0x00001000, 0, name, out bool certain), ObjectClasses.SpellComponent, name);
Check(certain, name + ": certain");
// An item's ordinary bitfield bits (stuck, attackable) don't change it.
Eq(InventoryReader.ClassifyFrom(0x00001000, 0x00000014, name, out _), ObjectClasses.SpellComponent, name + " with bitfield bits");
}
var comps = SortRule.ForClass(ObjectClasses.SpellComponent, 1);
Check(SortRules.Matches(comps, It(1, "Platinum Scarab", InventoryReader.ClassifyFrom(0x1000, 0, "Platinum Scarab", out _))), "a component rule takes scarabs");
Check(SortRules.Matches(comps, It(2, "Prismatic Taper", InventoryReader.ClassifyFrom(0x1000, 0, "Prismatic Taper", out _))), "and tapers");
}
private static void ResolveById()
{
SortInventory inv = Inv(3);
var gem = SortRule.ForClass(ObjectClasses.Gem, 1);
gem.PackId = 0x40000003;
Eq(SortRules.Resolve(gem, inv, out bool fell), 3, "the pack its id names, not its number");
Check(!fell, "not a fallback");
inv.Main.Items.Add(It(10, "Black Opal", ObjectClasses.Gem));
var p = new SortPlanner();
List<SortMove> m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003 && m[0].DestIndex == 3, "moved to the pack with its id");
Eq(p.View.Issues.Count, 0, "no warning");
// A new pack shows up ahead of it in the list: the rule follows its pack.
inv.Packs.Insert(0, new SortPack { Id = 0x40000009, Name = "New", Capacity = 24 });
Eq(SortRules.Resolve(gem, inv, out _), 4, "its pack is now 4th: still the one used");
m = p.Plan(inv, new List<SortRule> { gem }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].Dest.Id == 0x40000003, "still moved to the same pack");
Check(PackFix.Sync(new List<SortRule> { gem }, inv) && gem.Pack == 4, "its number follows (for the window and the fallback)");
Check(!PackFix.Sync(new List<SortRule> { gem }, inv), "no change the second time");
// Already in its pack: Tidy leaves it there.
inv.Main.Items.Clear();
inv.Packs[3].Items.Add(It(11, "Black Opal", ObjectClasses.Gem));
Eq(p.Plan(inv, new List<SortRule> { gem }, SortScope.All, true, 0, 0).Count, 0, "in its pack: no move");
// Its pack isn't carried: the number decides, and the window says so.
SortInventory inv2 = Inv(3);
inv2.Main.Items.Add(It(12, "Black Opal", ObjectClasses.Gem));
var gone = SortRule.ForClass(ObjectClasses.Gem, 2);
gone.PackId = 0x4000FFFF;
gone.PackNote = "Sack - Gems";
Eq(SortRules.Resolve(gone, inv2, out fell), 2, "not carried: its number");
Check(fell, "a fallback");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 1 && m[0].DestIndex == 2, "moved by number");
Check(p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 2 && p.View.Missing.Count == 0, "reported as a fallback, not missing");
// Not carried and no such number: nowhere.
gone.Pack = 5;
Eq(SortRules.Resolve(gone, inv2, out _), 0, "nowhere");
m = p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Check(m.Count == 0 && p.View.Missing.Contains(5) && p.View.Issues.Count == 1 && p.View.Issues[0].UsedPack == 0, "no move, reported missing");
Eq(p.View.Waiting, 1, "the item waits");
// A rule with no id is the number, as before; one that is off isn't reported.
Eq(SortRules.Resolve(SortRule.ForClass(ObjectClasses.Gem, 3), inv2, out fell), 3, "no id: the number");
Check(!fell, "no id: not a fallback");
gone.On = false;
p.Plan(inv2, new List<SortRule> { gone }, SortScope.Main, true, 0, 0);
Eq(p.View.Issues.Count, 0, "a rule that is off isn't reported");
}
private static List<SortRule> LuaRules() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 1), // a focus
SortRule.ForClass(ObjectClasses.Salvage, 2), // pack A
SortRule.ForClass(ObjectClasses.Gem, 3), // a focus
SortRule.ForClass(ObjectClasses.Key, 4), // pack B
SortRule.ForClass(ObjectClasses.HealingKit, 5), // pack C
SortRule.ForClass(ObjectClasses.TradeNote, 6), // nothing
};
private static void PackFixImported()
{
SortInventory inv = WithFoci();
List<SortRule> rules = LuaRules();
List<string> lines = PackFix.Apply(rules, inv, imported: true, LuaRules(), out int changed);
Eq(changed, 3, "three rules pointed at a pack");
Eq(lines.Count, 6, "a line for every rule");
Check(rules[0].PackId == 0 && rules[0].Pack == 1 && lines[0].Contains("a focus") && lines[0].Contains("left as pack 1"), "Lua pack 1 was a focus: left, and said so");
Check(rules[1].PackId == 0x40000001 && rules[1].Pack == 1, "Lua pack 2 = pack A = RynthSort's pack 1");
Check(lines[1].Contains("the Lua script's pack 2 -> pack 1") && lines[1].Contains("Pack - Salvage") && lines[1].Contains("0x40000001"), $"logged ({lines[1]})");
Check(rules[2].PackId == 0 && rules[2].Pack == 3 && lines[2].Contains("a focus"), "Lua pack 3 was a focus");
Check(rules[3].PackId == 0x40000002 && rules[3].Pack == 2, "Lua pack 4 = pack B = 2");
Check(rules[4].PackId == 0x40000003 && rules[4].Pack == 3 && rules[4].PackNote == "Pack - Components", "Lua pack 5 = pack C = 3, remembered with its contents");
Check(rules[5].PackId == 0 && rules[5].Pack == 6 && lines[5].Contains("doesn't exist") && lines[5].Contains("3 packs and 2 foci"), $"Lua pack 6 doesn't exist ({lines[5]})");
// Every rule with an id now: a second run changes nothing.
List<string> again = PackFix.Apply(rules, inv, true, LuaRules(), out int changed2);
Eq(changed2, 0, "rules with ids are skipped");
Eq(again.Count, 3, "only the three still without one are looked at");
// The Lua file unreadable (null): every rule is taken as the Lua script's.
List<SortRule> r2 = LuaRules();
PackFix.Apply(r2, inv, true, null, out int c3);
Check(c3 == 3 && r2[3].PackId == 0x40000002, "no Lua file to compare with: all as imported");
// No foci: Lua numbers and RynthSort's agree; the fix only adds the ids.
SortInventory plain = Inv(3);
foreach (SortPack pk in plain.Packs) plain.Slots.Add(new SortSlot(pk.Id, 24));
List<SortRule> r3 = SortRules.Defaults();
PackFix.Apply(r3, plain, true, SortRules.Defaults(), out int c4);
Check(c4 == 3 && r3[0].PackId == 0x40000001 && r3[0].Pack == 1 && r3[2].PackId == 0x40000003 && r3[2].Pack == 3, "no foci: same numbers, ids added");
// Rules RynthSort saved (not imported): each keeps its number and takes that pack's id.
List<SortRule> own = SortRules.Defaults();
List<string> ownLines = PackFix.Apply(own, inv, imported: false, null, out int c5);
Check(c5 == 3 && own[0].PackId == 0x40000001 && own[1].PackId == 0x40000002 && own[2].PackId == 0x40000003, "RynthSort's numbers count real packs: pinned as they are");
Check(ownLines[0].Contains("pack 1 kept"), $"logged ({ownLines[0]})");
Check(PackFix.Ready(inv), "every capacity read: ready");
inv.Slots[2] = new SortSlot(FocusB, -1);
Check(!PackFix.Ready(inv), "a capacity not readable yet: not ready (could be a pack)");
}
// Drakkon's rules as RynthSort's file had them on 2026-10-11 (imported, then edited in the
// window), against his Lua script's file (2026-10-07): only rules 5 and 6 are still the Lua
// script's (keys 3, kits 4); the rest were picked in RynthSort's window, in its numbers.
private static List<SortRule> DrakkonNow() => new()
{
SortRule.ForClass(ObjectClasses.SpellComponent, 4),
SortRule.ForClass(ObjectClasses.Salvage, 1),
SortRule.ForClass(ObjectClasses.Gem, 4),
SortRule.ForClass(ObjectClasses.ManaStone, 4),
SortRule.ForClass(ObjectClasses.Key, 3),
SortRule.ForClass(ObjectClasses.HealingKit, 4),
SortRule.ForClass(ObjectClasses.TradeNote, 4),
SortRule.ForName("Ink of", 2),
SortRule.ForName("Prismatic Taper", 4),
};
private static void PackFixDrakkon()
{
SortStore st = TempStore("drakkon");
string lua = st.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
var d = new CharacterSortData { Rules = DrakkonNow(), ImportedFrom = lua };
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved like the old file");
// The old file had no packsFixed and version 1.
string own = st.PathFor("DreamWeave", "Drakkon");
File.WriteAllText(own, File.ReadAllText(own).Replace("\"packsFixed\": false", "\"x\": 0").Replace("\"version\": 3", "\"version\": 1"));
CharacterSortData loaded = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && !loaded.PacksFixed && loaded.LuaRules != null && loaded.LuaRules.Count == 6, "imported, not fixed: the Lua file's rules read to compare with");
// A layout with one focus: slot 1 pack A, slot 2 a focus, slot 3 pack B, slot 4 pack C.
var inv = new SortInventory();
inv.Main.Id = Me;
inv.Slots.Add(new SortSlot(0x40000001, 24));
inv.Slots.Add(new SortSlot(FocusA, 0));
inv.Slots.Add(new SortSlot(0x40000002, 24));
inv.Slots.Add(new SortSlot(0x40000003, 24));
foreach (SortSlot s in inv.Slots)
if (s.IsPack) inv.Packs.Add(new SortPack { Id = s.Id, Name = "Pack", Capacity = 24 });
List<SortRule> r = loaded.Rules;
List<string> lines = PackFix.Apply(r, inv, true, loaded.LuaRules, out int changed);
Check(r[4].PackId == 0x40000002 && r[4].Pack == 2, "keys: the Lua script's pack 3 (after the focus) -> pack 2");
Check(r[5].PackId == 0x40000003 && r[5].Pack == 3, "kits: the Lua script's pack 4 -> pack 3");
Check(r[1].PackId == 0x40000001 && r[1].Pack == 1, "salvage (picked in RynthSort): pack 1 kept");
Check(r[7].PackId == 0x40000002 && r[7].Pack == 2, "Ink of (picked in RynthSort): pack 2 kept");
Check(r[0].PackId == 0 && r[0].Pack == 4 && lines[0].Contains("which you don't have"), "components to RynthSort's pack 4: there are only 3, left (and said)");
Check(r[8].PackId == 0 && r[8].Pack == 4, "Prismatic Taper to pack 4: the same");
Eq(changed, 4, "four rules tied to their packs");
Eq(lines.Count, 9, "a line per rule");
}
private static void PackFixLoop()
{
var w = new FakeWorld { Inv = WithFoci() };
w.Inv.Main.Items.Add(It(10, "Platinum Scarab", ObjectClasses.SpellComponent));
w.Inv.Main.Items.Add(It(11, "Healing Kit", ObjectClasses.HealingKit));
SortController c = Controller();
c.Data.Rules = LuaRules();
c.Data.ImportedFrom = "lua.json";
c.Data.LuaRules = LuaRules();
List<string>? fixLines = null;
int fixChanged = -1;
c.PacksFixed = (l, n) => { fixLines = l; fixChanged = n; };
Ticks(c, w, 0, SortController.FixSettleMs - 100);
Eq(w.Sent.Count, 0, "imported rules not fixed yet: nothing moves");
Eq(c.Status, "reading your packs", "status says why");
Check(!c.Data.PacksFixed && fixLines == null, "not before the packs have read the same for a while");
Ticks(c, w, SortController.FixSettleMs - 100 + 16, SortController.FixSettleMs + 1500);
Check(c.Data.PacksFixed && c.Data.LuaRules == null, "fixed once settled");
Check(fixLines != null && fixLines.Count == 6 && fixChanged == 3, "the plugin hears it (to log and save)");
Check(c.Log.Any(x => x.Contains("Imported pack numbers fixed: 3 of 6")), "noted in the window");
Check(w.Sent.Any(m => m.Item.Id == 11 && m.Dest.Id == 0x40000003), "kits (the Lua script's pack 5) go to pack C");
// Components named the Lua script's pack 1, a focus: left as it was, "pack 1", which is
// RynthSort's first real pack (the log line says so; Tom picks the right one).
Check(w.Sent.Any(m => m.Item.Id == 10 && m.Dest.Id == 0x40000001), "a rule left as it was keeps its number");
Check(c.Data.Rules[0].PackId == 0, "and has no id until one is picked");
}
private static void PackLabels()
{
var inv = new SortInventory();
inv.Main.Id = Me;
for (int i = 1; i <= 3; i++) inv.Packs.Add(new SortPack { Id = 0x40000000u + (uint)i, Name = "Pack", Capacity = 24 });
for (uint i = 0; i < 10; i++) inv.Packs[0].Items.Add(It(100 + i, "Salvaged Iron", ObjectClasses.Salvage));
for (uint i = 0; i < 5; i++) inv.Packs[0].Items.Add(It(200 + i, "Black Opal", ObjectClasses.Gem));
inv.Packs[0].Items.Add(It(300, "Legendary Key", ObjectClasses.Key));
inv.Packs[0].Items.Add(It(301, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(400, "Lead Scarab", ObjectClasses.SpellComponent));
inv.Packs[1].Items.Add(It(401, "Pyreal Mote", ObjectClasses.Misc));
inv.Packs[1].Items.Add(It(402, "Pyreal Mote", ObjectClasses.Misc));
Eq(inv.Packs[0].Summary(), "Salvage, Gems, Keys", "the three commonest kinds");
Eq(inv.Packs[1].Summary(), "Pyreal Mote, Components", "misc items by name");
Eq(inv.Packs[2].Summary(), "empty", "empty");
var p = new SortPlanner();
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
List<string> choices = SortPanel.PackChoices(p.View, 1);
Eq(choices[0], "Pack 1: Pack (17/24) - Salvage, Gems, Keys", "picker label: number, name, room, contents");
Eq(choices[1], "Pack 2: Pack (3/24) - Pyreal Mote, Components", "bags with one name told apart by contents");
Eq(choices[2], "Pack 3: Pack (0/24) - empty", "an empty pack");
Eq(choices[3], "Pack 4 (none)", "then numbers you don't have");
// Picking stores the id; the row shows the pack it resolves to.
var rule = SortRule.ForClass(ObjectClasses.Gem, 1);
SortPanel.SetPack(rule, p.View, 2);
Check(rule.Pack == 2 && rule.PackId == 0x40000002 && rule.PackNote == "Pack - Pyreal Mote, Components", "picked: number, id and note");
Eq(SortPanel.ShownPack(p.View, rule), 2, "the rule is listed under pack 2");
SortPanel.SetPack(rule, p.View, 6);
Check(rule.Pack == 6 && rule.PackId == 0 && rule.PackNote == "", "a number you don't have: no id");
Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("list order") && !SortPanel.PackTooltip(p.View).Contains("top of the pack column"),
"pack order unknown: the tooltip doesn't claim screen order");
inv.PackOrderKnown = true;
p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0);
Check(SortPanel.PackTooltip(p.View).Contains("top of the pack column"), "pack order known: numbered from the top");
// Warnings sit with their pack: a rule that fell back to a number is listed (and warned
// about) under the pack it uses; rules whose pack isn't carried are grouped by that pack.
var gems = SortRule.ForClass(ObjectClasses.Gem, 7);
gems.PackId = 0x4000AAAA; gems.PackNote = "Sack - Gems";
var keys = SortRule.ForClass(ObjectClasses.Key, 7);
keys.PackId = 0x4000AAAA; keys.PackNote = "Sack - Gems";
var salvage = SortRule.ForClass(ObjectClasses.Salvage, 1);
salvage.PackId = 0x4000BBBB; salvage.PackNote = "Bag - Salvage";
var rules = new List<SortRule> { SortRule.ForClass(ObjectClasses.SpellComponent, 1), gems, keys, SortRule.ForClass(ObjectClasses.ManaStone, 6), salvage };
inv.PackOrderKnown = false;
p.Plan(inv, rules, SortScope.Main, true, 0, 0);
Eq(SortPanel.FallbackWarnings(p.View, 1).Count, 1, "one fallback warning, under pack 1");
Eq(SortPanel.FallbackWarnings(p.View, 1)[0], "Salvage: its pack (Bag - Salvage) isn't carried, so this one is used", "with what the pack was");
Eq(SortPanel.FallbackWarnings(p.View, 2).Count, 0, "none under pack 2");
Dictionary<int, List<SortRule>> groups = SortPanel.Group(rules, p.View);
Check(groups[1].Count == 2 && groups[1].Contains(salvage), "pack 1 lists its own rule and the fallback");
Check(groups[0].Count == 3 && groups[0].Contains(gems) && groups[0].Contains(keys), "rules for packs you don't have, together");
}
private static void StorePackIds()
{
SortStore st = TempStore("packids");
CharacterSortData d = st.Load("S", "A", out _);
Check(!d.PacksFixed, "new character: the defaults get tied to packs on the first read");
d.Rules[0].PackId = 0x8000ABCD;
d.Rules[0].PackNote = "Sack - Components";
d.PacksFixed = true;
st.Save("S", "A", d);
string json = File.ReadAllText(st.PathFor("S", "A"));
Check(json.Contains("\"version\": 3") && json.Contains("\"packId\": 2147527629") && json.Contains("\"packsFixed\": true"), "version 2 with pack ids");
Check(!json.Contains("\"packId\": 0"), "no packId written for rules without one");
CharacterSortData back = st.Load("S", "A", out string? problem);
Check(problem == null && back.PacksFixed && back.Rules[0].PackId == 0x8000ABCD && back.Rules[0].PackNote == "Sack - Components" && back.Rules[1].PackId == 0, "read back");
Check(back.LuaRules == null, "not imported: nothing to compare with");
// A version 1 file: rules by number, not fixed.
File.WriteAllText(st.PathFor("S", "A"), "{\"version\":1,\"rules\":[{\"kind\":\"class\",\"class\":11,\"pack\":3}]}");
CharacterSortData v1 = st.Load("S", "A", out problem);
Check(problem == null && !v1.PacksFixed && v1.Rules[0].PackId == 0 && v1.Rules[0].Pack == 3, "version 1 loads: number only, fix pending");
File.WriteAllText(st.PathFor("S", "A"), "{\"rules\":[{\"pack\":3,\"packId\":-5},{\"pack\":2,\"packId\":3.5},{\"pack\":1,\"packId\":1073741825.0}]}");
CharacterSortData odd = st.Load("S", "A", out _);
Check(odd.Rules[0].PackId == 0 && odd.Rules[1].PackId == 0 && odd.Rules[2].PackId == 0x40000001, "odd ids read as none; a whole double is fine");
// A fresh import: the Lua rules kept to compare with, not fixed.
SortStore imp = TempStore("packids-import");
string lua = imp.LuaPathFor("DreamWeave", "Drakkon");
Directory.CreateDirectory(Path.GetDirectoryName(lua)!);
File.WriteAllText(lua, LuaFile);
CharacterSortData fresh = imp.Load("DreamWeave", "Drakkon", out _);
Check(!fresh.PacksFixed && fresh.LuaRules != null && fresh.LuaRules.Count == 6 && !ReferenceEquals(fresh.LuaRules[0], fresh.Rules[0]), "fresh import: Lua rules copied, fix pending");
// Saved with a backup: the old file kept beside it.
imp.Save("DreamWeave", "Drakkon", fresh);
string before = File.ReadAllText(imp.PathFor("DreamWeave", "Drakkon"));
fresh.PacksFixed = true;
Check(imp.Save("DreamWeave", "Drakkon", fresh, backup: true) == null, "saved with a backup");
string bak = imp.PathFor("DreamWeave", "Drakkon") + ".bak";
Check(File.Exists(bak) && File.ReadAllText(bak) == before, ".bak holds the file as it was");
CharacterSortData fixedNow = imp.Load("DreamWeave", "Drakkon", out _);
Check(fixedNow.PacksFixed && fixedNow.LuaRules == null, "once fixed, the Lua file isn't read again");
}
}
}

View file

@ -47,6 +47,12 @@ namespace RynthSort.Tests
{
Run("rules: class and name matching, first match wins", RuleMatching);
Run("classify: item classes as RynthLua sees them", Classify);
Run("classify: scarabs, tapers and other spell components", ClassifyComponents);
Run("rules: a rule's pack by id, else its number", ResolveById);
Run("pack fix: imported Lua numbers (foci counted)", PackFixImported);
Run("pack fix: Drakkon's rules (edited after the import)", PackFixDrakkon);
Run("pack fix: in the loop (held until the packs settle)", PackFixLoop);
Run("window: pack labels and warnings", PackLabels);
Run("plan: settle time, force", PlanSettle);
Run("plan: pack choice (full pack, stacks, capacity)", PlanPackChoice);
Run("plan: worn, packs, foci and blocked items never move", PlanNeverMoves);
@ -67,9 +73,19 @@ namespace RynthSort.Tests
Run("store: save and load", StoreRoundTrip);
Run("store: Lua script import", StoreLuaImport);
Run("store: odd files", StoreOddFiles);
Run("store: pack ids, the fix flag and the backup", StorePackIds);
Run("lua autostart warning", LuaAutostart);
Run("window: display lists parse in the engine", WindowParses);
Run("window: a bar button of its own", WindowBarButton);
Run("window: rule editing through events", WindowEvents);
Run("rules: several classes and names in one rule", MultiRules);
Run("store: old rules migrate to version 3", RuleMigration);
Run("order: inside a pack (A-Z, fewest moves, every order of up to 7)", InPackOrder);
Run("order: slot orders and the pack column", SlotOrders);
Run("plan: stacks and order inside packs", PlanInPack);
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
}
finally
{
@ -140,9 +156,11 @@ namespace RynthSort.Tests
Check(!SortRules.Matches(off, gem), "a rule that is off matches nothing");
var rules = new List<SortRule> { SortRule.ForName("taper", 5), SortRule.ForClass(ObjectClasses.SpellComponent, 1) };
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "first match wins (name rule above the class rule)");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "a name match beats a class match");
(rules[0], rules[1]) = (rules[1], rules[0]);
Eq(SortRules.RuleFor(rules, comp)?.Pack, 1, "reordered: the class rule wins");
Eq(SortRules.RuleFor(rules, comp)?.Pack, 5, "whatever the order");
var twoClass = new List<SortRule> { SortRule.ForClass(ObjectClasses.Gem, 2), SortRule.ForClass(ObjectClasses.Gem, 4) };
Eq(SortRules.RuleFor(twoClass, gem)?.Pack, 2, "two class matches: the rule saved first");
Check(SortRules.RuleFor(Defaults, misc) == null, "no rule wants misc");
Eq(SortRules.RuleFor(Defaults, salvage)?.Pack, 2, "default: salvage to pack 2");
Eq(SortRules.RuleFor(Defaults, gem)?.Pack, 3, "default: gems to pack 3");
@ -411,6 +429,13 @@ namespace RynthSort.Tests
Check(w.Update(0x7000_0002, 7, 20_000), "the next corpse");
Check(w.Update(0, 0, 20_500), "closed: 1.5 s more (the next corpse is a moment away)");
Check(!w.Update(0, 0, 21_600), "then clear");
// An unreadable count (-1) between real reads is not a change (2026-10-11: paused for ever).
var f = new LootWatch();
Check(f.Update(0x7000_0003, 6, 30_000), "a corpse opened");
for (long t = 30_500; t < 40_000; t += 500)
f.Update(0x7000_0003, t % 1000 == 0 ? 6 : -1, t);
Check(!f.Update(0x7000_0003, 6, 40_000), "a flickering unreadable count doesn't keep it 'looting'");
}
private static void StatusJsonFallback()
@ -466,14 +491,17 @@ namespace RynthSort.Tests
public GateInputs Gate;
public readonly List<SortMove> Sent = new();
public bool EngineAccepts = true;
/// <summary>What the pretend engine can do (none: as an engine before API v80 without merges).</summary>
public SortAbilities Can;
/// <summary>"land" moves the item at once; "refuse" answers with InventoryServerSaveFailed; "busy" with You're too busy; "silent" never answers.</summary>
public string Server = "land";
public int ErrorSeq = 3;
private readonly Dictionary<uint, uint> _where = new();
private readonly HashSet<uint> _gone = new();
public SortInventory? ReadInventory() => Inv;
public GateInputs ReadGate(bool sortInCombat, long nowMs) { GateInputs g = Gate; g.SortInCombat = sortInCombat; return g; }
public int ErrorSeqNow() => ErrorSeq;
public SortAbilities Abilities => Can;
public bool SendMove(in SortMove move)
{
@ -482,12 +510,7 @@ namespace RynthSort.Tests
switch (Server)
{
case "land":
uint id = move.Item.Id;
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main)) p.Items.RemoveAll(i => i.Id == id);
uint destId = move.Dest.Id;
SortPack dest = destId == Inv.Main.Id ? Inv.Main : Inv.Packs.First(p => p.Id == destId);
dest.Items.Add(move.Item);
_where[id] = dest.Id;
if (ServerApply(Inv, move)) _gone.Add(move.Item.Id);
break;
case "refuse":
ErrorSeq++;
@ -504,15 +527,58 @@ namespace RynthSort.Tests
private uint _refused;
private bool _busy;
public MoveObservation Observe(uint itemId)
public MoveObservation Observe(in SortMove move)
{
var o = new MoveObservation { Exists = true, Container = _where.TryGetValue(itemId, out uint c) ? c : Me, ErrorSeq = ErrorSeq };
uint itemId = move.Item.Id;
var o = new MoveObservation { Exists = !_gone.Contains(itemId), Container = Me, ErrorSeq = ErrorSeq, Slot = -1, Stack = move.Item.Stack };
foreach (SortPack p in Inv.Packs.Prepend(Inv.Main))
{
int at = p.Items.FindIndex(i => i.Id == itemId);
if (at < 0) continue;
o.Container = p.Id;
o.Slot = at;
o.Stack = p.Items[at].Stack;
}
if (_refused == itemId) { o.ErrorEventType = 0xA0; o.ErrorObject = itemId; }
if (_busy) { o.Error = 0x1D; o.ErrorEventType = 0x28A; }
return o;
}
}
/// <summary>
/// What ACE does with a move: a merge adds what fits to the other stack (the rest stays; a
/// stack emptied is gone: true); a move takes the item out and puts it in at its placement
/// (clamped), or at the end when it names none. Items keep their objects (the planner's
/// copies of stack sizes see the change, as a fresh read would).
/// </summary>
private static bool ServerApply(SortInventory inv, SortMove move)
{
uint id = move.Item.Id;
uint destId = move.Dest.Id;
SortPack? from = inv.Packs.Prepend(inv.Main).FirstOrDefault(p => p.Items.Any(i => i.Id == id));
if (from == null) return false;
SortItem item = from.Items.First(i => i.Id == id);
SortPack dest = destId == inv.Main.Id ? inv.Main : inv.Packs.First(p => p.Id == destId);
uint mergeInto = move.MergeInto;
if (mergeInto != 0)
{
SortItem? into = dest.Items.FirstOrDefault(i => i.Id == mergeInto);
if (into == null) return false;
int max = into.MaxStack > 1 ? into.MaxStack : item.MaxStack;
int amount = Math.Min(item.Stack, max - into.Stack);
if (amount <= 0) return false;
into.Stack += amount;
item.Stack -= amount;
if (item.Stack > 0) return false;
from.Items.Remove(item);
return true;
}
from.Items.Remove(item);
int at = move.Placement >= 0 ? Math.Clamp(move.Placement, 0, dest.Items.Count) : dest.Items.Count;
dest.Items.Insert(at, item);
return false;
}
private static SortController Controller(bool auto = true, int gapMs = 300, int settleSec = 0)
{
var c = new SortController();
@ -695,7 +761,7 @@ namespace RynthSort.Tests
Ticks(c, w, 0, 600);
Eq(w.Sent.Count, 2, "tidy moved both quickly (job gap, not the 3 s auto gap)");
Eq(w.Inv.Packs[1].Items.Count, 2, "both in pack 2");
Check(c.Job == null && c.Log[0] == "Packs tidied", "job ends with a note");
Check(c.Job == null && c.Log[0] == "Packs sorted", "job ends with a note");
// Unpack turns auto-sort off (and asks for a save) so nothing moves back.
var w2 = new FakeWorld();
@ -750,21 +816,23 @@ namespace RynthSort.Tests
{
SortStore st = TempStore("roundtrip");
CharacterSortData d = st.Load("DreamWeave", "Drakkon", out string? problem);
Check(problem == null && d.Rules.Count == 5 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(problem == null && d.Rules.Count == 3 && d.ImportedFrom.Length == 0, "no file: the defaults");
Check(!d.Settings.WindowOpen, "no file: the window starts closed (the bar button opens it)");
d.Rules.Add(SortRule.ForName("Pyreal \"Mote\"", 6));
d.Rules[0].On = false;
d.Settings.Auto = false;
d.Settings.SettleSec = 12;
d.Settings.GapMs = 900;
d.Settings.SortInCombat = true;
d.Settings.WindowOpen = false;
d.Settings.WindowOpen = true;
Check(st.Save("DreamWeave", "Drakkon", d) == null, "saved");
Check(File.Exists(Path.Combine(st.Root, "characters", "DreamWeave_Drakkon.json")), "file named server_character");
CharacterSortData back = st.Load("DreamWeave", "Drakkon", out problem);
Check(problem == null, "read back");
Eq(back.Rules.Count, 6, "rules");
Check(!back.Rules[0].On && back.Rules[5].Kind == RuleKind.Name && back.Rules[5].Text == "Pyreal \"Mote\"" && back.Rules[5].Pack == 6, "rule fields");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && !back.Settings.WindowOpen, "settings");
Eq(back.Rules.Count, 4, "rules");
Check(!back.Rules[0].On && back.Rules[3].Classes.Count == 0 && back.Rules[3].Names.Count == 1 && back.Rules[3].Names[0] == "Pyreal \"Mote\"" && back.Rules[3].Pack == 6, "rule fields");
Check(back.Rules[2].SameAs(SortRules.Defaults()[2]), "a rule with three classes comes back whole");
Check(!back.Settings.Auto && back.Settings.SettleSec == 12 && back.Settings.GapMs == 900 && back.Settings.SortInCombat && back.Settings.WindowOpen, "settings");
Eq(SortStore.FileStem("Dream:Weave", "Con"), "Dream_Weave_Con", "unsafe characters replaced like RynthLua");
Eq(SortStore.SafeFileName("CON"), "_CON", "reserved names guarded");
}
@ -782,9 +850,10 @@ namespace RynthSort.Tests
Check(problem == null, "Lua file read");
Eq(d.ImportedFrom, lua, "marked as imported");
Eq(d.Rules.Count, 6, "six rules");
Check(d.Rules[5].Kind == RuleKind.Class && d.Rules[5].Class == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4");
Check(d.Rules[5].Names.Count == 0 && d.Rules[5].Classes.Count == 1 && d.Rules[5].Classes[0] == ObjectClasses.HealingKit && d.Rules[5].Pack == 4, "healing kits to pack 4 (one class)");
Check(!d.Settings.Auto && d.Settings.SettleSec == 5 && d.Settings.GapMs == 600, "settings taken over");
Check(d.Settings.WindowOpen && !d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(!d.Settings.SortInCombat, "plugin-only settings at their defaults");
Check(d.Settings.WindowOpen, "taken over from the Lua script: the window opens once to show the rules");
// Once RynthSort has its own file, the Lua file is no longer read (and is left alone).
d.Rules.RemoveAt(0);
@ -804,7 +873,7 @@ namespace RynthSort.Tests
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
File.WriteAllText(own, "{ not json");
CharacterSortData d = st.Load("S", "A", out string? problem);
Check(problem != null && d.Rules.Count == 5, "broken file: defaults, problem reported");
Check(problem != null && d.Rules.Count == 3, "broken file: defaults, problem reported");
// The Lua script saved an empty rule list as {}; numbers as doubles; out-of-range values clamped.
File.WriteAllText(own, "{\"rules\":{},\"settings\":{\"auto\":true,\"settleSec\":99.0,\"gapMs\":5,\"x\":1}}");
@ -815,9 +884,9 @@ namespace RynthSort.Tests
File.WriteAllText(own, "{\"rules\":[{\"kind\":\"name\",\"text\":\"Key\",\"pack\":2.0},{\"class\":11,\"pack\":-4},7,{\"on\":false}]}");
d = st.Load("S", "A", out _);
Eq(d.Rules.Count, 3, "a non-object entry is skipped");
Check(d.Rules[0].Kind == RuleKind.Name && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Check(d.Rules[0].Names.Count == 1 && d.Rules[0].Names[0] == "Key" && d.Rules[0].Classes.Count == 0 && d.Rules[0].Pack == 2 && d.Rules[0].On, "missing 'on' = on; 2.0 = 2");
Eq(d.Rules[1].Pack, 1, "pack clamped to 1");
Check(!d.Rules[2].On && d.Rules[2].Class == ObjectClasses.SpellComponent, "defaults for missing fields");
Check(!d.Rules[2].On && d.Rules[2].Classes.Count == 1 && d.Rules[2].Classes[0] == ObjectClasses.SpellComponent, "defaults for missing fields");
}
private static void LuaAutostart()
@ -869,6 +938,32 @@ namespace RynthSort.Tests
maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max();
}
private static unsafe List<ParsedWindow> ParseWindows(UiHost host)
{
int n = Write(host);
byte[] buf = SubmitBuffer(host);
List<ParsedWindow> windows;
fixed (byte* p = buf) DisplayListParser.Parse(p, n, 4000f, out _, out windows, out _);
return windows;
}
private static void WindowBarButton()
{
Eq(UiFormat.FlagBarButton, WindowFlags.BarButton, "the plugin's bit is the engine's");
var (_, panel, host, w) = Window();
Draw(w, panel);
List<ParsedWindow> windows = ParseWindows(host);
Check(windows.Count == 1 && windows[0].Title == "RynthSort", "one window, titled RynthSort (the button's tooltip)");
uint f = windows.Count == 1 ? windows[0].Flags : 0;
Check((f & WindowFlags.ShowInBar) != 0 && (f & WindowFlags.BarButton) != 0, "ShowInBar + BarButton survive the engine's parse");
w.MarkSubmitted(true);
w.ShowInBar = false;
windows = ParseWindows(host);
f = windows.Count == 1 ? windows[0].Flags : ~0u;
Check((f & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == 0, "not in the bar: no button either");
}
private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload)
{
var e = new byte[16 + payload.Length];
@ -890,37 +985,65 @@ namespace RynthSort.Tests
ParseAll(host, "default rules", out int ops);
Check(ops > 10 && ops < 1500, $"ops in range ({ops})");
string body = BodyText(w);
Check(body.Contains("Auto-sort") && body.Contains("Sort main pack") && body.Contains("Tidy all packs")
&& body.Contains("Empty side packs") && body.Contains("Clean packs"), "buttons and toggle");
Check(body.Contains("Rules (first match wins)") && body.Contains("1. Spell Component -> pack 1 (Pack 1)"), "rule list");
Check(body.Contains("Auto-sort") && body.Contains("Sort now") && body.Contains("Clean packs") && body.Contains("Empty side packs"), "buttons and toggle");
Check(body.Contains("Main pack (1/102)"), "the main pack's line");
Check(body.Contains("Pack 1: Pack 1 (24/24) - Junk 0, Junk 1, Junk 2"), "a section per pack, named with its room and contents");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Gem, Key, Mana Stone"), "a rule with three classes as one row under its pack");
Check(body.Contains("Pack 4: Pack 4 (0/24) - empty") && body.Contains("No rules send items here."), "a pack without rules says so");
Check(body.IndexOf("Pack 1: ", StringComparison.Ordinal) < body.IndexOf("Spell Component", StringComparison.Ordinal)
&& body.IndexOf("Spell Component", StringComparison.Ordinal) < body.IndexOf("Pack 2: ", StringComparison.Ordinal), "a rule sits under its pack");
Check(!body.Contains("Classes:"), "no editor until a rule is picked");
w.MarkSubmitted(true);
// A selected rule's editor (class, then name), the settings open, warnings and a log.
Apply(host, Event(1, 1, w.Hash, w.KeyOf("row.0"), Click));
// The gem rule's editor, the settings open, warnings and a log.
SortRule gemRule = c.Data.Rules[2];
Apply(host, Event(1, 1, w.Hash, w.KeyOf($"r{gemRule.Uid}.row"), Click));
Apply(host, Event(6, 2, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
c.Note("Prismatic Taper -> pack 1");
panel.Warnings = () => new[] { "The RynthSort Lua script is set to start too" };
Draw(w, panel);
ParseAll(host, "rule editor (class)", out _);
ParseAll(host, "rule editor", out _);
body = BodyText(w);
Check(body.Contains("Rule 1") && body.Contains("Mana Stone") && body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("Pack 7 (none)"), "editor with class and pack choices");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights"), "settings shown");
Check(body.Contains("Classes:") && body.Contains("Gem x") && body.Contains("Key x") && body.Contains("Mana Stone x"), "the rule's classes as chips");
Check(body.Contains("Add a class...") && body.Contains("Name has") && body.Contains("Remove rule"), "add a class, add a name, remove");
Check(body.Contains("Pack 3: Pack 3 (0/24) - empty") && body.Contains("Pack 7 (none)"), "the pack picker");
Check(body.Contains("Settle (s)") && body.Contains("Gap (ms)") && body.Contains("Sort during fights")
&& body.Contains("Put items in order inside packs") && body.Contains("Group by kind first"), "settings shown");
Check(body.Contains("plugin API 80"), "an engine that can't read orders: said in the settings");
Check(body.Contains("Lua script is set to start"), "warning shown");
w.MarkSubmitted(true);
c.Data.Rules[0].Kind = RuleKind.Name;
c.Data.Rules[0].Text = "Taper";
c.Data.Rules[0].Class = 999;
gemRule.AddName("Opal");
gemRule.AddName("a##b");
Draw(w, panel);
ParseAll(host, "rule editor (name)", out _);
Check(BodyText(w).Contains("Name has"), "name editor");
c.Data.Rules[0].Kind = RuleKind.Class;
ParseAll(host, "rule editor with names", out _);
body = BodyText(w);
Check(body.Contains("Names:") && body.Contains("\"Opal\" x"), "names as chips");
Check(body.Contains("Gem, Key, Mana Stone, name has \"a# #b\", name has \"Opal\""), "the row: classes, then names, A-Z (## shown apart)");
// A rule whose pack isn't carried: its own section, grouped by what the pack was.
var gone = SortRule.ForClass(ObjectClasses.Lockpick, 9);
gone.PackId = 0x4000AAAA;
gone.PackNote = "Sack - Gems";
c.Data.Rules.Add(gone);
var inv = Inv(4);
Fill(inv.Packs[0], 24, 1000);
inv.Packs[0].OrderKnown = true;
c.Planner.Plan(inv, c.Data.Rules, SortScope.All, true, 0, 0, PlanOptions.Full);
Draw(w, panel);
ParseAll(host, "rule editor (class the editor doesn't offer)", out _);
Check(BodyText(w).Contains("class 999"), "an unknown class stays shown");
ParseAll(host, "missing pack", out _);
body = BodyText(w);
Check(body.Contains("Rules for packs you don't have (1)") && body.Contains("A pack you don't have (it was Sack - Gems):") && body.Contains("Lockpick"), "missing-pack section");
Check(body.Contains("Pack 1: Pack 1 (24/24)") && body.Contains("in order"), "a pack in order says so");
// Two rules naming the same class for different packs: the losing pack says so.
c.Data.Rules.Add(SortRule.ForClass(ObjectClasses.Gem, 4));
Draw(w, panel);
ParseAll(host, "conflict", out _);
Check(BodyText(w).Contains("Gem: also in a rule for pack 3, which wins"), "conflict shown under the losing pack");
// Many rules still fit.
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.ForName("x" + i, 1 + i % 8));
for (int i = 0; i < SortStore.MaxRules; i++) c.Data.Rules.Add(SortRule.For(1 + i % 8, new[] { ObjectClasses.Armor, ObjectClasses.Food }, "x" + i, "y" + i));
Draw(w, panel);
ParseAll(host, "64+ rules", out int many);
Check(many < 1500, $"many rules fit ({many} ops)");
@ -932,64 +1055,107 @@ namespace RynthSort.Tests
Check(BodyText(w).Contains("Log in"), "logged-out text");
}
private static byte[] TextEvent(string text, bool submitted)
{
byte[] t = Encoding.UTF8.GetBytes(text);
var payload = new byte[3 + t.Length];
payload[0] = submitted ? (byte)1 : (byte)0;
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)t.Length);
t.CopyTo(payload, 3);
return payload;
}
private static void WindowEvents()
{
var (c, panel, host, w) = Window();
Draw(w, panel);
int rules = c.Data.Rules.Count;
uint seq = 0;
void Send(ushort type, string id, byte[] payload)
{
Apply(host, Event(type, ++seq, w.Hash, w.KeyOf(id), payload));
Draw(w, panel);
}
Apply(host, Event(1, 1, w.Hash, w.KeyOf("rule.add"), Click));
// "+ Add rule" in pack 4's section: a new, empty rule for pack 4, its editor open.
Send(1, "add.40000004", Click);
Eq(c.Data.Rules.Count, rules + 1, "Add rule");
Eq(panel.Selected, rules, "the new rule is selected");
Draw(w, panel);
SortRule r = panel.Selected!;
Check(r != null && r.IsEmpty && r.PackId == 0x40000004 && r.Pack == 4, "the new rule is selected, empty, for that pack");
Check(BodyText(w).Contains("(empty: add a class or a name)"), "an empty rule says what to do");
string k = "r" + r!.Uid;
Apply(host, Event(1, 2, w.Hash, w.KeyOf("rule.up"), Click));
Eq(panel.Selected, rules - 1, "Up moves the selection with the rule");
Draw(w, panel);
// Classes through the picker (its first line is "Add a class...").
Send(3, k + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Armor) + 1));
Check(r.Classes.Count == 1 && r.HasClass(ObjectClasses.Armor), "picker adds Armor");
int clothing = ObjectClasses.Choices.Where(x => x != ObjectClasses.Armor).ToList().IndexOf(ObjectClasses.Clothing) + 1;
Send(3, k + ".addclass", BitConverter.GetBytes(clothing));
Check(r.HasClass(ObjectClasses.Clothing) && r.Classes.Count == 2, "and Clothing (the picker leaves out what the rule has)");
Send(3, k + ".addclass", BitConverter.GetBytes(0));
Eq(r.Classes.Count, 2, "the picker's first line adds nothing");
// The new rule: make it a name rule for "opal" to pack 4.
Apply(host, Event(3, 3, w.Hash, w.KeyOf("rule.kind"), BitConverter.GetBytes(1)));
Draw(w, panel);
byte[] text = Encoding.UTF8.GetBytes("opal");
var payload = new byte[3 + text.Length];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)text.Length);
text.CopyTo(payload, 3);
Apply(host, Event(5, 4, w.Hash, w.KeyOf("rule.text"), payload));
Apply(host, Event(3, 5, w.Hash, w.KeyOf("rule.pack"), BitConverter.GetBytes(3)));
SortRule r = c.Data.Rules[rules - 1];
Check(r.Kind == RuleKind.Name && r.Text == "opal" && r.Pack == 4, "edited through the combo, text box and pack combo");
Draw(w, panel);
// Names: typed and Enter, or typed and Add.
Send(5, k + ".draft", TextEvent("Shield", true));
Check(r.Names.Count == 1 && r.HasName("Shield"), "Enter adds the name");
Send(5, k + ".draft", TextEvent("Buckler", false));
Eq(r.Names.Count, 1, "typing alone adds nothing");
Send(1, k + ".addname", Click);
Check(r.HasName("Buckler") && r.Names.Count == 2, "Add adds it");
Send(5, k + ".draft", TextEvent("shield", true));
Eq(r.Names.Count, 2, "the same name in another case isn't added twice");
Check(BodyText(w).Contains("Armor, Clothing, name has \"Buckler\", name has \"Shield\""), "the row lists them");
// Its checkbox turns it off.
Apply(host, Event(2, 6, w.Hash, w.KeyOf("on." + (rules - 1)), new byte[] { 0 }));
Check(!r.On, "checkbox turns the rule off");
Draw(w, panel);
// Chips take entries out.
Send(1, $"{k}.c{ObjectClasses.Clothing}", Click);
Check(!r.HasClass(ObjectClasses.Clothing) && r.HasClass(ObjectClasses.Armor), "a class chip removes its class");
Send(1, k + ".n0", Click);
Check(!r.HasName("Buckler") && r.HasName("Shield"), "a name chip removes its name (A-Z: Buckler first)");
Apply(host, Event(1, 7, w.Hash, w.KeyOf("rule.down"), Click));
Eq(c.Data.Rules.IndexOf(r), rules, "Down");
Draw(w, panel);
Apply(host, Event(1, 8, w.Hash, w.KeyOf("rule.remove"), Click));
Check(!c.Data.Rules.Contains(r) && c.Data.Rules.Count == rules, "Remove");
Draw(w, panel);
// Another pack through the picker.
Send(3, k + ".pack", BitConverter.GetBytes(1));
Check(r.Pack == 2 && r.PackId == 0x40000002 && r.PackNote.StartsWith("Pack 2 - "), $"moved to pack 2, kept by its id ({r.PackNote})");
string body = BodyText(w);
Check(body.IndexOf("Pack 2: ", StringComparison.Ordinal) < body.IndexOf("Armor, name has", StringComparison.Ordinal)
&& body.IndexOf("Armor, name has", StringComparison.Ordinal) < body.IndexOf("Pack 3: ", StringComparison.Ordinal), "now listed under pack 2");
// Class combo on rule 1.
Apply(host, Event(1, 9, w.Hash, w.KeyOf("row.0"), Click));
Draw(w, panel);
Apply(host, Event(3, 10, w.Hash, w.KeyOf("rule.class"), BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.HealingKit))));
Eq(c.Data.Rules[0].Class, ObjectClasses.HealingKit, "class combo");
// On and off.
Send(2, k + ".on", new byte[] { 0 });
Check(!r.On, "the box turns the rule off");
Send(2, k + ".on", new byte[] { 1 });
Check(r.On, "and on");
// Merge rules: a second rule for pack 3 joins the first.
Send(1, "add.40000003", Click);
SortRule second = panel.Selected!;
Send(3, "r" + second.Uid + ".addclass", BitConverter.GetBytes(ObjectClasses.ChoiceIndex(ObjectClasses.Lockpick) + 1));
Check(BodyText(w).Contains("Merge rules"), "two rules in a pack: Merge rules offered");
int before = c.Data.Rules.Count;
Send(1, "merge.40000003", Click);
Eq(c.Data.Rules.Count, before - 1, "two rules became one");
SortRule merged = c.Data.Rules.Single(x => x.PackId == 0x40000003 || x.Pack == 3);
Check(merged.HasClass(ObjectClasses.Gem) && merged.HasClass(ObjectClasses.Key) && merged.HasClass(ObjectClasses.ManaStone) && merged.HasClass(ObjectClasses.Lockpick),
"the merged rule has every class");
// Remove.
Send(1, k + ".row", Click);
Check(ReferenceEquals(panel.Selected, r), "picked again");
Send(1, k + ".remove", Click);
Check(!c.Data.Rules.Contains(r) && panel.Selected == null, "Remove");
// Settings and buttons.
Apply(host, Event(6, 11, w.Hash, w.KeyOf("settings"), new byte[] { 1 }));
Draw(w, panel);
Apply(host, Event(3, 12, w.Hash, w.KeyOf("settle"), BitConverter.GetBytes(12)));
Apply(host, Event(3, 13, w.Hash, w.KeyOf("gap"), BitConverter.GetBytes(50_000)));
Apply(host, Event(2, 14, w.Hash, w.KeyOf("combat"), new byte[] { 1 }));
Send(6, "settings", new byte[] { 1 });
Send(3, "settle", BitConverter.GetBytes(12));
Send(3, "gap", BitConverter.GetBytes(50_000));
Send(2, "combat", new byte[] { 1 });
Check(c.Data.Settings.SettleSec == 12 && c.Data.Settings.GapMs == SortSettings.GapMax && c.Data.Settings.SortInCombat, "sliders (clamped) and the fights box");
Apply(host, Event(2, 15, w.Hash, w.KeyOf("auto"), new byte[] { 0 }));
Send(2, "order", new byte[] { 0 });
Send(2, "orderkind", new byte[] { 1 });
Check(!c.Data.Settings.OrderInPacks && c.Data.Settings.OrderKindFirst, "the order boxes");
Send(2, "auto", new byte[] { 0 });
Check(!c.Data.Settings.Auto, "auto-sort box");
Apply(host, Event(1, 16, w.Hash, w.KeyOf("job.all"), Click));
Eq(c.Job, SortScope.All, "Tidy button");
Apply(host, Event(1, 17, w.Hash, w.KeyOf("job.unpack"), Click));
Send(1, "job.all", Click);
Eq(c.Job, SortScope.All, "Sort now button");
Send(1, "job.unpack", Click);
Check(c.Job == SortScope.Unpack && c.UnpackWhich == null, "Empty side packs button");
}
}

View file

@ -4,7 +4,12 @@
Offline checks for RynthSort: rule matching, pack choice (a full pack only takes an item that
joins a stack there), Tidy / Clean / Unpack planning, the "stay out of the way" gates (looting,
vendor, trade, busy, portal space and RynthAi's activity bits), one move at a time with the
gap and the back-off after refusals, the per-character file and the Lua script import, and that
gap and the back-off after refusals, the per-character file and the Lua script import, rules
tied to pack ids (and the one-time fix of the Lua script's pack numbers, which counted foci),
rules with several classes and names (and old files migrating to them), the order inside
packs (every order of up to 7 items, shuffled packs to 102), slot orders and the pack column,
stacks joined in place, that a fixed inventory runs out of moves (planner and loop),
the pack picker's labels, spell component classification, and that
the window's display list is accepted by the engine's own parser (RynthCore
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the sibling
RynthCore checkout). Nothing native is loaded: no AC, no ImGui context. Files go to a temp