diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
index fcfcd46..6aaa5a0 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
@@ -120,7 +120,7 @@ public partial class BuffManager
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
- OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
+ OffhandPutAway(bowId); // a shield: combat puts it back after (and it is buffed in the pack)
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs
new file mode 100644
index 0000000..a90c445
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.Shield.cs
@@ -0,0 +1,549 @@
+using System;
+using System.Collections.Generic;
+using RynthCore.PluginSdk;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// The shield's armor spells (2026-10-28). Impenetrability and the seven Banes are cast on the
+/// player, and ACE puts them on every worn piece of armor and a worn shield
+/// (WorldObject_Magic.TryCastItemEnchantment_WithRedirects). But buffing holds a wand, and ACE won't
+/// wield a caster beside a shield: the wand swap puts the shield into a pack first, so the
+/// self-cast never reached it. The shield now gets its own casts, aimed at it, after the armor's.
+///
+/// * Which shield: one in the Items list (the Shield action, or a shield filed as a weapon) that
+/// is in use: in the off hand, or put into a pack by buffing's own wand swap (combat puts it
+/// back). A listed shield that was in a pack before (not worn) is left alone, as armor in a
+/// pack is; an unlisted shield is never a target. No listed shield: nothing here runs.
+/// * Which spells: the armor's, Impenetrability and the Banes still in the buff list (the
+/// Protections and Banes ticks, or a buff profile), at the level the armor gets. Weapon
+/// enchantments never go on the shield. Buff the shield (LegacyUiSettings.BuffShield, on by
+/// default) turns it off.
+/// * When: on the armor's rules (Rebuff With, Also Refresh Under in a batch, Force Rebuff), on the
+/// shield's own timers, recorded from the "You cast X on <shield>" line.
+/// * Never at a shield being moved (its pack move or wield not settled, a swap under way).
+/// * A cast at the shield that gets no answer twice in a row, or that the server says can't be
+/// cast on it, stops shield buffing for ShieldParkTime; the armor is never held up by it.
+///
+public partial class BuffManager
+{
+ /// The shield's armor spells: keyed by (shield id, spell family), .
+ private readonly Dictionary _shieldSpellTimers = new();
+ internal static long ShieldKey(int shieldId, int family) => ((long)unchecked((uint)shieldId) << 32) | unchecked((uint)family);
+
+ // The shield the pending cast is aimed at. Means something only while _pendingSpellId is set:
+ // every other cast clears it when it is sent.
+ private int _pendingShieldId;
+ private bool PendingIsShield => _pendingSpellId != 0 && _pendingShieldId != 0;
+
+ // Families confirmed on the shield in this force/batch run, at their level (ClearRunFamilies).
+ private readonly Dictionary _shieldRunLevels = new();
+ // A family the server refused on the shield (no components, no mana): rested, the armor's not touched.
+ private readonly Dictionary _shieldFamilyRestUntil = new();
+ // Casts at the shield with no answer in a row; at ShieldNoShowsToPark the shield is parked.
+ private int _shieldNoShows;
+ private int _shieldParkedId;
+ private DateTime _shieldParkedUntil = DateTime.MinValue;
+ internal const int ShieldNoShowsToPark = 2;
+ internal static readonly TimeSpan ShieldParkTime = TimeSpan.FromMinutes(30);
+
+ // The off-hand item buffing's wand swap put into a pack (combat puts it back on), and when.
+ // Seen in the off hand again after StowedSightingGraceMs, it is forgotten: the next time it is
+ // in a pack, something else put it there.
+ private int _stowedShieldId;
+ private DateTime _stowedShieldAt = DateTime.MinValue;
+ private const double StowedSightingGraceMs = 10000;
+
+ // ShieldToBuff walks the inventory: its answer is kept ShieldReadMs (the arbiter asks every tick),
+ // and worked out again at once when the Items list or the cache changes. Tests set ShieldReadMs 0.
+ internal long ShieldReadMs = 1000;
+ private int _shieldChoice;
+ private string _shieldChoiceWhy = "";
+ private long _shieldChoiceAt = long.MinValue / 2;
+ private List? _shieldChoiceRules;
+ private int _shieldChoiceRuleCount;
+ private WorldObjectCache? _shieldChoiceCache;
+ private string _shieldChoiceLogged = "";
+
+ /// Impenetrability (Brogard's Defiance) and the Banes: the armor spells, which a shield takes too.
+ internal static bool IsArmorItemSpell(string name) =>
+ name.IndexOf("Impenetrability", StringComparison.OrdinalIgnoreCase) >= 0
+ || name.IndexOf("Brogard's Defiance", StringComparison.OrdinalIgnoreCase) >= 0
+ || name.IndexOf(" Bane", StringComparison.OrdinalIgnoreCase) >= 0
+ || name.StartsWith("Bane", StringComparison.OrdinalIgnoreCase);
+
+ ///
+ /// Buffing's wand swap put (the off hand) into a pack: combat puts it back
+ /// (OffhandStowed), and a shield there is still the one in use, so it is buffed in the pack.
+ ///
+ internal void OffhandPutAway(int id)
+ {
+ if (id != 0)
+ {
+ _stowedShieldId = id;
+ _stowedShieldAt = RynthClock.Now;
+ _shieldChoiceAt = long.MinValue / 2;
+ }
+ OffhandStowed?.Invoke(id);
+ }
+
+ /// The Items list's shields the cache knows, in list order.
+ private List ListedShields()
+ {
+ var found = new List();
+ var cache = _worldObjectCache;
+ if (cache == null) return found;
+ List rules;
+ try { rules = new List(_settings.ItemRules); }
+ catch { return found; } // the list edited mid-copy: next read
+ foreach (var r in rules)
+ {
+ if (r.Id == 0 || found.Contains(r.Id)) continue;
+ var wo = cache[r.Id];
+ if (wo == null) continue;
+ if (CombatManager.IsShieldItem(wo) || (WeaponList.IsShieldRule(r) && wo.ObjectClass == AcObjectClass.Armor))
+ found.Add(r.Id);
+ }
+ return found;
+ }
+
+ private bool InInventory(int id)
+ {
+ if (_worldObjectCache == null || id == 0) return false;
+ foreach (var wo in _worldObjectCache.GetDirectInventory())
+ if (wo.Id == id) return true;
+ return false;
+ }
+
+ ///
+ /// The listed shield to buff now (0 = none) and where it is: the one in the off hand, else the
+ /// one buffing put into a pack for the wand. reads it again now.
+ ///
+ internal int ShieldToBuff(out string where, bool fresh = false)
+ {
+ long now = KitClockMs();
+ var rules = _settings.ItemRules;
+ if (!fresh && ReferenceEquals(rules, _shieldChoiceRules) && rules.Count == _shieldChoiceRuleCount
+ && ReferenceEquals(_worldObjectCache, _shieldChoiceCache) && now >= _shieldChoiceAt && now - _shieldChoiceAt < ShieldReadMs)
+ {
+ where = _shieldChoiceWhy;
+ return _shieldChoice;
+ }
+ int id = FindShieldToBuff(out where, out bool anyListed);
+ _shieldChoice = id;
+ _shieldChoiceWhy = where;
+ _shieldChoiceAt = now;
+ _shieldChoiceRules = rules;
+ _shieldChoiceRuleCount = rules.Count;
+ _shieldChoiceCache = _worldObjectCache;
+ // One log line when the answer changes, only for a character with a shield listed.
+ string line = anyListed ? $"{id:X8}|{where}" : "";
+ if (line != _shieldChoiceLogged)
+ {
+ _shieldChoiceLogged = line;
+ if (anyListed)
+ _host.Log(id != 0
+ ? $"[Buff] shield: 0x{(uint)id:X8} '{ItemName(id)}' ({where}) takes the armor spells"
+ : $"[Buff] shield: none buffed ({where})");
+ }
+ return id;
+ }
+
+ private int FindShieldToBuff(out string where, out bool anyListed)
+ {
+ anyListed = false;
+ if (!_settings.BuffShield) { where = "Buff the shield is off"; return 0; }
+ var listed = ListedShields();
+ anyListed = listed.Count > 0;
+ if (!anyListed) { where = "no shield listed"; return 0; }
+ foreach (int id in listed)
+ {
+ if (!IsWieldedLive(id)) continue;
+ if (id == _stowedShieldId && !ShieldMidSwap(id, out _)
+ && (RynthClock.Now - _stowedShieldAt).TotalMilliseconds > StowedSightingGraceMs)
+ _stowedShieldId = 0; // back in the off hand
+ where = "in the off hand";
+ return id;
+ }
+ if (_stowedShieldId != 0 && listed.Contains(_stowedShieldId) && InInventory(_stowedShieldId))
+ {
+ where = "put into a pack for the wand";
+ return _stowedShieldId;
+ }
+ where = "the listed shield is in a pack, not worn";
+ return 0;
+ }
+
+ ///
+ /// True while may be on its way into or out of a hand: the wand swap
+ /// under way, the shield's move into a pack not confirmed, or a swap the shared gate says just
+ /// moved it (combat's off-hand wield or dequip, a held multi-step swap).
+ ///
+ private bool ShieldMidSwap(int shieldId, out string why)
+ {
+ if (_wandSwap.Active) { why = "the wand swap is under way"; return true; }
+ if (_pendingWieldId != 0) { why = "the wand's wield is in flight"; return true; }
+ if (_bowDequipPendingId == shieldId && shieldId != 0) { why = "its move into a pack is in flight"; return true; }
+ if (_weaponSwapGate != null && _weaponSwapGate.MayBeMoving(shieldId))
+ {
+ why = $"a swap is moving it ({_weaponSwapGate.LastSwapBy})";
+ return true;
+ }
+ why = "";
+ return false;
+ }
+
+ private bool ShieldParked(int shieldId) =>
+ shieldId != 0 && shieldId == _shieldParkedId && RynthClock.Now < _shieldParkedUntil;
+
+ /// A family resting after a refusal: on the shield, or for the armor too (no components, a parked family).
+ private bool ShieldFamilyResting(int family)
+ {
+ DateTime now = RynthClock.Now;
+ return (_shieldFamilyRestUntil.TryGetValue(family, out DateTime s) && now < s)
+ || (_buffFailCooldownUntil.TryGetValue(family, out DateTime a) && now < a);
+ }
+
+ /// The armor spells of this character can cast, resolved like the armor's.
+ private List<(SpellInfo Spell, string BaseName)> ShieldSpells(List desiredBuffs)
+ {
+ var list = new List<(SpellInfo, string)>();
+ foreach (string baseName in desiredBuffs)
+ {
+ if (!IsArmorItemSpell(baseName)) continue; // weapon enchantments never go on the shield
+ AcSkillType skill = SkillFor(baseName);
+ if (!IsSkillUsable(skill)) continue;
+ int spellId = FindBestSpellId(baseName, skill);
+ if (spellId == 0) continue;
+ var spell = SpellTableStub.GetById(spellId);
+ if (spell == null || !IsArmorItemSpell(spell.Name)) continue;
+ list.Add((spell, baseName));
+ }
+ return list;
+ }
+
+ /// IsBuffActive for the shield: its own timer, the armor's rules.
+ private bool IsShieldBuffActive(int shieldId, SpellInfo spell, int? rebufferSecOverride = null)
+ {
+ int level = GetSpellLevel(spell);
+ if (_isForceRebuffing)
+ {
+ // Cast on the shield in this run: done, unless a higher level is castable now.
+ if (_shieldRunLevels.TryGetValue(spell.Family, out int ran)) return UpgradeParked(spell.Family) || level <= ran;
+ if (!_isAutoBatchRebuff) return false;
+ rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
+ }
+ int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
+ if (!_shieldSpellTimers.TryGetValue(ShieldKey(shieldId, spell.Family), out ItemSpellRecord? rec)) return false;
+ if (rec.SpellLevel < level && !UpgradeParked(spell.Family)) return false; // a higher level: recast, as the armor's
+ return RynthClock.Now < rec.ExpiresAt.AddSeconds(-rebufferSec);
+ }
+
+ /// AnyBuffBelowThreshold's shield half: an armor spell on the shield to buff under .
+ private bool ShieldBuffBelowThreshold(List desiredBuffs, int thresholdSec)
+ {
+ int shield = ShieldToBuff(out _);
+ if (shield == 0 || ShieldParked(shield)) return false;
+ foreach (var (spell, _) in ShieldSpells(desiredBuffs))
+ {
+ if (ShieldFamilyResting(spell.Family)) continue;
+ if (!IsShieldBuffActive(shield, spell, thresholdSec)) return true;
+ }
+ return false;
+ }
+
+ ///
+ /// CheckAndCastSelfBuffs' last step, once every buff on the character is on: the next armor
+ /// spell the shield needs, aimed at the shield. True when it acted (a cast, or the tick yielded
+ /// to the wand swap or a move of the shield).
+ ///
+ private bool CastShieldBuffs(List desiredBuffs, bool diagnose)
+ {
+ // This step runs on every buff tick: the kept answer first (no inventory walk while
+ // nothing is due), a fresh read only once a spell is due on the shield.
+ int shield = ShieldToBuff(out string where);
+ if (shield == 0) return false;
+ if (ShieldParked(shield))
+ {
+ LastBuffSkipReason = $"shield buffs parked ({(_shieldParkedUntil - RynthClock.Now).TotalMinutes:0} min left)";
+ return false;
+ }
+ var spells = ShieldSpells(desiredBuffs);
+ if (!spells.Exists(s => !IsShieldBuffActive(shield, s.Spell) && !ShieldFamilyResting(s.Spell.Family))) return false;
+ int read = ShieldToBuff(out where, fresh: true);
+ if (read != shield) return read != 0; // another shield (next tick), or none any more
+
+ foreach (var (spell, baseName) in spells)
+ {
+ if (IsShieldBuffActive(shield, spell)) continue;
+ if (ShieldFamilyResting(spell.Family))
+ {
+ LastBuffSkipReason = $"resting on the shield: {baseName}";
+ if (diagnose) DiagSkip(baseName + "@shield", $"[FR] skip '{baseName}' on the shield — resting after a refusal");
+ continue;
+ }
+
+ if (!EnsureMagicMode(forBuff: true))
+ {
+ if (_wandSwapExhausted)
+ {
+ // The wand can't be wielded now (see the self-buff loop): rest this family on the
+ // shield so buffing lets go and combat runs.
+ _shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(BuffFailCooldownSec);
+ LastBuffSkipReason = $"wand-swap exhausted: {baseName} on the shield";
+ continue;
+ }
+ LastBuffSkipReason = "magic-mode swap in progress (yielding tick)";
+ return true;
+ }
+
+ // The wand swap may just have put the shield into a pack: where is it now?
+ int now = ShieldToBuff(out where, fresh: true);
+ if (now != shield) return now != 0; // another shield (next tick), or none any more
+ if (ShieldMidSwap(shield, out string moving))
+ {
+ LastBuffSkipReason = $"the shield is being moved: {moving}";
+ return true;
+ }
+
+ // The mana reserve holds these as it holds every buff (see the self-buff loop).
+ if (_fastChainTick && BuffNeedsManaFirst(spell.Id, out _, out _))
+ {
+ _fastChainTick = false;
+ _chain.HoldForAnimation();
+ LastBuffSkipReason = "mana reserve before " + baseName + " on the shield: Stamina to Mana waits for the animation";
+ return true;
+ }
+ if (BuffWaitsForMana(spell.Id, baseName))
+ return true;
+
+ SendShieldCast(shield, spell, baseName, where, diagnose);
+ return true;
+ }
+ return false;
+ }
+
+ private void SendShieldCast(int shield, SpellInfo spell, string baseName, string where, bool diagnose)
+ {
+ int spellId = spell.Id;
+ string shieldName = ItemName(shield);
+ _pendingSpellId = spellId;
+ _pendingShieldId = shield;
+ _pendingUpgradeSpellId = 0; // the upgrade bookkeeping is the armor's
+ _host.WriteToChat($"[RynthAi] Casting: {spell.Name} on {shieldName}", 5);
+ if (diagnose) _host.Log($"[FR] CAST '{baseName}' on the shield 0x{(uint)shield:X8} '{shieldName}' ({where}) resolvedSpellId={spellId} (pending now set)");
+ NoteBuffCastMana(SpellManaCost(spellId));
+ _host.Log($"[Buff] mana {_vitals.CurrentMana}/{_vitals.MaxMana} ({_vitals.ManaPct}%) before {spell.Name} on the shield '{shieldName}' ({where}) (cost {SpellManaCost(spellId)}, reserve {ManaReserve()}, Get Mana At {_settings.GetManaAt}%)");
+ bool fast = _fastChainTick;
+ if (fast)
+ _host.Log($"[BuffChain] '{spell.Name}' on the shield goes without waiting for the animation: {_fastChainWhy}");
+ int seqAtSend = UseDoneSeqNow();
+ bool castOk = _host.CastSpellFor(unchecked((uint)shield), spellId, "Buff", $"{spell.Name} on the shield");
+ _lastCastAttempt = RynthClock.Now;
+ if (castOk)
+ {
+ NoteCastIssued(spellId);
+ _chain.Sent(spellId, spell.Name, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, fast);
+ }
+ else
+ {
+ _chain.ClientRefused(spellId, spell.Name, fast, s => _host.Log(s));
+ _pendingSpellId = 0; // the packet never went out: no answer will come
+ _pendingShieldId = 0;
+ LastBuffSkipReason = $"local CastSpell rejected: {baseName} on the shield (id={spellId})";
+ }
+ }
+
+ /// An armor spell landed on the shield: its timer, and in a force/batch run the family is done on it.
+ private void ShieldSpellLanded(int shieldId, SpellInfo spell)
+ {
+ RecordShieldSpell(shieldId, spell);
+ int level = GetSpellLevel(spell);
+ if (_isForceRebuffing && (shieldId == _pendingShieldId || shieldId == ShieldToBuff(out _))
+ && (!_shieldRunLevels.TryGetValue(spell.Family, out int ran) || level > ran))
+ _shieldRunLevels[spell.Family] = level;
+ }
+
+ private void RecordShieldSpell(int shieldId, SpellInfo spell)
+ {
+ int level = GetSpellLevel(spell);
+ double duration = GetCustomSpellDuration(level);
+ var now = RynthClock.Now;
+ _shieldSpellTimers[ShieldKey(shieldId, spell.Family)] = new ItemSpellRecord
+ {
+ CastAt = now,
+ ExpiresAt = now.AddSeconds(duration),
+ SpellName = spell.Name,
+ SpellLevel = level,
+ };
+ _host.Log($"[BuffDiag] RECORD '{spell.Name}' on the shield 0x{(uint)shieldId:X8} (fam={spell.Family}, lvl={level}, durSec={duration:F0}, expiresAt={now.AddSeconds(duration):HH:mm:ss})");
+ SaveBuffTimers();
+ }
+
+ /// "Flame Bane VI on Kite Shield, refreshing Flame Bane V" -> "Kite Shield"; "" with no target.
+ internal static string CastTarget(string afterCast)
+ {
+ int on = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase);
+ if (on < 0) return "";
+ string rest = afterCast.Substring(on + 4);
+ int comma = rest.IndexOf(',');
+ if (comma >= 0) rest = rest.Substring(0, comma);
+ return rest.Trim().TrimEnd('.', '!').Trim();
+ }
+
+ private bool NamesShield(string target, int shieldId)
+ {
+ string name = _worldObjectCache?[shieldId]?.Name ?? "";
+ return name.Length == 0 || target.Equals(name, StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// The listed shield a cast line names (the pending one first), 0 = none.
+ private int ListedShieldNamed(string target)
+ {
+ if (target.Length == 0) return 0;
+ var listed = ListedShields();
+ if (_pendingShieldId != 0 && listed.Contains(_pendingShieldId) && NamesShield(target, _pendingShieldId)
+ && (_worldObjectCache?[_pendingShieldId]?.Name ?? "").Length > 0)
+ return _pendingShieldId;
+ foreach (int id in listed)
+ {
+ string name = _worldObjectCache?[id]?.Name ?? "";
+ if (name.Length > 0 && target.Equals(name, StringComparison.OrdinalIgnoreCase)) return id;
+ }
+ return 0;
+ }
+
+ ///
+ /// OnChatWindowText's "You cast X on Y" for the shield, before the armor's handling: the pending
+ /// shield cast's result, a late line for a listed shield, or a self-cast that reached a worn
+ /// shield. Records the shield's timer. True when the line is done with here.
+ ///
+ private bool ShieldCastLine(SpellInfo spell, string afterCast)
+ {
+ if (!IsArmorItemSpell(spell.Name)) return false;
+ string target = CastTarget(afterCast);
+ var pending = PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
+ if (pending != null && pending.Family == spell.Family)
+ {
+ if (target.Length > 0 && !NamesShield(target, _pendingShieldId))
+ {
+ // A late line of the armor's own cast of this family: the armor's; the shield's cast waits.
+ RecordItemSpellCast(spell);
+ _host.Log($"[BuffChat] '{spell.Name}' on '{target}' is the armor's, not pending={_pendingSpellId} on the shield - recorded, pending kept.");
+ return true;
+ }
+ ShieldSpellLanded(_pendingShieldId, spell);
+ _shieldFamilyRestUntil.Remove(spell.Family);
+ _shieldNoShows = 0;
+ NoteCastAccepted();
+ _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} (on the shield 0x{(uint)_pendingShieldId:X8}) via ou-cast match name='{spell.Name}'");
+ _pendingSpellId = 0;
+ _pendingShieldId = 0;
+ _onCastResolved?.Invoke($"cast '{spell.Name}' on the shield");
+ return true;
+ }
+
+ int named = ListedShieldNamed(target);
+ if (named == 0) return false;
+ ShieldSpellLanded(named, spell);
+ // A self-cast of this family that reached a worn shield: the armor's result as well.
+ var selfPending = _pendingSpellId != 0 && !PendingIsShield ? SpellTableStub.GetById(_pendingSpellId) : null;
+ if (selfPending != null && selfPending.Family == spell.Family) return false;
+ _host.Log($"[BuffChat] '{spell.Name}' on the shield '{target}' - a late line, recorded{(_pendingSpellId != 0 ? $"; pending={_pendingSpellId} kept" : "")}.");
+ return true;
+ }
+
+ /// The pending shield cast was refused or fizzled: the armor's timers and families are left alone.
+ private void ShieldCastRefused(SpellInfo? spell, string why, double restSec)
+ {
+ if (spell != null && restSec > 0)
+ _shieldFamilyRestUntil[spell.Family] = RynthClock.Now.AddSeconds(restSec);
+ _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - {why}" +
+ (restSec > 0 ? $"; {spell?.Name} rests on the shield {restSec:0}s." : "; tried again."));
+ }
+
+ /// The pending shield cast got no answer in time (the tick's no-chat give-up).
+ private void ShieldCastNoShow(SpellInfo? spell)
+ {
+ int shield = _pendingShieldId;
+ _shieldNoShows++;
+ if (_shieldNoShows >= ShieldNoShowsToPark)
+ {
+ _shieldNoShows = 0;
+ ParkShield(shield, $"{ShieldNoShowsToPark} casts on it got no answer");
+ }
+ else
+ _host.Log($"[BuffChat] NO-CHAT TIMEOUT (shield) pending={_pendingSpellId} ('{spell?.Name}') on 0x{(uint)shield:X8} - " +
+ $"no answer in {NoChatResolveTimeoutMs:0}ms ({_shieldNoShows}/{ShieldNoShowsToPark} before shield buffing rests).");
+ }
+
+ private void ParkShield(int shield, string why)
+ {
+ _shieldParkedId = shield;
+ _shieldParkedUntil = RynthClock.Now + ShieldParkTime;
+ _host.Log($"[Buff] shield 0x{(uint)shield:X8} '{ItemName(shield)}': {why} - not buffing it for {ShieldParkTime.TotalMinutes:0} min.");
+ _host.WriteToChat($"[RynthAi] Not buffing the shield '{ItemName(shield)}' for {ShieldParkTime.TotalMinutes:0} min ({why}).", 2);
+ }
+
+ /// Force Rebuff: the shield starts over too.
+ private void ResetShieldBuffs()
+ {
+ _shieldSpellTimers.Clear();
+ _shieldRunLevels.Clear();
+ _shieldFamilyRestUntil.Clear();
+ _shieldNoShows = 0;
+ _shieldParkedId = 0;
+ _shieldParkedUntil = DateTime.MinValue;
+ _pendingShieldId = 0;
+ }
+
+ /// bufftimers.txt lines for the shield: "shield|id|family|castTicks|expiresTicks|level|name".
+ private void SaveShieldTimers(List lines)
+ {
+ foreach (var kvp in _shieldSpellTimers)
+ {
+ var info = kvp.Value;
+ uint id = unchecked((uint)(kvp.Key >> 32));
+ int family = unchecked((int)(kvp.Key & 0xFFFFFFFF));
+ lines.Add($"shield|{id}|{family}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
+ }
+ }
+
+ /// One "shield|..." line of bufftimers.txt; false when the line is something else.
+ private bool LoadShieldTimer(string[] p)
+ {
+ if (p[0] != "shield") return false;
+ if (p.Length < 7) return true;
+ if (!uint.TryParse(p[1], out uint id) || !int.TryParse(p[2], out int family)
+ || !long.TryParse(p[3], out long cast) || !long.TryParse(p[4], out long expires) || !int.TryParse(p[5], out int level))
+ return true;
+ var expiresAt = new DateTime(expires);
+ if (expiresAt > RynthClock.Now)
+ _shieldSpellTimers[ShieldKey(unchecked((int)id), family)] = new ItemSpellRecord
+ {
+ CastAt = new DateTime(cast), ExpiresAt = expiresAt, SpellLevel = level, SpellName = p[6],
+ };
+ return true;
+ }
+
+ /// /ra buffs and /ra buffs item: the shield's timers.
+ private void PrintShieldSpellTimers()
+ {
+ if (_shieldSpellTimers.Count == 0) return;
+ _host.WriteToChat($"[RynthAi] -- Shield spells ({_shieldSpellTimers.Count}) --", 1);
+ foreach (var kvp in _shieldSpellTimers)
+ {
+ var info = kvp.Value;
+ int id = unchecked((int)(uint)(kvp.Key >> 32));
+ TimeSpan left = info.ExpiresAt - RynthClock.Now;
+ _host.WriteToChat(left.TotalSeconds <= 0
+ ? $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): EXPIRED"
+ : $"[RynthAi] {ItemName(id)}: {info.SpellName} (Lvl {info.SpellLevel}): {Math.Round(left.TotalMinutes, 1)}m left / {Math.Round((info.ExpiresAt - info.CastAt).TotalMinutes, 0)}m total", 1);
+ }
+ }
+
+ /// Shield spell timers recorded (tests, status).
+ internal int ShieldSpellCount => _shieldSpellTimers.Count;
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index 691825f..c8149d9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -916,6 +916,9 @@ public partial class BuffManager : IDisposable
var info = kvp.Value;
lines.Add($"item|{kvp.Key}|{info.CastAt.Ticks}|{info.ExpiresAt.Ticks}|{info.SpellLevel}|{info.SpellName}");
}
+ // Last: a build from before the shield's lines reads them as old-style lines that
+ // expired long ago (no exception, so the lines above are loaded either way).
+ SaveShieldTimers(lines);
// The "char doesn't know this spell" blacklist is NO LONGER persisted.
// Persisting it meant one lag-induced no-chat timeout permanently
// poisoned a KNOWN spell across all future sessions, collapsing the
@@ -934,9 +937,11 @@ public partial class BuffManager : IDisposable
{
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
+ _shieldSpellTimers.Clear();
foreach (string line in System.IO.File.ReadAllLines(_buffTimerPath))
{
string[] p = line.Split('|');
+ if (LoadShieldTimer(p)) continue;
if (p[0] == "item" && p.Length >= 6)
{
@@ -973,9 +978,10 @@ public partial class BuffManager : IDisposable
_ramBuffTimers[family] = new RamTimerInfo { Expiration = expiration, SpellLevel = level, SpellName = name };
}
}
- int total = _ramBuffTimers.Count + _itemSpellTimers.Count;
+ int total = _ramBuffTimers.Count + _itemSpellTimers.Count + _shieldSpellTimers.Count;
if (total > 0)
- _host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s).", 1);
+ _host.WriteToChat($"[RynthAi] Restored {_ramBuffTimers.Count} player + {_itemSpellTimers.Count} item spell timer(s)" +
+ (_shieldSpellTimers.Count > 0 ? $" + {_shieldSpellTimers.Count} on the shield." : "."), 1);
}
catch { }
}
@@ -1020,6 +1026,7 @@ public partial class BuffManager : IDisposable
_upgradeParkedUntil.Clear();
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
+ ResetShieldBuffs(); // the shield's timers, rests and park too
EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff");
_pendingSpellId = 0;
_lastCastAttempt = DateTime.MinValue;
@@ -1522,6 +1529,20 @@ public partial class BuffManager : IDisposable
// switch in mid-cast.
if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("buff cast in flight", pendingSpell.Name); return; }
}
+ else if (pendingIsArmor && PendingIsShield)
+ {
+ // An armor spell aimed at the shield (BuffManager.Shield.cs): chat is authoritative,
+ // as for the armor, but a give-up counts against the shield only. No blacklist (the
+ // same spell just went on the armor) and no family park for the armor.
+ if (PendingGiveUpReached(NoChatResolveTimeoutMs))
+ {
+ ShieldCastNoShow(pendingSpell);
+ _pendingSpellId = 0;
+ _pendingShieldId = 0;
+ _onCastResolved?.Invoke("no-chat timeout (shield)");
+ }
+ if (_pendingSpellId != 0) { TryEmergencyHealWhilePending(); Hold("item spell in flight", pendingSpell?.Name ?? ""); return; }
+ }
else if (pendingIsArmor)
{
// ARMOR/ITEM: chat is authoritative. No-chat valve abandons a cast
@@ -2299,6 +2320,7 @@ public partial class BuffManager : IDisposable
// ever come; setting pending anyway waited 2.5 s and counted a no-show
// strike. Mirror the buff path: not handled, so the potion gets its turn.
_pendingSpellId = spellId;
+ _pendingShieldId = 0; // on the player, not the shield
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
_pendingVitalLabel = label;
_pendingVitalBase = what;
@@ -2785,7 +2807,8 @@ public partial class BuffManager : IDisposable
continue;
if (!IsBuffActive(spellId, thresholdSec)) return true;
}
- return false;
+ // The shield's armor spells start a batch the same way (BuffManager.Shield.cs).
+ return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec);
}
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
@@ -2912,6 +2935,7 @@ public partial class BuffManager : IDisposable
int upgradeFrom = spellInfo != null && buffFamily != 0 ? ActiveLevelBelow(buffFamily, upgradeTo) : 0;
_pendingSpellId = spellId;
+ _pendingShieldId = 0; // on the player, not the shield
if (buffFamily != 0)
{
_lastCastSpellIdByFamily[buffFamily] = spellId;
@@ -2967,7 +2991,8 @@ public partial class BuffManager : IDisposable
}
return true;
}
- return false;
+ // Everything on the character is on: the shield's armor spells (BuffManager.Shield.cs).
+ return CastShieldBuffs(desiredBuffs, diagnose);
}
/// Casts that replaced an active buff of the same family at a lower level (tests, status).
@@ -3310,6 +3335,7 @@ public partial class BuffManager : IDisposable
{
_forceRebuffCastFamilies.Clear();
_runConfirmedLevelByFamily.Clear();
+ _shieldRunLevels.Clear();
}
///
@@ -3572,10 +3598,12 @@ public partial class BuffManager : IDisposable
// left them "active" for up to an hour and the bot fought unbuffed (reported as
// "buffing skips missile weapons"). The player's registry dropping to zero (a death,
// or logging in after one) is the signal: forget them so they get recast.
- if (count == 0 && _lastLivePlayerEnchantCount != 0 && _itemSpellTimers.Count > 0)
+ if (count == 0 && _lastLivePlayerEnchantCount != 0 && (_itemSpellTimers.Count > 0 || _shieldSpellTimers.Count > 0))
{
- _host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s) so weapon/armor buffs recast");
+ _host.Log($"[BuffDiag] player enchantments dropped to 0 (was {_lastLivePlayerEnchantCount}) - clearing {_itemSpellTimers.Count} item-spell timer(s)" +
+ $"{(_shieldSpellTimers.Count > 0 ? $" and {_shieldSpellTimers.Count} on the shield" : "")} so weapon/armor buffs recast");
_itemSpellTimers.Clear();
+ _shieldSpellTimers.Clear();
}
_lastLivePlayerEnchantCount = count;
@@ -3808,7 +3836,7 @@ public partial class BuffManager : IDisposable
_host.WriteToChat($"[RynthAi] ServerTime={Math.Round(serverNow)} (no live read: serverTime=0 or API missing)", 1);
}
- if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0)
+ if (_ramBuffTimers.Count == 0 && _itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
{
_host.WriteToChat("[RynthAi] No buff timers active.", 1);
return;
@@ -3819,6 +3847,7 @@ public partial class BuffManager : IDisposable
_host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
PrintItemSpellTimers();
}
+ PrintShieldSpellTimers();
if (_ramBuffTimers.Count > 0)
{
@@ -3882,13 +3911,17 @@ public partial class BuffManager : IDisposable
public void PrintItemBuffDebug()
{
- if (_itemSpellTimers.Count == 0)
+ if (_itemSpellTimers.Count == 0 && _shieldSpellTimers.Count == 0)
{
_host.WriteToChat("[RynthAi] No item spell timers recorded yet.", 1);
return;
}
- _host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
- PrintItemSpellTimers();
+ if (_itemSpellTimers.Count > 0)
+ {
+ _host.WriteToChat($"[RynthAi] -- Item spells ({_itemSpellTimers.Count}) --", 1);
+ PrintItemSpellTimers();
+ }
+ PrintShieldSpellTimers();
}
private void PrintItemSpellTimers()
@@ -4228,8 +4261,9 @@ public partial class BuffManager : IDisposable
// Only clear pending if this enchantment matches what we were casting.
// Armor/item enchantments fire on the item, not the player — clearing
// _pendingSpellId unconditionally would lose track of pending item casts
- // and prevent the chat handler from recording their timers.
- if (_pendingSpellId != 0)
+ // and prevent the chat handler from recording their timers. A cast at the shield never
+ // lands on the player: only its chat line resolves it.
+ if (_pendingSpellId != 0 && !PendingIsShield)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null && pendingSpell.Family == spellInfo.Family)
@@ -4368,12 +4402,12 @@ public partial class BuffManager : IDisposable
else if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
- if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
+ if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // the shield's refusal leaves the armor's timer
{
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
- _host.Log($"[BuffChat] PARKED pending={_pendingSpellId} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
+ _host.Log($"[BuffChat] PARKED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
if (_pendingSpellId != _pendingVitalSpellId)
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
}
@@ -4432,6 +4466,14 @@ public partial class BuffManager : IDisposable
_noComponentsUntil[_pendingSpellId] = RynthClock.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
}
+ else if (pendingSpell != null && PendingIsShield)
+ {
+ // Aimed at the shield: the family rests on the shield only; the armor's is on.
+ bool noComps = lower.Contains("components") || lower.Contains("missing some required");
+ ShieldCastRefused(pendingSpell, "hard rejection", BuffFailCooldownSec);
+ _host.WriteToChat($"[RynthAi] Skipping {pendingSpell.Name} on the shield for {BuffFailCooldownSec / 60:0} min " +
+ $"({(noComps ? "no components for it" : "the server refused it")}).", 2);
+ }
else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
@@ -4481,7 +4523,9 @@ public partial class BuffManager : IDisposable
return;
}
double restSec = LowManaFamilyRestSec;
- if (pendingSpell != null)
+ if (pendingSpell != null && PendingIsShield)
+ ShieldCastRefused(pendingSpell, "not enough mana", restSec); // rests on the shield; the armor's timer stays
+ else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
{
@@ -4515,12 +4559,12 @@ public partial class BuffManager : IDisposable
if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
- if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name))
+ if (pendingSpell != null && IsItemEnchantment(pendingSpell.Name) && !PendingIsShield) // a fizzle at the shield leaves the armor's timer
{
_itemSpellTimers.Remove(pendingSpell.Family);
SaveBuffTimers();
}
- _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via soft-fail in '{text}'");
+ _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} via soft-fail in '{text}'");
}
_lastCastAttempt = DateTime.MinValue;
EndPendingUpgrade(_pendingSpellId, "fizzled");
@@ -4529,6 +4573,19 @@ public partial class BuffManager : IDisposable
return;
}
+ // "Flame Bane VI cannot be cast on Kite Shield." (ACE IsInvalidTarget: an item that takes no
+ // spells). Read only for a cast at the shield: shield buffing rests; the armor carries on.
+ if (PendingIsShield && lower.Contains(" cannot be cast on "))
+ {
+ _cast.Result(null, "refused by the server", atStart: true);
+ _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} on the shield 0x{(uint)_pendingShieldId:X8} - '{text}'");
+ ParkShield(_pendingShieldId, "the server says these spells can't be cast on it");
+ _pendingSpellId = 0;
+ _pendingShieldId = 0;
+ _onCastResolved?.Invoke("can't be cast on the shield");
+ return;
+ }
+
// A script heal (a transfer such as Vitality Siphon) cast at a monster that resists it:
// "Doorheld Surveyor resists your spell" is its only result, no "due to casting" line
// follows. Closed here as CombatManager reads the same line for its own casts.
@@ -4605,6 +4662,11 @@ public partial class BuffManager : IDisposable
if (spellInfo == null && _pendingSpellId != 0)
spellInfo = SpellTableStub.GetById(_pendingSpellId);
+ // An armor spell's line for the shield (its own cast, a late line, or a self-cast that
+ // reached a worn shield) goes on the shield's timer, not the armor's (BuffManager.Shield.cs).
+ if (spellInfo != null && !viaDueToCasting && ShieldCastLine(spellInfo, afterCast))
+ return;
+
// A result that names another spell than the pending one is not the pending cast's
// result: the pending cast keeps waiting for its own (or its give-up time).
var pendingInfo = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId) : null;
@@ -5428,7 +5490,7 @@ public partial class BuffManager : IDisposable
return WandSwapFailed(_wandSwap.Abandon("no pack with room"), forBuff, wandId, now);
}
bool offhand = hands.TryGetValue(step.Id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0;
- if (offhand) OffhandStowed?.Invoke(step.Id); // combat puts it back after
+ if (offhand) OffhandPutAway(step.Id); // combat puts it back after (and it is buffed in the pack)
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
@@ -5554,7 +5616,7 @@ public partial class BuffManager : IDisposable
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
foreach (int id in moves)
{
- if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandStowed?.Invoke(id);
+ if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandPutAway(id);
_host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
}
_host.WieldItem(unchecked((uint)wandId), HeldSlot);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs
index 1c8ae9e..98f71ec 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponSwapGate.cs
@@ -147,6 +147,22 @@ public sealed class WeaponSwapGate
}
}
+ ///
+ /// True while may still be on its way into or out of a hand: a
+ /// multi-step swap holds the gate, or the last claimed swap noted a move of this item and the
+ /// next swap would still wait for it (MinIntervalMs). Buffing doesn't aim a spell at a shield
+ /// then (BuffManager.Shield.cs).
+ ///
+ public bool MayBeMoving(int itemId)
+ {
+ long now = NowMs();
+ lock (_lock)
+ {
+ if (_heldBy.Length > 0 && now < _heldUntilMs) return true;
+ return itemId != 0 && _movingId == itemId && now - _lastSwapTickMs < MinIntervalMs;
+ }
+ }
+
/// Milliseconds since the last successful swap (diagnostics).
public long MsSinceLastSwap
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
index 7bff5f3..eaf1281 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
@@ -1006,6 +1006,13 @@ internal sealed class LegacyAdvancedSettingsUi
}
ImGui.EndTable();
}
+ ImGui.Checkbox("Buff the shield", ref _settings.BuffShield);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(
+ "Cast the ticked Impenetrability and Banes on your shield too, after\n" +
+ "the armor, renewed with it. The shield is the one in the Items list\n" +
+ "(Shield) that you wear: buffing puts it in a pack for the wand, so it\n" +
+ "is buffed there. On by default. No shield listed: nothing changes.");
ImGui.Spacing();
ImGui.Separator();
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index e563a44..c935f2f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -2055,7 +2055,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
- dst.BlacklistAttempts = tmp.BlacklistAttempts;
+ dst.BuffShield = tmp.BuffShield;
+ dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
// saved into profiles: it judges each cast before its damage can land.
@@ -2870,6 +2871,7 @@ internal sealed partial class LegacyDashboardRenderer
switch (cmd.Cmd)
{
case "startNav":
+ _settings.RearmFinishedNavRoute(); // the player's Start Navigation re-runs a finished Once route
_settings.IsMacroRunning = true;
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
@@ -3202,7 +3204,12 @@ internal sealed partial class LegacyDashboardRenderer
{
case 0: _settings.EnableCombat = enabled; break;
case 1: _settings.EnableBuffing = enabled; break;
- case 2: _settings.EnableNavigation = enabled; break;
+ case 2:
+ // The player switching nav on over a finished Once route re-runs it (a meta's
+ // enablenav doesn't, NavigationEngine.HandleRouteEnd).
+ if (enabled && !_settings.EnableNavigation) _settings.RearmFinishedNavRoute();
+ _settings.EnableNavigation = enabled;
+ break;
case 3: _settings.EnableLooting = enabled; break;
case 4: _settings.EnableMeta = enabled; break;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
index 3b30005..5f4d9aa 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
@@ -63,6 +63,7 @@ internal sealed class LegacyNavigationUi
ImGui.PushStyleColor(ImGuiCol.ButtonActive, new Vector4(0.08f, 0.28f, 0.08f, 1f));
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
{
+ _settings.RearmFinishedNavRoute(); // a finished Once route runs again
_settings.IsMacroRunning = true;
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index 79bc551..5d7dc1f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -389,6 +389,14 @@ public sealed class LegacyUiSettings
else next.Add(buffBaseName);
_disabledBuffs = next;
}
+ ///
+ /// Cast the armor spells (Impenetrability and the Banes still ticked above) on the shield
+ /// listed in the Items list too, after the armor, on the armor's timers (BuffManager.Shield.cs).
+ /// The self-cast never reaches it: ACE won't wield the wand beside a shield, so buffing puts
+ /// the shield into a pack first. On by default; a profile saved before this setting existed
+ /// loads it as on. No shield listed: nothing changes.
+ ///
+ public bool BuffShield = true;
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
///
@@ -726,6 +734,32 @@ public sealed class LegacyUiSettings
[JsonIgnore] public NavRouteParser CurrentRoute { get; set; } = new();
public int ActiveNavIndex;
+ ///
+ /// True for a Once route that has walked off its last point (the nav engine leaves the
+ /// index past the end). It stays finished over a macro stop/start and a meta turning nav
+ /// on, until it is loaded again, edited, or restarted (/ra nav restart, or
+ /// from the player's own nav-on controls).
+ ///
+ public bool NavRouteFinished()
+ {
+ var route = CurrentRoute;
+ return route != null && route.RouteType == NavRouteType.Once
+ && route.Points.Count > 0 && ActiveNavIndex >= route.Points.Count;
+ }
+
+ ///
+ /// The player turned nav on (the Nav switch, a Start Navigation button): a finished Once
+ /// route runs again from [0], as re-enabling nav did before 2026-10-28. Metas and scripts
+ /// that switch nav on don't call this, so a stop/start replaying a meta's
+ /// "/vt opt set enablenav true" no longer re-runs a finished route. True if it rewound.
+ ///
+ public bool RearmFinishedNavRoute()
+ {
+ if (!NavRouteFinished()) return false;
+ ActiveNavIndex = 0;
+ return true;
+ }
+
public bool ShowAdvancedWindow;
public int SelectedAdvancedTab;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
index a4a4085..48573dc 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
@@ -3701,6 +3701,7 @@ internal sealed partial class ExpressionEngine
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),
+ ["BuffShield"] = (() => B(s.BuffShield), v => s.BuffShield = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
index 7a53bab..85920ad 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
@@ -76,6 +76,22 @@ internal sealed class MetaManager
private long _evalChatSeq; // newest chat line its condition matched
private Match? _lastChatMatch;
+ // ── Macro stop/start replay ──────────────────────────────────────────────
+ // Starting the macro re-arms every rule of the state it is in (so a meta puts back a
+ // route the player changed or cleared while it was stopped). The rules that had already
+ // fired in that state before the stop "replay" when they fire again. A replayed nav load
+ // (EmbedNav, /vt nav load, /ra nav load) of the route that is still loaded and unchanged
+ // keeps the route where it was: its waypoint, a Linear route's direction, a finished
+ // Once route finished; a replayed "/ra nav restart" is skipped. Reloading here restarted
+ // Once routes on every stop/start (2026-10-28). Cleared by the next real state entry; a
+ // rule that first fires after the start is not a replay, and its nav load starts the
+ // route fresh as before.
+ private readonly HashSet _replayRules = new(ReferenceEqualityComparer.Instance);
+ private bool _replaying; // the action running now belongs to a replayed rule
+
+ /// Where a meta's nav names are looked for as .nav files. Tests point it at a scratch folder.
+ internal string NavFolder { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
+
// ── Call stack (CallMetaState / ReturnFromCall) ──────────────────────────
private readonly Stack _stateStack = new();
@@ -236,6 +252,73 @@ internal sealed class MetaManager
? 0
: FindNearestWaypoint(route);
+ ///
+ /// A replayed nav load (see ): true, and nothing reloaded, when
+ /// is the route loaded now and it still has the points of its source
+ /// (not edited, reversed or swapped for another since). The route
+ /// keeps its waypoint and a Linear route its direction (the engine sees the same route
+ /// object); nav is switched on as the load would, except for a finished Once route, which
+ /// stays finished. False: the caller loads the route fresh, as before.
+ ///
+ private bool KeepRunningRoute(string path, NavRouteParser source, string what)
+ {
+ var cur = _settings.CurrentRoute;
+ if (cur == null || cur.Points.Count == 0 || source.Points.Count == 0) return false;
+ if (!SameNavPath(_settings.CurrentNavPath, path)) return false;
+ if (!SameLines(cur.ToLines(), source.ToLines())) return false;
+
+ bool finished = _settings.NavRouteFinished();
+ if (!finished) _settings.EnableNavigation = true;
+ RynthLog.Write(LogCat.Meta, finished
+ ? $"[Meta] {what}: the macro started again on the same route, which is finished - it stays finished (/ra nav restart re-runs it)"
+ : $"[Meta] {what}: the macro started again on the same route - it carries on at [{_settings.ActiveNavIndex}] instead of starting over");
+ return true;
+ }
+
+ /// A replayed "/vt nav load" or "/ra nav load" of the .nav file that is still the loaded, unchanged route.
+ private bool KeepRunningNavFile(string rawName)
+ {
+ string name = NewProfileFiles.Tidy(rawName, NewProfileFiles.NavExtensions, out _);
+ if (NewProfileFiles.Validate(name) != null) return false;
+ string path = Path.Combine(NavFolder, name + ".nav");
+ if (!File.Exists(path)) return false;
+ return KeepRunningRoute(path, NavRouteParser.Load(path), $"nav load '{name}'");
+ }
+
+ ///
+ /// A replayed /ra nav command that would start the route over: "/ra nav load" of the running,
+ /// unchanged route, or "/ra nav restart". True: skipped, the nav stays where it was.
+ ///
+ private bool SkipReplayedNavCommand(string cmd)
+ {
+ string[] parts = cmd.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length < 3 || !parts[1].Equals("nav", StringComparison.OrdinalIgnoreCase)) return false;
+ if (parts[2].Equals("restart", StringComparison.OrdinalIgnoreCase))
+ {
+ RynthLog.Write(LogCat.Meta, "[Meta] /ra nav restart: not run again for the macro start (it ran when the rule first fired)");
+ return true;
+ }
+ return parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && parts.Length >= 4
+ && KeepRunningNavFile(string.Join(" ", parts, 3, parts.Length - 3));
+ }
+
+ private static bool SameNavPath(string? a, string? b)
+ {
+ if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
+ if (string.Equals(a, b, StringComparison.OrdinalIgnoreCase)) return true;
+ if (a.StartsWith('<') || b.StartsWith('<')) return false; // "" is not a file
+ try { return string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); }
+ catch { return false; }
+ }
+
+ private static bool SameLines(List a, List b)
+ {
+ if (a.Count != b.Count) return false;
+ for (int i = 0; i < a.Count; i++)
+ if (!string.Equals(a[i], b[i], StringComparison.Ordinal)) return false;
+ return true;
+ }
+
public ExpressionEngine Expressions => _expressions ??= CreateExpressionEngine();
private ExpressionEngine CreateExpressionEngine()
@@ -312,7 +395,10 @@ internal sealed class MetaManager
// Macro just started — force reset so rules re-evaluate even if state
// name matches where we stopped. Otherwise HasFired stays latched across
// a stop/start cycle and IF:Always rules like EmbedNav never re-fire.
- if (!_lastMacroRunning)
+ // The rules that had already fired replay (see _replayRules): a replayed nav
+ // load of the route still running keeps its place instead of starting it over.
+ bool macroStarted = !_lastMacroRunning;
+ if (macroStarted)
_settings.ForceStateReset = true;
_lastMacroRunning = true;
@@ -343,9 +429,21 @@ internal sealed class MetaManager
_statePStartTime = _statePResume is double resumed ? Clock().AddSeconds(-resumed) : Clock();
_statePResume = null;
_settings.ForceStateReset = false;
+ // A bare stop/start (no state entry, no meta load pending) replays the rules that
+ // had fired; any other reset is a real state entry and nothing is a replay.
+ bool replay = macroStarted && !realStateEntry && !metaReloaded;
lock (_settings.MetaRulesLock)
- foreach (var r in _settings.MetaRules) r.HasFired = false;
+ {
+ _replayRules.Clear();
+ foreach (var r in _settings.MetaRules)
+ {
+ if (replay && r.HasFired) _replayRules.Add(r);
+ r.HasFired = false;
+ }
+ }
}
+ else if (stateChanged)
+ _replayRules.Clear();
_lastState = _settings.CurrentState;
double secondsInState = (Clock() - _stateStartTime).TotalSeconds;
@@ -434,7 +532,9 @@ internal sealed class MetaManager
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] {rule.State} | {DescribeCondition(rule)} → {DescribeAction(rule)}", 1);
- ExecuteAction(rule);
+ _replaying = _replayRules.Contains(rule);
+ try { ExecuteAction(rule); }
+ finally { _replaying = false; }
// If state changed during this action, stop evaluating further rules this tick
if (_settings.CurrentState != _lastState || _settings.ForceStateReset)
@@ -888,7 +988,10 @@ internal sealed class MetaManager
if (cmd.StartsWith("/ra ", StringComparison.OrdinalIgnoreCase)
|| cmd.Equals("/ra", StringComparison.OrdinalIgnoreCase))
{
- _raCommandHandler?.Invoke(cmd);
+ // A replayed "/ra nav load" of the route still running, or "/ra nav restart",
+ // would start the route over: skipped.
+ if (!(_replaying && SkipReplayedNavCommand(cmd)))
+ _raCommandHandler?.Invoke(cmd);
}
else if (_host.HasInvokeChatParser)
_host.InvokeChatParser(cmd);
@@ -977,7 +1080,7 @@ internal sealed class MetaManager
// 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")))
+ && !File.Exists(Path.Combine(NavFolder, routeName + ".nav")))
{
_host.Log("[Meta] EmbedNav: Patrol -> /ra dunnav-patrol");
if (_raCommandHandler != null) _raCommandHandler("/ra dunnav-patrol");
@@ -1002,6 +1105,8 @@ internal sealed class MetaManager
if (_settings.EmbeddedNavs.TryGetValue(routeName, out var embedded))
{
var newRoute = NavRouteParser.LoadFromLines(embedded);
+ // The macro was started again: the route still running keeps its place.
+ if (_replaying && KeepRunningRoute($"", newRoute, $"EmbedNav '{routeName}'")) break;
_settings.CurrentNavPath = $"";
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
@@ -1012,11 +1117,11 @@ internal sealed class MetaManager
}
// Fallback: a standalone .nav file in NavProfiles.
- string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
- string fullPath = Path.Combine(navFolder, routeName + ".nav");
+ string fullPath = Path.Combine(NavFolder, routeName + ".nav");
if (File.Exists(fullPath))
{
var newRoute = NavRouteParser.Load(fullPath);
+ if (_replaying && KeepRunningRoute(fullPath, newRoute, $"EmbedNav file '{routeName}'")) break;
_settings.CurrentNavPath = fullPath;
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
@@ -1257,6 +1362,9 @@ internal sealed class MetaManager
|| parts[2].Equals("save", StringComparison.OrdinalIgnoreCase)))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
+ // The macro was started again: the route still running keeps its place.
+ if (_replaying && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && KeepRunningNavFile(name))
+ return true;
_raCommandHandler?.Invoke($"/ra nav {parts[2].ToLowerInvariant()} {name}");
return true;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
index c4f285b..bf9e3cc 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs
@@ -763,8 +763,9 @@ internal sealed class NavigationEngine
/// Points the route at the waypoint nearest the player (macro start). Circular
/// and Linear routes pick from the whole route; a Once route only from the
/// current waypoint onward, so finished steps (a recall, a portal) aren't
- /// repeated. Only plain waypoints are candidates; if the current one is a
- /// Recall/Portal/Chat/Pause step it is kept. With NavResumeNearest off the
+ /// repeated, and a finished Once route stays finished. Only plain waypoints are
+ /// candidates; if the current one is a Recall/Portal/Chat/Pause step it is kept.
+ /// A Linear route keeps its direction. With NavResumeNearest off the
/// route keeps its last waypoint, unless (hazard escapes
/// and corpse runs, which leave the route behind).
///
@@ -781,6 +782,9 @@ internal sealed class NavigationEngine
var route = _settings.CurrentRoute;
if (route == null || route.Points.Count == 0) return;
if (route.RouteType == NavRouteType.Follow) return;
+ // A finished Once route (index left past its end) is done: picking from [0] here
+ // used to turn it back on at the nearest point, so a stop + start re-ran it.
+ if (_settings.NavRouteFinished()) return;
if (!TryGetPos(out double ns, out double ew)) return;
int cur = _settings.ActiveNavIndex;
@@ -922,6 +926,23 @@ internal sealed class NavigationEngine
_hasGoodHeading = false;
}
+ ///
+ /// /ra nav restart: the loaded route starts over from its first point, as when it was
+ /// loaded with NavResumeNearest off (a Linear route heading out again, a finished Once
+ /// route running again). Nav is switched on; the macro is left as it is. False (nothing
+ /// done) with no waypoints to walk (none loaded, or a Follow route).
+ ///
+ public bool RestartRoute()
+ {
+ var route = _settings.CurrentRoute;
+ if (route == null || route.Points.Count == 0 || route.RouteType == NavRouteType.Follow) return false;
+ ResetRouteState();
+ _settings.ActiveNavIndex = 0;
+ _settings.EnableNavigation = true;
+ _host.Log($"Nav: route restarted from [0] ({route.RouteType}, {route.Points.Count} pts)");
+ return true;
+ }
+
///
/// One-shot view of everything the nav engine is keying off. Nav had no
/// snapshot (Combat/Buff/Meta did), so a wedged route meant guessing which
@@ -1454,14 +1475,17 @@ internal sealed class NavigationEngine
/// A finite (Once) route ran off its last point: stop and disable nav, but leave
/// the points intact. This used to Points.Clear() the in-memory route, so
/// re-enabling nav was a silent no-op until the profile was reloaded
- /// (2026-06-03 audit P2). The index is left past the end; re-enabling nav lands
- /// in , which rewinds it for a genuine re-run.
+ /// (2026-06-03 audit P2). The index is left past the end, which marks the route
+ /// finished (): it stays finished
+ /// over a macro stop/start and a meta turning nav on, and runs again when it is
+ /// loaded again, edited, or restarted (/ra nav restart, or the player's Nav switch /
+ /// Start Navigation button, ).
///
private void CompleteOnceRoute(NavRouteParser route)
{
_settings.EnableNavigation = false;
StopMovement();
- _host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained for re-run");
+ _host.Log($"Nav: Once route complete ({route.Points.Count} pts) — nav disabled, route retained (load it again or /ra nav restart to re-run)");
}
private void HandleRouteEnd(NavRouteParser route)
@@ -1472,16 +1496,19 @@ internal sealed class NavigationEngine
return;
}
- // Nav was re-enabled on a finished Once route (CompleteOnceRoute leaves the
- // index past the end). Rewind so the re-run actually walks instead of
- // silently doing nothing. Cannot loop: completion always disables nav, and
- // Tick returns early while it is disabled.
- if (route.RouteType == NavRouteType.Once
- && _settings.ActiveNavIndex >= route.Points.Count
- && route.Points.Count > 0)
+ // Nav was switched on over a finished Once route (CompleteOnceRoute leaves the
+ // index past the end). This used to rewind it to [0], so anything that turned nav
+ // on re-ran the route: a meta's "/vt opt set enablenav true" replayed by a macro
+ // start, an expression. It stays finished, as a finished VTank Once route (its
+ // points used up) does; the player's Nav switch / Start Navigation button and
+ // /ra nav restart rewind it before nav gets here. Nav goes off again so the
+ // arbiter doesn't hold "Navigating" (above combat with BoostNavPriority) for a
+ // route with nothing left to walk.
+ if (_settings.NavRouteFinished())
{
- _host.Log("Nav: Once route re-armed — restarting from point [0]");
- _settings.ActiveNavIndex = 0;
+ _settings.EnableNavigation = false;
+ StopMovement();
+ _host.Log($"Nav: the Once route is finished ({route.Points.Count} pts) — nav stays off; load it again or /ra nav restart to re-run it");
return;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
index 522bdc9..b952f6f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs
@@ -66,6 +66,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra nav save [name] — save the route; a name saves it as .nav");
ChatLine("[RynthAi] /ra nav load — load a nav from NavProfiles (none by that name: a new empty one)");
ChatLine("[RynthAi] /ra nav list — list the navs in NavProfiles");
+ ChatLine("[RynthAi] /ra nav restart — run the loaded route again from its first point (a stop/start keeps its place; a finished Once route stays done)");
ChatLine("[RynthAi] /ra meta load — load a meta from MetaFiles (none by that name: a new blank one)");
ChatLine("[RynthAi] /ra meta new — create a blank meta and load it");
ChatLine("[RynthAi] /ra meta list — list the metas in MetaFiles");
@@ -1148,8 +1149,24 @@ public sealed partial class RynthAiPlugin
var names = _dashboard.NavFileNames();
ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}");
break;
+ case "restart":
+ {
+ // Stopping and starting the macro keeps the route where it was (a finished Once
+ // route stays finished); this is the way to run it again from the top on purpose.
+ var route = _dashboard.Settings.CurrentRoute;
+ if (_navigationEngine == null) { ChatLine("[RynthAi] Navigation engine not ready."); break; }
+ if (!_navigationEngine.RestartRoute())
+ {
+ ChatLine(route != null && route.RouteType == NavRouteType.Follow && route.FollowTargetName.Length > 0
+ ? "[RynthAi] A Follow route has no waypoints to restart."
+ : "[RynthAi] No nav route loaded to restart.");
+ break;
+ }
+ ChatLine($"[RynthAi] Nav route restarted from its first point ({route!.RouteType}, {route.Points.Count} waypoints).");
+ break;
+ }
default:
- ChatLine("[RynthAi] /ra nav save [name] | /ra nav load | /ra nav list");
+ ChatLine("[RynthAi] /ra nav save [name] | /ra nav load | /ra nav list | /ra nav restart");
break;
}
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
index aa288da..aca0908 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs
@@ -1795,7 +1795,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// The hold timer keys off wantBuffRaw, NOT off the decision: keying it
// off the decision would reset it on the bypass tick itself and the
// ~10s retry cadence would silently become "once every 5 minutes".
- if (!wantBuffRaw)
+ // Only while the macro runs (2026-10-28): stopped mid-heal, buffing still "wanted"
+ // a vital recharge nothing acts on, and 5 min later a stopped character was told
+ // buffing was stuck (stance wedge?) with nothing wrong.
+ if (!wantBuffRaw || !settings.IsMacroRunning)
{
_buffingHeldSince = DateTime.MinValue;
_buffComaWarned = false;
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs b/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs
index 403681a..35bcbbd 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/DefSession.cs
@@ -30,6 +30,8 @@ internal sealed class DefSession
public Func ReadRetail = (_, _) => false;
/// An object's name as the client knows it (an item in one of AC's slots that the pack read missed); null = unknown.
public Func ObjectName = _ => null;
+ /// The spells the character knows, with names, A-Z (empty = can't be read now). Spell slots.
+ public Func> KnownSpells = () => Array.Empty();
/// The keys the engine's hotkeys give a chat command ("/rdef use 3"): "F9, Ctrl+1"; "" = none.
public Func CommandKeys = _ => string.Empty;
/// Gives own slot N the key (it comes off whatever had it): the plugin's BindOwnSlotKey. False when it can't.
@@ -70,6 +72,11 @@ internal sealed class DefSession
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
+ if (slot.IsSpell)
+ {
+ Use.Request(UseRequest.Cast(slot.SpellId, slot.SpellLabel, "slot " + slotNumber, Now()));
+ return null;
+ }
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
return null;
@@ -129,12 +136,48 @@ internal sealed class DefSession
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
slot.Item = ItemRef.From(it);
+ slot.SpellId = 0;
+ slot.SpellName = string.Empty;
slot.Mode = UseMode.Auto;
Save();
ItemKind kind = ItemKinds.Classify(it);
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
}
+ ///
+ /// Puts a spell the character knows in a slot (the bar's "Put a spell here...": a search over the
+ /// known spells; the engine can't tell which spell is selected in the game's spellbook). Refused for
+ /// a spell the character doesn't know, when the spellbook can be read.
+ ///
+ public string SetSpell(int slotNumber, uint spellId)
+ {
+ if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
+ if (spellId == 0) return "That isn't a spell.";
+ IReadOnlyList known = KnownSpells();
+ SpellInfo? spell = null;
+ foreach (SpellInfo s in known)
+ if (s.Id == spellId) { spell = s; break; }
+ if (spell == null && known.Count > 0) return $"You don't know {SpellTable.Name(spellId)}, so it can't go in a slot.";
+ SpellInfo info = spell ?? (SpellTable.TryGet(spellId, out SpellInfo t) ? t : new SpellInfo(spellId, SpellTable.Name(spellId), false, false));
+ Data.Slots[slotNumber - 1] = new DefSlot { SpellId = spellId, SpellName = info.Name };
+ Save();
+ return $"Slot {slotNumber}: {info.Name} ({SpellTargeting.Describe(info)} when pressed).";
+ }
+
+ /// /rdef spell <slot> <name>: one of the character's spells by what the player typed.
+ public string SetSpellFromName(int slotNumber, string text)
+ {
+ if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
+ IReadOnlyList known = KnownSpells();
+ if (known.Count == 0) return "Your spells can't be read right now (in the world, on RynthCore with ReadKnownSpells).";
+ List found = SpellTable.Search(known, text, 6, out int total);
+ if (total == 0) return $"You know no spell named '{text}'.";
+ bool exact = found[0].Name.Equals((text ?? string.Empty).Trim(), StringComparison.OrdinalIgnoreCase);
+ if (total > 1 && !exact)
+ return $"{total} of your spells match '{text}': {string.Join(", ", found.ConvertAll(s => s.Name))}{(total > found.Count ? ", ..." : "")}. Type more of the name.";
+ return SetSpell(slotNumber, found[0].Id);
+ }
+
public string ClearSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
@@ -212,6 +255,7 @@ internal sealed class DefSession
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
ItemRef? item = Data.Slots[slotNumber - 1].Item;
+ if (byName && Data.Slots[slotNumber - 1].IsSpell) return $"Slot {slotNumber} holds a spell: bind the slot itself (/rdef bind {slotNumber} ).";
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
@@ -261,12 +305,12 @@ internal sealed class DefSession
return "The Shortcuts bar shows the game's 18 slots first again; RynthDefective's own slots follow them from slot 19 (its slot 1 there).";
var ids = new uint[DefSettings.RetailSlots];
var spells = new uint[DefSettings.RetailSlots];
- int items = ReadRetail(ids, spells) ? BarMapping.RetailItems(ids) : 0;
+ int items = ReadRetail(ids, spells) ? BarMapping.RetailShortcuts(ids, spells) : 0;
CopyOffer = items;
const string what = "The Shortcuts bar is independent of the game's toolbar now: every slot is RynthDefective's own "
+ "(clicks one-touch, keys RynthCore hotkeys). The game's toolbar and its keys are unchanged.";
return items == 0 ? what
- : what + $" The game's 18 slots hold {items} item{(items == 1 ? "" : "s")}: Defective Settings offers to copy them in.";
+ : what + $" The game's 18 slots hold {items} shortcut{(items == 1 ? "" : "s")} (items and spells): Defective Settings offers to copy them in.";
}
/// The player said no to the copy.
@@ -301,8 +345,8 @@ internal sealed class DefSession
if (BindOwnKey(to, key)) keysMoved++; else keysFailed++;
Keys.Invalidate();
- string msg = r.Copied == 0 ? "None of the game's slots held an item to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
- if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (a spell, or an item not in your pack).";
+ string msg = r.Copied == 0 ? "None of the game's slots held an item or a spell to copy." : $"Copied {r.Copied} of the game's slots into this bar (slots 1-18).";
+ if (r.Skipped > 0) msg += $" {r.Skipped} couldn't be (an item not in your pack whose name the game doesn't know).";
if (r.Moved.Count > 0)
msg += $" Your own {r.Moved.Count} slot{(r.Moved.Count == 1 ? "" : "s")} moved after them, to 19 and on"
+ (keysMoved > 0 ? $", {keysMoved} key{(keysMoved == 1 ? "" : "s")} with them" : "") + ".";
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
index 1d37e47..ea4c3d1 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
@@ -2,7 +2,7 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
-internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings }
+internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell }
/// A parsed "/rdef ..." line. Use: (1-based) or (an item name).
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
@@ -10,7 +10,7 @@ internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "",
internal static class DefCommandParser
{
public const string Usage =
- "/rdef [use | set [item name] | clear | bind | unbind | "
+ "/rdef [use | set [item name] | spell | clear | bind | unbind | "
+ "weapons [search] | fav | slots | list | status | settings | panels (the game panel buttons) | selection]";
/// Parses the arguments after "/rdef" (blank = show or hide the bar).
@@ -43,6 +43,13 @@ internal static class DefCommandParser
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
return new DefCommand(DefVerb.Set, slot, tail);
}
+ case "spell":
+ {
+ SplitSlot(rest, out string? slotText, out string tail);
+ if (slotText == null || !TrySlot(slotText, out int slot) || tail.Length == 0)
+ return Fail("Usage: /rdef spell , e.g. /rdef spell 3 Heal Self VI (one of your spells; the slot casts it)");
+ return new DefCommand(DefVerb.Spell, slot, tail);
+ }
case "clear":
{
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
index 3bf6f83..ebf5c74 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
@@ -4,17 +4,29 @@ using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
-/// One slot of the bar: an item (or nothing) and how pressing it uses that item.
+/// One slot of the bar: an item or a spell (or nothing), and how pressing it uses that item.
internal sealed class DefSlot
{
- /// The item the slot holds; null = empty.
+ /// The item the slot holds; null = none.
public ItemRef? Item;
/// How pressing it uses the item. picks by what the item is.
public UseMode Mode = UseMode.Auto;
+ /// The spell the slot casts (2026-10-28); 0 = none. A slot holds an item or a spell, never both.
+ public uint SpellId;
+ /// The spell's name when it was put in the slot (shown when the spell table doesn't know it).
+ public string SpellName = string.Empty;
- public bool Empty => Item == null;
+ public bool Empty => Item == null && SpellId == 0;
+ public bool IsSpell => Item == null && SpellId != 0;
- public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
+ /// What the slot holds, by name: the item's, the spell's, or "".
+ public string Label => Item?.FullName ?? (SpellId != 0 ? SpellLabel : string.Empty);
+
+ /// The spell's name: the table's, else the saved one, else "Spell 1234".
+ public string SpellLabel =>
+ SpellTable.TryGet(SpellId, out SpellInfo s) ? s.Name : SpellName.Length > 0 ? SpellName : SpellTable.Name(SpellId);
+
+ public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode, SpellId = SpellId, SpellName = SpellName };
}
/// The "use as" choice of a slot.
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs
index 611bffe..eee477f 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefStore.cs
@@ -83,6 +83,12 @@ internal sealed class DefStore
slot.Item = ParseRef(e, "item");
int mode = Int(e, "mode", 0);
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
+ // A spell (2026-10-28; a file from before has none): only in a slot without an item.
+ if (slot.Item == null && e.TryGetProperty("spell", out JsonElement sp) && sp.ValueKind == JsonValueKind.Object)
+ {
+ slot.SpellId = UInt(sp, "id");
+ slot.SpellName = slot.SpellId != 0 ? Str(sp, "name") : string.Empty;
+ }
}
}
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
@@ -167,6 +173,13 @@ internal sealed class DefStore
{
w.WriteStartObject();
if (slot.Item != null) WriteRef(w, "item", slot.Item);
+ else if (slot.SpellId != 0)
+ {
+ w.WriteStartObject("spell");
+ w.WriteNumber("id", slot.SpellId);
+ w.WriteString("name", slot.SpellLabel);
+ w.WriteEndObject();
+ }
w.WriteNumber("mode", (int)slot.Mode);
w.WriteEndObject();
}
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/Spells.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/Spells.cs
new file mode 100644
index 0000000..8a4474d
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/Spells.cs
@@ -0,0 +1,188 @@
+// ============================================================================
+// RynthDefective - Model/Spells.cs
+// Spell slots (2026-10-28): what a spell is called, whom it is cast on, and
+// finding one of the character's spells by name. Pure (the tests run it).
+//
+// The engine's plugin API has no spell names or targets and no way to read
+// the spell selected in AC's spellbook or spell bar, so the names and the
+// "self-targeted" / "harmful" flags come from RynthAi's spell table
+// (Combat\SpellData.txt, linked in as RynthInventory and RynthOracle link it:
+// id, name, category, family, words, duration, difficulty, then three flags,
+// the second harmful, the third self-targeted), and the player picks a spell
+// by name from the ones the character knows (ReadKnownSpells).
+// ============================================================================
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+
+namespace RynthCore.Plugin.RynthDefective.Model;
+
+/// One spell: its name, and whether it is cast on yourself only (recalls, Self buffs) or harms its target (war, debuffs).
+internal readonly record struct SpellInfo(uint Id, string Name, bool SelfTargeted, bool Harmful);
+
+internal static class SpellTable
+{
+ private const string ResourceName = "RynthDefective.SpellData.txt";
+ private static Dictionary? _byId;
+
+ public static bool TryGet(uint id, out SpellInfo info)
+ {
+ EnsureLoaded();
+ return _byId!.TryGetValue(id, out info);
+ }
+
+ /// The spell's name, or "Spell 1234" for one the table doesn't have (a server's own).
+ public static string Name(uint id) => TryGet(id, out SpellInfo s) ? s.Name : "Spell " + id.ToString(CultureInfo.InvariantCulture);
+
+ public static int Count
+ {
+ get { EnsureLoaded(); return _byId!.Count; }
+ }
+
+ private static void EnsureLoaded()
+ {
+ if (_byId != null) return;
+ Dictionary map;
+ try
+ {
+ using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
+ if (s == null) map = new Dictionary();
+ else
+ {
+ using var reader = new StreamReader(s, detectEncodingFromByteOrderMarks: true);
+ map = Parse(reader);
+ }
+ }
+ catch
+ {
+ map = new Dictionary(); // a missing table costs names ("Spell 1234") and targets (by the selection)
+ }
+ _byId = map;
+ }
+
+ /// The table's lines (the tests read their own).
+ internal static Dictionary Parse(TextReader reader)
+ {
+ var map = new Dictionary(6400);
+ while (reader.ReadLine() is string line)
+ {
+ string[] c = line.Split('\t');
+ if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id) || id == 0) continue;
+ string name = c[1].Trim();
+ if (name.Length == 0) continue;
+ bool harmful = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
+ bool self = c.Length > 9 && c[9].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
+ map[id] = new SpellInfo(id, name, self, harmful);
+ }
+ return map;
+ }
+
+ /// The character's spells (ids) with names, A-Z; ones the table doesn't name are listed by number.
+ public static SpellInfo[] Known(ReadOnlySpan ids)
+ {
+ var list = new List(ids.Length);
+ var seen = new HashSet();
+ foreach (uint id in ids)
+ {
+ if (id == 0 || !seen.Add(id)) continue;
+ list.Add(TryGet(id, out SpellInfo s) ? s : new SpellInfo(id, Name(id), false, false));
+ }
+ list.Sort((a, b) =>
+ {
+ int c = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
+ return c != 0 ? c : a.Id.CompareTo(b.Id);
+ });
+ return list.ToArray();
+ }
+
+ ///
+ /// The spells in that match what the player typed, best first: the exact
+ /// name, then names starting with it, then names holding every word of it ("heal self", "vi heal").
+ /// At most ; is how many matched. Blank = all of them.
+ ///
+ public static List Search(IReadOnlyList known, string? query, int max, out int total)
+ {
+ string q = (query ?? string.Empty).Trim();
+ string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ var exact = new List();
+ var starts = new List();
+ var contains = new List();
+ foreach (SpellInfo s in known)
+ {
+ if (q.Length == 0) { contains.Add(s); continue; }
+ if (s.Name.Equals(q, StringComparison.OrdinalIgnoreCase)) exact.Add(s);
+ else if (s.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) starts.Add(s);
+ else if (AllWords(s.Name, words)) contains.Add(s);
+ }
+ total = exact.Count + starts.Count + contains.Count;
+ var result = new List(Math.Min(total, Math.Max(0, max)));
+ foreach (List group in new[] { exact, starts, contains })
+ foreach (SpellInfo s in group)
+ {
+ if (result.Count >= max) return result;
+ result.Add(s);
+ }
+ return result;
+ }
+
+ private static bool AllWords(string name, string[] words)
+ {
+ if (words.Length == 0) return false;
+ foreach (string w in words)
+ if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return false;
+ return true;
+ }
+}
+
+/// Whom a spell slot's cast goes to.
+internal enum CastAt { Yourself, Selection, Refused }
+
+internal static class SpellTargeting
+{
+ ///
+ /// The target for casting now. A self-targeted spell (a recall, a Self buff)
+ /// is cast on yourself whatever is selected. Any other spell goes on the selection; with nothing
+ /// selected a beneficial one (Heal Other, a buff, an item spell) is cast on yourself, a harmful one
+ /// (war, void, a debuff) is refused, and so is a harmful one with yourself selected. A spell the table
+ /// doesn't know goes on the selection, else on yourself. says why it was refused.
+ ///
+ public static CastAt Decide(SpellInfo? spell, uint selected, uint player, out uint target, out string why)
+ {
+ why = string.Empty;
+ target = 0;
+ if (player == 0)
+ {
+ why = "the character isn't ready";
+ return CastAt.Refused;
+ }
+ if (spell is { SelfTargeted: true })
+ {
+ target = player;
+ return CastAt.Yourself;
+ }
+ bool harmful = spell is { Harmful: true };
+ if (selected != 0 && selected != player)
+ {
+ target = selected;
+ return CastAt.Selection;
+ }
+ if (harmful)
+ {
+ why = selected == player ? "select a monster first (you have yourself selected)" : "select a target first";
+ return CastAt.Refused;
+ }
+ target = player;
+ return CastAt.Yourself;
+ }
+
+ /// "cast on you" / "cast on the selection (else on you)" / "cast on the selected monster", for the slot's tooltip.
+ public static string Describe(SpellInfo? spell) => spell switch
+ {
+ { SelfTargeted: true } => "cast on you",
+ { Harmful: true } => "cast on the selected target",
+ _ => "cast on the selected target, or on you with nothing selected",
+ };
+}
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/README.md b/Plugins/RynthCore.Plugin.RynthDefective/README.md
index 406a17e..592003e 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/README.md
+++ b/Plugins/RynthCore.Plugin.RynthDefective/README.md
@@ -30,7 +30,7 @@ all three go.
* **Independent of the game's toolbar** (per character, off by default): every slot on the bar is
RynthDefective's own. The game's 18 slots are not on it; clicks are one-touch (a kit on yourself, a
potion used, a weapon wielded) and keys are RynthCore hotkeys (`/rdef use N` for bar slot N). Turning it
- on offers to copy the items in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
+ on offers to copy the items and spells in the game's 18 slots into the bar's slots 1-18 (nothing is copied unless you
say so); your own slots move after them, to 19 and on, with their keys, so the bar looks as it did. The
game's toolbar and its keys are not changed. Turning it off shows the game's 18 first again, RynthDefective's
slot 1 at 19.
@@ -51,6 +51,17 @@ a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
+**Spell slots.** One of RynthDefective's own slots can hold a spell instead: right-click it on the Shortcuts
+bar and choose *Put a spell here...*, then find the spell by name among the ones the character knows (the
+engine can't tell RynthDefective which spell is selected in the game's spellbook, so it is picked there), or
+type `/rdef spell 3 Heal Self VI`. Its picture is the spell's. Pressing it casts the spell, in Magic mode
+(asked for first when the character is in another stance; the cast waits for the stance to settle): a spell
+cast on yourself only (Self buffs, recalls) goes on you; any other on the selection, or on you when nothing is
+selected and the spell is a helpful one (Heal Other, a buff); a war, void or debuff spell with nothing (or
+yourself) selected is refused and says so, as is a spell the character doesn't know. The same one-at-a-time
+and busy rules as items apply. The game's own 18 slots keep the game's own spell handling; copying them into an
+independent bar brings their spells along as spell slots.
+
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
first, `/rdef set 3 Health Potion` the second.
@@ -84,6 +95,13 @@ weapons you wielded are listed first (they are also in their kind's group).
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
waiting one. A request not sent within 6 s gives up and says why.
+* A busy reading that just sits there is a leftover, not a reason to wait: the client's busy count can stay
+ up with nothing in flight after a death, a login or an interrupted action (and RynthAi's "waiting on the
+ server" with it). A count that hasn't moved for 4 s with nothing of RynthDefective's in flight, a gesture
+ that has "animated" for 4 s, or RynthAi's bit on for 5.5 s holds nothing (logged once); only a count above
+ that leftover holds again. RynthDefective never resets the count itself (the engine owns it). If the server
+ really is busy it answers "You're too busy" and the use is tried once more a second later.
+* A key pressed in portal space (a death's too) is not kept for later: it says so.
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
@@ -99,6 +117,7 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef panels | selection show / hide the Game Panels buttons, the Selection window
/rdef use use the slot's item, or the carried item with that name
/rdef set [item name] put the selected item (or the named one) in a slot
+/rdef spell put one of your spells in a slot (it casts it)
/rdef clear empty a slot
/rdef bind bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind
/rdef weapons [search] show the weapon picker
@@ -107,7 +126,7 @@ weapons you wielded are listed first (they are also in their kind's group).
/rdef list | status | help
```
-`/rdef use`, `set`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
+`/rdef use`, `set`, `spell`, `clear`, `bind` take RynthDefective's own slot numbers (1-42): on the Shortcuts bar own
slot N is bar slot 18+N, or bar slot N when the bar is independent of the game's toolbar.
## Settings
@@ -120,8 +139,8 @@ with the slots, favourites and recent weapons in
## Not in 0.1
-Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
-changer (Defective has them).
+Pages, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element changer
+(Defective has them).
## Needs
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj
index bbeb96c..d4e3ba7 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj
+++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthCore.Plugin.RynthDefective.csproj
@@ -31,7 +31,7 @@
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
66
- Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions and weapons by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.
+ Draws the Shortcuts bar (the game's 18 slots and its own), the Game Panels buttons and the Selection window: one-touch kits, potions, weapons and spells by slot or key, and a fast weapon picker. Settings: the bar's gear or /rdef settings.
@@ -42,6 +42,11 @@
+
+
+
+
+
+
diff --git a/Tools/RynthDefective.Tests/SpellTests.cs b/Tools/RynthDefective.Tests/SpellTests.cs
new file mode 100644
index 0000000..a550d24
--- /dev/null
+++ b/Tools/RynthDefective.Tests/SpellTests.cs
@@ -0,0 +1,292 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using RynthCore.Engine.UI.ScriptWindows;
+using RynthCore.Plugin.RynthDefective.Items;
+using RynthCore.Plugin.RynthDefective.Model;
+using RynthCore.Plugin.RynthDefective.Use;
+
+namespace RynthDefective.Tests
+{
+ // Spell slots (2026-10-28): the spell table and search, whom a cast goes to, a slot's cast through
+ // the use controller (Magic mode first, the refusals), putting a spell in a slot, the file.
+ internal static partial class Program
+ {
+ private const uint HealSelf = 6, HealOther = 5, FlameBolt = 27, FrostBolt = 28, LifestoneRecall = 1635;
+
+ private static void SpellTableAndSearch()
+ {
+ Check(SpellTable.Count > 5000, "the table is in the plugin: " + SpellTable.Count);
+ Check(SpellTable.TryGet(HealSelf, out SpellInfo hs) && hs.Name == "Heal Self I" && hs.SelfTargeted && !hs.Harmful, "Heal Self I: on yourself, not harmful");
+ Check(SpellTable.TryGet(HealOther, out SpellInfo ho) && ho.Name == "Heal Other I" && !ho.SelfTargeted && !ho.Harmful, "Heal Other I: targeted, helpful");
+ Check(SpellTable.TryGet(FlameBolt, out SpellInfo fb) && fb.Name == "Flame Bolt I" && fb.Harmful && !fb.SelfTargeted, "Flame Bolt I: harmful");
+ Check(SpellTable.TryGet(LifestoneRecall, out SpellInfo ls) && ls.SelfTargeted, "Lifestone Recall: on yourself");
+ Eq(SpellTable.Name(999_999), "Spell 999999", "a spell the table doesn't have goes by number");
+
+ Dictionary parsed = SpellTable.Parse(new StringReader(
+ "x\ty\n0\tZero\n7\t \n12\tSome Spell\t1\t1\tw\t-1\t1\tFalse\tTrue\tTrue\n13\tShort\n"));
+ Check(parsed.Count == 2 && parsed[12].Harmful && parsed[12].SelfTargeted && !parsed[13].Harmful && !parsed[13].SelfTargeted,
+ "odd lines are skipped; a short line has no flags");
+
+ SpellInfo[] known = SpellTable.Known(new uint[] { FlameBolt, HealSelf, HealOther, HealSelf, 0, 999_999 });
+ Eq(string.Join("|", known.Select(k => k.Name)), "Flame Bolt I|Heal Other I|Heal Self I|Spell 999999", "the character's spells A-Z, once each");
+
+ SpellInfo[] list = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
+ List r = SpellTable.Search(list, "heal self i", 10, out int total);
+ Check(total == 1 && r[0].Id == HealSelf, "the exact name, any case");
+ r = SpellTable.Search(list, "Heal", 10, out total);
+ Eq(string.Join("|", r.Select(x => x.Name)), "Heal Other I|Heal Self I", "names starting with it");
+ r = SpellTable.Search(list, "bolt", 10, out total);
+ Eq(string.Join("|", r.Select(x => x.Name)), "Flame Bolt I|Frost Bolt I", "a word anywhere");
+ r = SpellTable.Search(list, "frost i", 10, out total);
+ Check(total == 1 && r[0].Id == FrostBolt, "every word of it");
+ r = SpellTable.Search(list, "", 3, out total);
+ Check(r.Count == 3 && total == 5, "blank: all of them, at most the limit");
+ SpellTable.Search(list, "zzz", 10, out total);
+ Eq(total, 0, "nothing matches");
+ }
+
+ private static void SpellCastTarget()
+ {
+ var self = new SpellInfo(HealSelf, "Heal Self I", true, false);
+ var helpful = new SpellInfo(HealOther, "Heal Other I", false, false);
+ var harmful = new SpellInfo(FlameBolt, "Flame Bolt I", false, true);
+ const uint mob = 0x8000_1234u;
+
+ Eq(SpellTargeting.Decide(self, mob, Me, out uint t, out _), CastAt.Yourself, "a self spell goes on you, whatever is selected");
+ Eq(t, Me, "on you");
+ Eq(SpellTargeting.Decide(helpful, mob, Me, out t, out _), CastAt.Selection, "a targeted spell goes on the selection");
+ Eq(t, mob, "the selected object");
+ Eq(SpellTargeting.Decide(helpful, 0, Me, out t, out _), CastAt.Yourself, "a helpful one with nothing selected: on you");
+ Eq(t, Me, "on you");
+ Eq(SpellTargeting.Decide(helpful, Me, Me, out t, out _), CastAt.Yourself, "with yourself selected: on you");
+ Eq(SpellTargeting.Decide(harmful, mob, Me, out t, out _), CastAt.Selection, "a harmful one on the selected monster");
+ Eq(t, mob, "the monster");
+ Eq(SpellTargeting.Decide(harmful, 0, Me, out t, out string why), CastAt.Refused, "a harmful one with nothing selected: refused");
+ Check(t == 0 && why.Contains("select a target"), "and says to select one: " + why);
+ Eq(SpellTargeting.Decide(harmful, Me, Me, out _, out why), CastAt.Refused, "a harmful one at yourself: refused");
+ Check(why.Contains("monster"), "says to select a monster: " + why);
+ Eq(SpellTargeting.Decide(null, mob, Me, out t, out _), CastAt.Selection, "a spell the table doesn't know: on the selection");
+ Eq(SpellTargeting.Decide(null, 0, Me, out t, out _), CastAt.Yourself, "else on you");
+ Eq(SpellTargeting.Decide(self, 0, 0, out _, out why), CastAt.Refused, "no character yet: refused");
+ Check(SpellTargeting.Describe(self) == "cast on you" && SpellTargeting.Describe(harmful).Contains("selected target")
+ && SpellTargeting.Describe(helpful).Contains("or on you"), "the tooltip words");
+ }
+
+ private static Harness Caster(params uint[] known)
+ {
+ Harness h = With();
+ h.World.Known = new HashSet(known);
+ return h;
+ }
+
+ private static bool Cast(Harness h, uint spell, string name) =>
+ h.Use.Request(UseRequest.Cast(spell, name, "slot", h.World.NowMs));
+
+ private static void SpellUse()
+ {
+ // From peace: Magic mode first, the cast once the stance has settled, answered by UseDone.
+ Harness h = Caster(HealSelf, HealOther, FlameBolt);
+ Check(Cast(h, HealSelf, "Heal Self I"), "queued");
+ h.Tick();
+ Eq(string.Join("|", h.World.Sent), "mode 8", "at peace: Magic mode first");
+ Check(h.Use.InFlight && h.Said.Last().Contains("Magic mode"), "in flight, and says so: " + string.Join(";", h.Said));
+ h.Tick(500);
+ h.Tick(500);
+ Eq(h.World.Sent.Count, 1, "the stance settles first");
+ h.Tick(400);
+ Eq(string.Join("|", h.World.Sent), "mode 8|cast 6 me", "then the cast, on you");
+ Eq(h.Said.Last(), "Casting Heal Self I...", "status");
+ Check(h.Use.InFlight && h.Use.InvolvesSpell(HealSelf), "waiting for the server's answer");
+ Check(!Cast(h, HealSelf, "Heal Self I") || h.Use.HasPending, "pressed again during the cast: one more, once");
+ Check(!Cast(h, HealSelf, "Heal Self I"), "a held key queues once");
+ h.World.Answer();
+ h.Tick(100);
+ Check(!h.Use.InFlight, "answered");
+ h.Tick(300);
+ Eq(h.World.Sent.Last(), "cast 6 me", "the second press casts again, Magic mode already in place");
+
+ // Already in Magic: cast at once. A harmful spell on the selected monster.
+ h = Caster(FlameBolt);
+ h.World.CombatMode = Stance.Magic;
+ h.World.SelectedId = 0x1234;
+ Cast(h, FlameBolt, "Flame Bolt I");
+ h.Tick();
+ Eq(string.Join("|", h.World.Sent), "cast 27 1234", "in Magic already: cast on the selection at once");
+ Eq(h.Said.Last(), "Casting Flame Bolt I on the selection...", "status");
+
+ // Refusals: nothing selected for a harmful spell, a spell the character doesn't know, no casting at all.
+ h = Caster(FlameBolt);
+ h.World.CombatMode = Stance.Magic;
+ Cast(h, FlameBolt, "Flame Bolt I");
+ h.Tick();
+ Check(h.World.Sent.Count == 0 && !h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, select a target first.",
+ "a war spell with nothing selected: refused, said: " + string.Join(";", h.Warned));
+ h = Caster(HealSelf);
+ Cast(h, FlameBolt, "Flame Bolt I");
+ h.Tick();
+ Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0] == "Flame Bolt I: not cast, you don't know that spell.",
+ "a spell the character doesn't know: refused, no mode change: " + string.Join(";", h.Warned));
+ h = With();
+ h.World.Known = null; // the spellbook can't be read: the server decides
+ h.World.CombatMode = Stance.Magic;
+ Cast(h, HealSelf, "Heal Self I");
+ h.Tick();
+ Eq(string.Join("|", h.World.Sent), "cast 6 me", "spellbook unreadable: cast anyway");
+ h = Caster(HealSelf);
+ h.World.CanCast = false;
+ Cast(h, HealSelf, "Heal Self I");
+ h.Tick();
+ Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("can't cast"), "an engine that can't cast: said");
+ h = Caster(HealSelf);
+ h.World.CombatMode = Stance.Magic;
+ h.World.RefuseSends = true;
+ Cast(h, HealSelf, "Heal Self I");
+ h.Tick();
+ Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't take the cast"), "the client turns the cast away: said, not waited on");
+
+ // Magic mode never comes (a sword in hand): asked once, then said, nothing cast.
+ h = Caster(HealSelf);
+ h.World.CombatMode = Stance.Melee;
+ h.World.ModeRefused = true;
+ Cast(h, HealSelf, "Heal Self I");
+ h.Tick();
+ h.Ticks(3, 1000);
+ Check(h.Use.InFlight && h.Warned.Count == 0, "still waiting for the stance");
+ h.Tick(1100);
+ Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("didn't go into magic mode (melee now)"), "the stance never came: said: " + string.Join(";", h.Warned));
+ Eq(string.Join("|", h.World.Sent), "mode 8", "asked once, never cast");
+
+ // The busy rules hold a cast like a use; "too busy" from the server gets one more try.
+ h = Caster(HealSelf);
+ h.World.CombatMode = Stance.Magic;
+ h.Tick();
+ h.World.BusyCount = 1;
+ Cast(h, HealSelf, "Heal Self I");
+ h.Ticks(2, 1000);
+ Eq(h.World.Sent.Count, 0, "a busy count that just rose holds the cast");
+ h.World.BusyCount = 0;
+ h.Tick(100);
+ Eq(string.Join("|", h.World.Sent), "cast 6 me", "and it goes once the character is free");
+ h.World.Answer(UseController.TooBusyError);
+ h.Tick(100);
+ h.Tick(1100);
+ Eq(string.Join("|", h.World.Sent), "cast 6 me|cast 6 me", "'too busy': cast once more a second later");
+ Check(h.Logged.Any(l => l.Contains("the one more try")), "logged as the retry");
+ h.World.Answer(UseController.TooBusyError);
+ h.Tick(100);
+ Check(h.Warned.Count == 1 && h.Warned[0].Contains("not cast, the server says the character is busy"), "twice: said: " + string.Join(";", h.Warned));
+ }
+
+ private static void SpellSession()
+ {
+ var rig = new Rig("spells");
+ IReadOnlyList known = SpellTable.Known(new uint[] { HealSelf, HealOther, FlameBolt, FrostBolt, LifestoneRecall });
+ rig.S.KnownSpells = () => known;
+
+ string m = rig.S.SetSpell(3, HealSelf);
+ DefSlot s3 = rig.S.Data.Slots[2];
+ Check(s3.IsSpell && s3.SpellId == HealSelf && s3.SpellName == "Heal Self I" && !s3.Empty && s3.Item == null, "slot 3 casts Heal Self I");
+ Check(m.Contains("Slot 3: Heal Self I") && m.Contains("cast on you"), "and says how: " + m);
+ Check(rig.Saves > 0, "saved");
+ Eq(s3.Label, "Heal Self I", "its label");
+
+ m = rig.S.SetSpell(4, 2000);
+ Check(rig.S.Data.Slots[3].Empty && m.Contains("don't know"), "a spell the character doesn't know: refused: " + m);
+ rig.S.KnownSpells = () => Array.Empty();
+ m = rig.S.SetSpell(4, 2000);
+ Check(rig.S.Data.Slots[3].SpellId == 2000, "the spellbook unreadable: taken (the cast is refused then if it must be): " + m);
+ rig.S.KnownSpells = () => known;
+
+ m = rig.S.SetSpellFromName(5, "frost bolt i");
+ Check(rig.S.Data.Slots[4].SpellId == FrostBolt, "by name, any case: " + m);
+ m = rig.S.SetSpellFromName(6, "bolt");
+ Check(rig.S.Data.Slots[5].Empty && m.Contains("2 of your spells match 'bolt'") && m.Contains("Flame Bolt I, Frost Bolt I"), "two match: says which: " + m);
+ m = rig.S.SetSpellFromName(6, "lifestone");
+ Check(rig.S.Data.Slots[5].SpellId == LifestoneRecall, "one starts with it: " + m);
+ m = rig.S.SetSpellFromName(7, "nothing like it");
+ Check(rig.S.Data.Slots[6].Empty && m.Contains("no spell named"), "none: " + m);
+ rig.S.KnownSpells = () => Array.Empty();
+ Check(rig.S.SetSpellFromName(7, "heal").Contains("can't be read"), "by name needs the spellbook");
+ rig.S.KnownSpells = () => known;
+
+ Check(rig.S.UseSlot(3) == null && rig.S.Use.Pending?.Spell == HealSelf && rig.S.Use.Pending.Label == "Heal Self I", "pressing a spell slot asks for its cast");
+ Check(rig.S.UseSlot(8)!.Contains("empty"), "an empty slot says so");
+
+ m = rig.S.BindKey(5, "F9", byName: true);
+ Check(m.Contains("holds a spell") && rig.Chat.Count == 0, "a spell slot binds by slot only: " + m);
+
+ rig.Inv = new List { Kit(10) };
+ rig.S.SetSlot(3, Kit(10));
+ Check(rig.S.Data.Slots[2].Item?.Id == 10 && rig.S.Data.Slots[2].SpellId == 0 && !rig.S.Data.Slots[2].IsSpell, "an item over a spell: the spell is gone");
+ DefSlot clone = rig.S.Data.Slots[4].Clone();
+ Check(clone.SpellId == FrostBolt && clone.SpellName == "Frost Bolt I", "a copy keeps the spell");
+ rig.S.ClearSlot(5);
+ Check(rig.S.Data.Slots[4].Empty, "cleared");
+
+ DefCommand c = DefCommandParser.Parse("spell 3 Heal Self VI");
+ Check(c.Verb == DefVerb.Spell && c.Slot == 3 && c.Text == "Heal Self VI", "/rdef spell 3 Heal Self VI");
+ Check(DefCommandParser.Parse("spell 3").Verb == DefVerb.Error && DefCommandParser.Parse("spell x Heal").Verb == DefVerb.Error
+ && DefCommandParser.Parse("spell").Verb == DefVerb.Error, "a slot and a name are needed");
+ }
+
+ private static void SpellWindow()
+ {
+ // The script-window bar (engines without the Shortcuts bar): a spell slot is a picture, else its initials.
+ Windows w = Stocked("bar-spell");
+ w.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
+ w.DrawBar();
+ ParsedWindow bar = ParseAll(w.Host, "bar with a spell", out _).First(p => p.Key == "RynthDefective/Bar");
+ Eq(CountOps(bar, ScriptOp.ImageButton), 5, "the four items and the spell drawn as pictures");
+ Eq(CountOps(bar, ScriptOp.Button), 3 + 3, "three empty slots and the toolbar");
+ Check(w.BarText.Contains("Heal Self I, a spell.") && w.BarText.Contains("cast on you"), "its tooltip says what it casts");
+
+ Windows t = Stocked("bar-spell-text", icons: false);
+ t.S.Data.Slots[5] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
+ t.DrawBar();
+ ParseAll(t.Host, "bar with a spell, no pictures", out _);
+ Check(t.BarText.Contains("HSI"), "no pictures: its initials");
+
+ // The editor on the spell slot.
+ w.Bar.EditOpen = true;
+ w.Bar.Editor.Select(6);
+ w.DrawBar();
+ ParseAll(w.Host, "editor on a spell slot", out _);
+ Check(w.BarText.Contains("Slot 6: Heal Self I") && w.BarText.Contains("6. Heal Self I") && w.BarText.Contains("A spell: pressing the slot has it cast on you"),
+ "the editor names the spell and how it is cast");
+ Check(!w.BarText.Contains("Pressing it") && w.BarText.Contains("Bind to this slot"), "no item use setting; the key controls stay");
+ }
+
+ private static void SpellStore()
+ {
+ var st = new DefStore(Path.Combine(_temp, "spells"));
+ var d = new DefData();
+ d.Slots[0].Item = ItemRef.From(Kit(0x7100_0001u));
+ d.Slots[1] = new DefSlot { SpellId = HealSelf, SpellName = "Heal Self I" };
+ d.Slots[2] = new DefSlot { SpellId = 987_654, SpellName = "A Server's Own Spell" };
+ Check(st.Save("S", "Spells", d) == null, "saved");
+ DefData r = st.Load("S", "Spells", out string? problem);
+ Check(problem == null, "read");
+ Check(r.Slots[1].IsSpell && r.Slots[1].SpellId == HealSelf && r.Slots[1].Label == "Heal Self I" && r.Slots[1].Mode == UseMode.Auto, "a spell slot comes back");
+ Check(r.Slots[2].SpellId == 987_654 && r.Slots[2].Label == "A Server's Own Spell", "a spell the table doesn't know keeps its saved name");
+ Check(r.Slots[0].Item?.Name == "Peerless Healing Kit" && r.Slots[0].SpellId == 0 && r.Slots[3].Empty, "the item slot and the empty ones as they were");
+ Eq(DefStore.ToJson(r), DefStore.ToJson(d), "writing what was read gives the same file");
+
+ // A file from before spell slots: read unchanged, written back the same.
+ const string old = "{\n \"version\": 1,\n \"slots\": [\n {\n \"item\": {\n \"id\": 5,\n \"name\": \"Kit\"\n },\n \"mode\": 2\n },\n {\n \"mode\": 0\n }\n ]\n}";
+ DefData o = DefStore.Parse(System.Text.Json.JsonDocument.Parse(old).RootElement);
+ Check(o.Slots[0].Item?.Name == "Kit" && o.Slots[0].Mode == UseMode.OnSelf && o.Slots[0].SpellId == 0 && o.Slots.Skip(1).All(x => x.Empty),
+ "an old file: the item, its mode, no spells");
+ Check(!DefStore.ToJson(o).Contains("\"spell\""), "and no spell is written for it");
+
+ // Hand-edited oddities: an item wins over a spell; a spell with no id, or not an object, is nothing.
+ const string odd = "{\"slots\":[{\"item\":{\"id\":5,\"name\":\"Kit\"},\"spell\":{\"id\":6,\"name\":\"Heal Self I\"}},"
+ + "{\"spell\":{\"id\":0,\"name\":\"X\"}},{\"spell\":6},{\"spell\":{\"id\":6}},{\"spell\":{\"id\":-3,\"name\":\"Y\"}}]}";
+ DefData x = DefStore.Parse(System.Text.Json.JsonDocument.Parse(odd).RootElement);
+ Check(x.Slots[0].Item?.Name == "Kit" && x.Slots[0].SpellId == 0, "an item and a spell in one slot: the item");
+ Check(x.Slots[1].Empty && x.Slots[2].Empty && x.Slots[4].Empty, "no id, not an object, a negative id: empty");
+ Check(x.Slots[3].SpellId == HealSelf && x.Slots[3].Label == "Heal Self I", "an id with no name: named by the table");
+ }
+ }
+}
diff --git a/Tools/RynthDefective.Tests/UseTests.cs b/Tools/RynthDefective.Tests/UseTests.cs
index d2643de..063f6a1 100644
--- a/Tools/RynthDefective.Tests/UseTests.cs
+++ b/Tools/RynthDefective.Tests/UseTests.cs
@@ -75,19 +75,38 @@ namespace RynthDefective.Tests
{
Harness h = With(Kit(0x10));
ItemRef kit = ItemRef.From(Kit(0x10));
- h.World.ClientBusy = true;
+ // A count that keeps moving is an action under way (the player's own, another plugin's): it holds.
+ h.Tick(); // the first look: idle
h.Slot(kit);
- h.Ticks(5, 1000);
- Eq(h.World.Sent.Count, 0, "the client's busy count holds it");
+ for (int i = 0; i < 5; i++)
+ {
+ h.World.BusyCount = 1 + (i % 2);
+ h.Tick(1000);
+ }
+ Eq(h.World.Sent.Count, 0, "a moving busy count holds it");
Check(h.Use.HasPending && h.Warned.Count == 0, "still waiting inside the limit");
- h.Ticks(2, 1000);
+ h.World.BusyCount = 2;
+ h.Tick(1000);
Check(!h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0] == "Peerless Healing Kit: not used, the character is busy.", "past the limit it gives up and says why: " + string.Join(";", h.Warned));
+ Eq(h.World.Sent.Count, 0, "and sent nothing");
h = With(Kit(0x10));
h.World.Animating = true;
h.Slot(kit);
- h.Ticks(7, 1000);
- Check(h.Warned.Count == 1 && h.Warned[0].Contains("an animation is playing"), "a gesture holds it: " + string.Join(";", h.Warned));
+ h.Ticks(3, 1000);
+ Eq(h.World.Sent.Count, 0, "a gesture holds it");
+ h.World.Animating = false;
+ h.Tick(100);
+ Eq(h.World.Sent.Count, 1, "and it goes when the gesture ends");
+
+ h = With(Kit(0x10));
+ h.World.Animating = true;
+ h.Slot(kit);
+ h.Ticks(4, 1000);
+ Eq(h.World.Sent.Count, 0, "a gesture 3 s long still holds it");
+ h.Tick(1000);
+ Check(h.World.Sent.Count == 1 && h.Warned.Count == 0, "one that never ends (a stuck motion queue) is let go after 4 s");
+ Eq(h.Logged.Count(l => l.Contains("'animating' for")), 1, "logged once");
h = With(Kit(0x10));
h.World.BotWaitingOnServer = true;
@@ -115,6 +134,168 @@ namespace RynthDefective.Tests
Eq(h.World.Sent.Count, 1, "no RynthAi: nothing to wait for");
}
+ private static BusyFacts Facts(int count = 0, long steady = 0, int leftover = 0, long own = long.MaxValue / 4,
+ bool anim = false, long animMs = 0, bool? bot = null, long botMs = 0) =>
+ new(count, steady, leftover, own, anim, animMs, bot, botMs);
+
+ private static void BusyRuleDecisions()
+ {
+ Eq(BusyRule.Decide(Facts(), out BusyStale st), BusyHold.None, "idle: send");
+ Eq(st, BusyStale.None, "nothing ignored");
+
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000), out st), BusyHold.None, "busy with nothing in flight for longer than the bound: send");
+ Eq(st, BusyStale.Count, "the count was ignored as a leftover");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs), out _), BusyHold.None, "exactly the bound: a leftover");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: BusyRule.CountTrustMs - 1), out _), BusyHold.Busy, "just under it: still trusted");
+
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: 500), out _), BusyHold.Busy, "busy just after our own use: wait");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, own: BusyRule.OwnTrustMs), out _), BusyHold.None, "our own use long enough ago: a leftover");
+
+ Eq(BusyRule.Decide(Facts(anim: true, animMs: 300), out _), BusyHold.Animation, "animating: wait");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, anim: true, animMs: 300), out _), BusyHold.Animation, "animating holds over a leftover count");
+ Eq(BusyRule.Decide(Facts(anim: true, animMs: BusyRule.AnimationMaxMs), out st), BusyHold.None, "a gesture past the bound is a stuck motion queue");
+ Eq(st, BusyStale.Animation, "and ignored as such");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 200, anim: true, animMs: 9000), out _), BusyHold.Busy, "a stuck gesture doesn't hide a fresh count");
+
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 200), out _), BusyHold.Busy, "a count that just changed: wait");
+ Eq(BusyRule.Decide(Facts(count: 3, steady: 200, leftover: 2), out _), BusyHold.Busy, "a count that just rose above the leftover: wait");
+ Eq(BusyRule.Decide(Facts(count: 2, steady: 200, leftover: 2), out st), BusyHold.None, "back at the leftover (our use answered): holds nothing though it just moved");
+ Eq(st, BusyStale.Count, "the leftover is still a leftover");
+ Eq(BusyRule.Decide(Facts(count: 3, steady: 5000, leftover: 2), out st), BusyHold.None, "above the leftover but unchanged for longer than the bound: a bigger leftover");
+ Eq(st, BusyStale.Count, "ignored");
+
+ Eq(BusyRule.Decide(Facts(bot: true, botMs: 1000), out _), BusyHold.Bot, "RynthAi waiting on the server, fresh: wait");
+ Eq(BusyRule.Decide(Facts(bot: true, botMs: BusyRule.BotTrustMs), out st), BusyHold.None, "RynthAi's bit longer than its own action limits: send");
+ Eq(st, BusyStale.Bot, "ignored");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 10_000), out st), BusyHold.None, "RynthAi's copy of a leftover count (its macro off after a death)");
+ Eq(st, BusyStale.Count | BusyStale.Bot, "both ignored");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: BusyRule.CountTrustMs), out _), BusyHold.None, "with a leftover count the bit gets the count's bound");
+ Eq(BusyRule.Decide(Facts(count: 1, steady: 10_000, bot: true, botMs: 1000), out _), BusyHold.Bot, "a bit that just came on holds even over a leftover (RynthAi just sent something)");
+ Eq(BusyRule.Decide(Facts(bot: false, botMs: 50), out _), BusyHold.None, "RynthAi idle");
+ }
+
+ private static void UseStaleBusy()
+ {
+ ItemRef kit = ItemRef.From(Kit(0x10));
+
+ // A login with a count the last session left: nothing moves it.
+ Harness h = With(Kit(0x10));
+ h.World.BusyCount = 2;
+ h.Tick(); // the first look
+ h.Slot(kit);
+ h.Ticks(3, 1000);
+ Eq(h.World.Sent.Count, 0, "right after the first look the count may be real: held");
+ h.Tick(1000);
+ Eq(string.Join("|", h.World.Sent), "useon 10 me", "unchanged for 4 s with nothing in flight: a leftover, the kit goes");
+ Eq(h.Warned.Count, 0, "no warning");
+ Eq(h.Logged.Count(l => l.Contains("busy count has read 2")), 1, "the leftover is logged once");
+ Check(h.Logged.Any(l => l.Contains("left alone")), "and the log says the count isn't touched");
+ Eq(h.Use.Busy.Leftover, 2, "2 is the leftover");
+
+ // Our own kit raises it; the answer brings it back to the leftover; the next kit goes at once.
+ h.World.BusyCount = 3;
+ h.Tick(100);
+ Check(h.Use.InFlight, "our kit is in flight");
+ h.World.BusyCount = 2;
+ h.World.Answer();
+ h.Tick(100);
+ Check(!h.Use.InFlight, "answered");
+ h.Slot(kit);
+ h.Tick(300);
+ Eq(h.World.Sent.Count, 2, "the next kit goes at once: the count is back at the leftover");
+ Eq(h.Logged.Count(l => l.Contains("busy count has read")), 1, "nothing new logged");
+ h.World.Answer();
+ h.Tick(100);
+
+ // Something else raises it above the leftover: real again, until it too sits unchanged.
+ h.World.BusyCount = 3;
+ h.Tick(300);
+ h.Slot(kit);
+ h.Ticks(3, 1000);
+ Eq(h.World.Sent.Count, 2, "a count above the leftover that just rose holds the kit");
+ h.Tick(1000);
+ Eq(h.World.Sent.Count, 3, "until it has sat unchanged for 4 s too");
+ Eq(h.Logged.Count(l => l.Contains("busy count has read 3")), 1, "a bigger leftover gets its own line");
+ h.World.Answer();
+ h.Tick(100);
+ h.World.BusyCount = 0;
+ h.Tick(100);
+ Eq(h.Use.Busy.Leftover, 0, "idle again: no leftover");
+
+ // A death: the count and RynthAi's copy of it sit through the death portal.
+ h = With(Kit(0x10));
+ h.World.BusyCount = 1;
+ h.World.BotWaitingOnServer = true;
+ h.Tick();
+ h.World.InWorld = false;
+ h.Ticks(8, 1000);
+ h.World.InWorld = true;
+ h.Slot(kit);
+ h.Tick(100);
+ Eq(string.Join("|", h.World.Sent), "useon 10 me", "landed: the count and RynthAi's bit that sat through the portal hold nothing");
+ Check(h.Logged.Any(l => l.Contains("RynthAi has read 'waiting on the server'")), "RynthAi's bit is logged as ignored too");
+
+ // A request made in the portal is dropped and said so.
+ h = With(Kit(0x10));
+ h.World.InWorld = false;
+ h.Slot(kit);
+ h.Tick();
+ Check(!h.Use.HasPending && h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("portal space"), "a key in portal space: not used, and says why: " + string.Join(";", h.Warned));
+
+ // A login starts the clocks again (ResetSession), portal space doesn't.
+ h = With(Kit(0x10));
+ h.World.BusyCount = 1;
+ h.Tick();
+ h.Ticks(6, 1000);
+ h.Use.ResetSession();
+ h.Slot(kit);
+ h.Tick(100);
+ Eq(h.World.Sent.Count, 0, "after a login the count is new again: held for now");
+ }
+
+ private static void UseTooBusyRetry()
+ {
+ ItemRef kit = ItemRef.From(Kit(0x10));
+ Harness h = With(Kit(0x10));
+ h.Slot(kit);
+ h.Tick();
+ Eq(h.World.Sent.Count, 1, "sent");
+ h.World.Answer(UseController.TooBusyError);
+ h.Tick(100);
+ Check(!h.Use.InFlight && h.Use.HasPending, "answered 'too busy': queued once more");
+ h.Tick(500);
+ Eq(h.World.Sent.Count, 1, "not straight away");
+ h.Tick(600);
+ Eq(h.World.Sent.Count, 2, "a second later, sent again");
+ Check(h.Logged.Any(l => l.Contains("one more try")), "the log says it is the retry");
+ h.World.Answer(UseController.TooBusyError);
+ h.Tick(100);
+ Check(!h.Use.InFlight && !h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0].Contains("the server says the character is busy"),
+ "busy again: said once, not retried again: " + string.Join(";", h.Warned));
+ h.Ticks(5, 1000);
+ Eq(h.World.Sent.Count, 2, "no loop");
+
+ // Another answer: no retry.
+ h = With(Kit(0x10));
+ h.Slot(kit);
+ h.Tick();
+ h.World.Answer(0x0402);
+ h.Tick(100);
+ h.Ticks(3, 1000);
+ Check(h.World.Sent.Count == 1 && !h.Use.HasPending, "another error is not retried");
+
+ // A newer request while the first was in flight wins over the retry.
+ h = With(Kit(0x10), Potion(0x20));
+ h.Slot(kit);
+ h.Tick();
+ h.Slot(ItemRef.From(Potion(0x20)));
+ h.World.Answer(UseController.TooBusyError);
+ h.Tick(100);
+ Check(h.Use.Pending?.Item?.Name == "Health Potion", "the newest wish wins over the retry");
+ h.Tick(1100);
+ Eq(string.Join("|", h.World.Sent), "useon 10 me|use 20", "the potion goes, the kit isn't sent again");
+ }
+
private static void UseUnanswered()
{
Harness h = With(Potion(0x20));