diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.OneTouch.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.OneTouch.cs new file mode 100644 index 0000000..7fc804c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.OneTouch.cs @@ -0,0 +1,230 @@ +// ============================================================================ +// RynthSuite - Combat/BuffManager.OneTouch.cs +// One-touch heal / stamina / mana (/ra heal, /ra stam, /ra mana; RynthCore's +// "One-touch heal" hotkeys): one press uses the best thing the character has +// for that vital right now, whatever the Heal At / Top Off lines say and with +// the macro on or off. +// +// Nothing new decides what to use: it is the vitals step's own choice. +// Health a healing kit, Heal Self and a health potion (AttemptHealChain), with +// the kit and potion before the spell when a weapon is out (no wand swap +// at low health, as the emergency step); Stamina to Health Self last, when +// its feature is on (Stamina To Health At over 0) and stamina is over its +// floor. The kit Kit Min Success skipped is still the last resort. +// Stamina a stamina kit, a listed potion (out of Magic stance), Revitalize Self, +// then any stamina potion (AttemptStaminaChain). +// Mana Stamina to Mana Self or a mana potion; with stamina at the floor, stamina +// first (AttemptManaRefill). +// A vital already full says so and does nothing. Kits and potions need Use Kits in +// Magic Mode / Use Potions as always. +// +// Busy: the request waits (up to OneTouchWaitMs) for the same things the vitals step +// waits for: a kit or cast in flight, the server answering the last action, a gesture, +// a busy count. A heal is let through like the emergency heals are (the pacer's heal +// rules, a leftover busy count cleared, no stance settle, and a kit or potion - not a +// spell - while a buff cast is still pending). Past OneTouchWaitMs it says why and stops. +// +// Requested from any thread (chat commands run on AC's thread); the pass runs on the +// next heartbeat (pump thread). Pressing the key again while a request waits does not +// queue a second one. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Plugin.RynthAi; + +internal enum OneTouchVital { Health = 0, Stamina = 1, Mana = 2 } + +public partial class BuffManager +{ + /// The longest a request waits for the character to be free, or for a stance step (the + /// wand swap, peace for a kit), before it gives up and says why. + internal const long OneTouchWaitMs = 8000; + + private readonly long[] _oneTouchAt = new long[3]; // OneTouchVital -> Environment.TickCount64 of the request, 0 = none + + // True on the pump thread while a one-touch heal is being paced or attempted: the heal rules of the + // pacer (HealNeedNow) and the stance settle (HealIsUrgent) apply whatever health is. + private bool _oneTouchHealthScope; + + /// Asks for one pass for on the next heartbeat. Any thread. + internal void RequestOneTouch(OneTouchVital vital) + { + // A request already waiting keeps its time: pressing again is not a second heal. + Interlocked.CompareExchange(ref _oneTouchAt[(int)vital], Math.Max(1, Environment.TickCount64), 0); + } + + /// A request for is waiting to run. + internal bool OneTouchPending(OneTouchVital vital) => Volatile.Read(ref _oneTouchAt[(int)vital]) != 0; + + private static string OneTouchName(OneTouchVital v) => v switch + { + OneTouchVital.Health => "Heal", + OneTouchVital.Stamina => "Stamina", + _ => "Mana", + }; + + private enum OneTouchStep { Sent, InProgress, Nothing } + + /// HeartbeatCore, every tick (macro on or off): the waiting requests, health first, one per tick. + private void TickOneTouchRequest() + { + for (int i = 0; i < _oneTouchAt.Length; i++) + { + long at = Volatile.Read(ref _oneTouchAt[i]); + if (at == 0) continue; + var vital = (OneTouchVital)i; + string name = OneTouchName(vital); + long waited = Environment.TickCount64 - at; + + ReleaseStaleVitalCastMacroOff(); + string busy = OneTouchBusyReason(vital, out bool itemsOnly); + string why = busy.Length > 0 ? $"the character stayed busy ({busy})" : ""; + if (busy.Length == 0) + { + OneTouchStep step = OneTouchStepNow(vital, itemsOnly, out string said); + if (step != OneTouchStep.InProgress) + { + Interlocked.Exchange(ref _oneTouchAt[i], 0); + _host.WriteToChat($"[RynthAi] {name}: {said}", 1); + return; + } + why = said; + } + if (waited < OneTouchWaitMs) return; // the lower vitals wait too: one action at a time + Interlocked.Exchange(ref _oneTouchAt[i], 0); + _host.WriteToChat($"[RynthAi] {name}: not done, {why}.", 1); + _host.Log($"[RynthAi] One-touch {name.ToLowerInvariant()}: gave up after {waited} ms: {why}"); + return; + } + } + + /// With the macro off nothing else releases a vital cast the server never confirmed + /// (PendingGiveUpReached, as the macro's tick does); without that the next press would wait on it. + private void ReleaseStaleVitalCastMacroOff() + { + if (_settings.IsMacroRunning || _pendingSpellId == 0 || _pendingSpellId != _pendingVitalSpellId) return; + if (!PendingGiveUpReached(SelfBuffGiveUpMs)) return; + _host.Log($"[BuffDiag] vital cast id={_pendingSpellId} not confirmed by chat ({GiveUpWhy(SelfBuffGiveUpMs)}) — released, no strike (macro off)."); + _pendingSpellId = 0; + _pendingVitalSpellId = 0; + _onCastResolved?.Invoke("vital cast unconfirmed"); + } + + /// + /// What holds a pass back right now ("" = nothing). : a buff cast is + /// still pending but the server has finished it, so a health kit or potion may go and a spell may not + /// (it would replace the pending cast; TryEmergencyHealWhilePending's rule). + /// + internal string OneTouchBusyReason(OneTouchVital vital, out bool itemsOnly) + { + itemsOnly = false; + if (_vitals.MaxHealth <= 0) return "vitals not read yet"; + if (KitPending()) return "a kit is in flight"; + if (_pendingSpellId != 0) + { + if (vital != OneTouchVital.Health || _pendingSpellId == _pendingVitalSpellId) return "a cast is in flight"; + if (IsAwaitingCastResolution()) return "the server hasn't finished the last cast"; + itemsOnly = true; + } + if (vital != OneTouchVital.Health && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < _settings.SpellCastIntervalMs) + return "inside the spell interval"; + + bool pacerAllows; + string pacerWhy; + _oneTouchHealthScope = vital == OneTouchVital.Health; + try { pacerAllows = PacerAllows(out pacerWhy); } + finally { _oneTouchHealthScope = false; } + if (!pacerAllows) return "server answering the last action: " + pacerWhy; + if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return "a gesture is animating"; + // A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal), or one the + // pacer let a heal ahead of; the other vitals wait for the count to drop. + if (BusyCount > 0 && !_pacerLetHealAhead && (vital != OneTouchVital.Health || BusyHoldsHeal())) + return $"busy count {BusyCount}"; + return ""; + } + + /// + /// One attempt for (pump thread; internal for the host tests). Sent: something + /// went out, or the vital is full or has no option at all ( says which); InProgress: + /// a step toward it is in flight (peace for the kit, the wand swap, a spell that has to wait for a + /// pending cast) and the next tick tries again. + /// + private OneTouchStep OneTouchStepNow(OneTouchVital vital, bool itemsOnly, out string said) + { + int hp = _vitals.HealthPct, st = _vitals.StaminaPct, mn = _vitals.ManaPct; + string vitals = $"health {hp}%, stamina {st}%, mana {mn}%"; + var before = (kit: _kitUsedAt, potion: _lastPotionAt, spell: _pendingSpellId); + bool handled; + bool staminaFirst = false; + string noWhy; + _vitalWhy = ""; + _healWaitKind = ""; + _oneTouchHealthScope = vital == OneTouchVital.Health; + try + { + switch (vital) + { + case OneTouchVital.Health: + if (_vitals.CurrentHealth >= _vitals.MaxHealth) { said = $"health is full ({vitals})."; return OneTouchStep.Nothing; } + handled = AttemptHealChain(itemsBeforeSpell: CurrentCombatMode != CombatMode.Magic, allowSpell: !itemsOnly, + out string kitWhy, out string spellWhy, out string potionWhy); + string stamToHealthWhy = "not on (Stamina To Health At is 0)"; + if (!handled && _settings.StaminaToHealthAt > 0 && !itemsOnly) + { + if (st > _settings.StaminaToHealthMinStamina) + { + _vitalWhy = ""; + handled = AttemptVitalCast("Stamina to Health Self"); + stamToHealthWhy = Why(_vitalWhy); + } + else stamToHealthWhy = $"stamina {st}% is not over {_settings.StaminaToHealthMinStamina}%"; + } + noWhy = $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}; Stamina to Health: {stamToHealthWhy}"; + break; + case OneTouchVital.Stamina: + if (_vitals.CurrentStamina >= _vitals.MaxStamina) { said = $"stamina is full ({vitals})."; return OneTouchStep.Nothing; } + handled = AttemptStaminaChain(); + noWhy = Why(_vitalWhy); + break; + default: + if (_vitals.CurrentMana >= _vitals.MaxMana) { said = $"mana is full ({vitals})."; return OneTouchStep.Nothing; } + handled = AttemptManaRefill(st, out staminaFirst); + noWhy = Why(_vitalWhy); + break; + } + } + finally { _oneTouchHealthScope = false; } + + string name = OneTouchName(vital).ToLowerInvariant(); + if (!handled) + { + // A spell held back for a pending buff cast: that cast resolves in a moment, then the spell may go. + if (itemsOnly) + { + said = "waiting for the pending cast to end (" + noWhy + ")"; + return OneTouchStep.InProgress; + } + said = $"nothing could {(vital == OneTouchVital.Health ? "heal" : vital == OneTouchVital.Stamina ? "restore stamina" : "restore mana")} " + + $"({vitals}): {noWhy}."; + _host.Log($"[RynthAi] One-touch {name}: {said}"); + return OneTouchStep.Nothing; + } + + string how; + if (_kitUsedAt != before.kit) how = vital == OneTouchVital.Health ? "using a healing kit" : "using a stamina kit"; + else if (_lastPotionAt != before.potion) how = "drinking a potion"; + else if (_pendingSpellId != 0 && _pendingSpellId == _pendingVitalSpellId && _pendingSpellId != before.spell) + how = "casting " + (SpellTableStub.GetById(_pendingSpellId)?.Name ?? "a spell"); + else + { + // Handled without sending: a stance step is in flight (_healWaitKind says which). + said = _healWaitKind.Length > 0 ? _healWaitKind : "getting ready"; + return OneTouchStep.InProgress; + } + said = how + (staminaFirst ? " (stamina first, for Stamina to Mana)" : "") + $" ({vitals})."; + _host.Log($"[RynthAi] One-touch {name}: {said}"); + return OneTouchStep.Sent; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 27e4f6b..919a873 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1248,6 +1248,7 @@ public partial class BuffManager : IDisposable // A recall the HP failsafe asked for goes out after the macro stop (BuffManager.HpFailsafe.cs). TickFailsafeRecall(); TickRechargeRequest(); // /ra recharge: one vitals pass, macro on or off (BuffManager.Recharge.cs) + TickOneTouchRequest(); // /ra heal, /ra stam, /ra mana: one-touch recharge, macro on or off (BuffManager.OneTouch.cs) if (!_settings.IsMacroRunning) return; @@ -1887,31 +1888,16 @@ public partial class BuffManager : IDisposable _isHealingSelf = true; return true; } - _vitalWhy = ""; - bool healed = AttemptHealthKitUse(); - string kitWhy = _vitalWhy; - if (!healed) { _vitalWhy = ""; healed = AttemptVitalCast("Heal Self"); } - string spellWhy = _vitalWhy; - if (!healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); } - // Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all - // (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later). - if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal)) - { - string potionWhy = _vitalWhy; - _vitalWhy = ""; - healed = AttemptHealthKitUse(ignoreMinSuccess: true); - if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %."); - else _vitalWhy = potionWhy; - } + bool healed = AttemptHealChain(itemsBeforeSpell: false, allowSpell: true, out string kitWhy, out string spellWhy, out string potionWhy); if (healed) { _isHealingSelf = true; return true; } _healUnavailableUntil = DateTime.Now.AddMilliseconds(HealUnavailableMs); - Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(_vitalWhy)}"); + Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}"); LogNoHeal($"health {curHealthPct}% < {(inCombat ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " + - $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(_vitalWhy)}"); + $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}"); } else if (!inCombat && curHealthPct < _settings.HealAt) { @@ -1930,17 +1916,9 @@ public partial class BuffManager : IDisposable if (manaLow) { _vitalWhy = ""; - if ((curStamPct > StaminaToManaFloorPct() && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion")) + if (AttemptManaRefill(curStamPct, out bool refilledStamina)) { - _isRechargingMana = true; - return true; - } - // Stamina too low for Stamina to Mana (StaminaToManaFloorPct: Re-stam At, at least 15): a - // stamina kit, Revitalize or a potion first. - if (curStamPct <= StaminaToManaFloorPct() && TopStaminaToManaId() != 0 - && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina"))) - { - _isRechargingStamina = true; + if (refilledStamina) _isRechargingStamina = true; else _isRechargingMana = true; return true; } // Mana can't pay for any Stamina to Mana and nothing else refilled it: a caster's @@ -1968,27 +1946,90 @@ public partial class BuffManager : IDisposable // for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina // potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize // on top of it. In Magic stance (a caster) Revitalize stays first. - bool potionFirst = CurrentCombatMode != CombatMode.Magic; - if (curStamPct < stamThreshold) + if (curStamPct < stamThreshold && AttemptStaminaChain()) { - bool potionJustDrunk = potionFirst && _settings.UsePotions - && (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500 - && HasListedPotion("StaminaPotion", "Stamina"); - if (!potionJustDrunk - && (AttemptStaminaKitUse() - || (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina")) - || AttemptVitalCast("Revitalize Self") - || AttemptPotion("StaminaPotion", "Stamina"))) - { - _isRechargingStamina = true; - if (_restamRun) _restamRunCasts++; - return true; - } + _isRechargingStamina = true; + if (_restamRun) _restamRunCasts++; + return true; } return false; } + /// + /// The heal chain of the vitals step (CheckVitals, and the one-touch heal): a kit, Heal Self and a + /// potion, or with the kit and potion before the spell (no wand swap + /// first, as the emergency step does), then the kit Kit Min Success skipped as the last resort. + /// false: no cast (one is pending and a Heal Self would replace it). + /// True also while a stance step (peace for the kit, the wand swap) is in flight; the why strings + /// say what each option did when nothing healed. + /// + private bool AttemptHealChain(bool itemsBeforeSpell, bool allowSpell, out string kitWhy, out string spellWhy, out string potionWhy) + { + spellWhy = ""; + string potWhy = ""; + _vitalWhy = ""; + bool healed = AttemptHealthKitUse(); + kitWhy = _vitalWhy; + if (itemsBeforeSpell && !healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); potWhy = _vitalWhy; } + if (!healed) + { + _vitalWhy = ""; + healed = allowSpell ? AttemptVitalCast("Heal Self") : VitalNo("a cast is pending"); + spellWhy = _vitalWhy; + } + if (!itemsBeforeSpell && !healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); potWhy = _vitalWhy; } + // Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all + // (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later). + if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal)) + { + _vitalWhy = ""; + healed = AttemptHealthKitUse(ignoreMinSuccess: true); + if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %."); + } + if (!healed) _vitalWhy = potWhy; + potionWhy = potWhy; + return healed; + } + + /// + /// The mana step: Stamina to Mana Self or a mana potion; with stamina at or under the Stamina to Mana + /// floor, stamina is refilled first (kit, Revitalize, potion) so Stamina to Mana can run next. + /// : it was stamina that was started, not mana. + /// + private bool AttemptManaRefill(int curStamPct, out bool refilledStamina) + { + refilledStamina = false; + if ((curStamPct > StaminaToManaFloorPct() && AttemptVitalCast("Stamina to Mana Self")) || AttemptPotion("ManaPotion")) + return true; + // Stamina too low for Stamina to Mana (StaminaToManaFloorPct: Re-stam At, at least 15): a + // stamina kit, Revitalize or a potion first. + if (curStamPct <= StaminaToManaFloorPct() && TopStaminaToManaId() != 0 + && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self") || AttemptPotion("StaminaPotion", "Stamina"))) + { + refilledStamina = true; + return true; + } + return false; + } + + /// + /// The stamina step: a kit, a listed potion first out of Magic stance, Revitalize, then any potion + /// (the reasons are in the comment above CheckVitals' stamina line). + /// + private bool AttemptStaminaChain() + { + bool potionFirst = CurrentCombatMode != CombatMode.Magic; + bool potionJustDrunk = potionFirst && _settings.UsePotions + && (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500 + && HasListedPotion("StaminaPotion", "Stamina"); + return !potionJustDrunk + && (AttemptStaminaKitUse() + || (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina")) + || AttemptVitalCast("Revitalize Self") + || AttemptPotion("StaminaPotion", "Stamina")); + } + // Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina // reaches Re-stam To; one Revitalize often doesn't get far. Capped so a recharge that // never gains can't loop: it ends after RestamRunMaxCasts. @@ -2165,7 +2206,7 @@ public partial class BuffManager : IDisposable return VitalNo(recoveryWhy); if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); - bool urgentHeal = label == LabelHealing && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct); + bool urgentHeal = label == LabelHealing && (_oneTouchHealthScope || HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct)); if (!EnsureMagicMode(urgentHeal: urgentHeal)) { if (!_magicModeBlocked) { _healWaitKind = "wand swap / Magic stance"; return true; } // a swap step is in flight: yield the tick @@ -4468,7 +4509,8 @@ public partial class BuffManager : IDisposable int hp = _vitals.HealthPct; int emergencyAt = _settings.EmergencyHealAt; if (emergencyAt > 0 && hp <= emergencyAt) return HealNeed.Emergency; - return HealthUnderAnyLine(hp, _vitals.StaminaPct) ? HealNeed.Heal : HealNeed.None; + // A one-touch heal the player asked for counts as a heal whatever the lines say (BuffManager.OneTouch.cs). + return HealthUnderAnyLine(hp, _vitals.StaminaPct) || _oneTouchHealthScope ? HealNeed.Heal : HealNeed.None; } /// Times the vitals/buff step waited for the server's answer (tests, status). diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 5d241b8..34b73fa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -4317,6 +4317,7 @@ public partial class CombatManager : IDisposable { uint pick = _damageStore.GetManualWeapon(wcid); if (pick == 0) { pick = _damageStore.GetDefaultWeapon(); fixedSource = "Damage tab default"; fixedIsDefault = true; } + if (pick != 0 && SkillTooLowFor((int)pick)) pick = 0; // logged when it was refused if (pick != 0 && !listed.Any(c => c.Id == (int)pick)) { NoteUnlisted((int)pick, fixedSource); pick = 0; } fixedId = (int)pick; uint best = _damageStore.GetBestWeapon(wcid); @@ -4341,7 +4342,15 @@ public partial class CombatManager : IDisposable double minGain = _settings.WeaponSwapMinGainPct > 0 && SwapHoldsAllowed(InHandWeaponId()) ? _settings.WeaponSwapMinGainPct / 100.0 : 0; return WeaponPlanner.Choose(listed, ruleElement, weak, e => CanCastElement(e, rule), - fixedId, fixedSource, learnedId, ctype, fixedIsDefault, minGain); + fixedId, fixedSource, learnedId, ctype, fixedIsDefault, minGain, PreferredDamageFor(rule)); + } + + /// The preferred damage type for a fight: the rule's own, else (Auto) the Default row's. + internal string PreferredDamageFor(MonsterRule? rule) + { + if (rule != null && DamageStyles.Parse(rule.PreferredDamage) != DamageStyle.Auto) return rule.PreferredDamage; + var def = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + return def?.PreferredDamage ?? ""; } // PropertyInt 166 SlayerCreatureType, PropertyFloat 138 SlayerDamageBonus (ACE.Entity). @@ -4457,6 +4466,7 @@ public partial class CombatManager : IDisposable continue; } if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List()).Add(r.Id); continue; } + if (r.Id != inHand && SkillTooLowFor(r.Id)) continue; if (list.Any(c => c.Id == r.Id)) continue; if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) continue; // listed arrows are the ammo choice, never a weapon to wield if (IsShieldItem(wo)) continue; // listed shields are the off hand's (CombatManager.Offhand.cs) @@ -4488,7 +4498,10 @@ public partial class CombatManager : IDisposable { if (WorldObjectCache.IsAmmo(wo)) continue; // The off hand (a dual-wielded weapon in the Shield slot) is not the weapon in hand. - if ((wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0) continue; + // CurrentWieldedLocation can read 0: the weenie's own wielder record says where it is. + // Drakkon dual wielding two Hand Wraps (2026-10-16) had the off-hand pair read as the + // weapon in hand, and the swaps went from it ("Frost Hand Wraps -> Nodachi"). + if ((WieldedSlotOf(wo) & OffhandRules.ShieldSlot) != 0) continue; bool weapon = wo.ObjectClass == AcObjectClass.MeleeWeapon || wo.ObjectClass == AcObjectClass.MissileWeapon || IsWandObject(wo); @@ -4502,6 +4515,21 @@ public partial class CombatManager : IDisposable return found; } + /// Where the player wields : CurrentWieldedLocation, else the weenie's wielder record (0 = not known). + private int WieldedSlotOf(WorldObject wo) + { + int slot = wo.Values(LongValueKey.CurrentWieldedLocation, 0); + if (slot != 0 || !_host.HasGetObjectWielderInfo) return slot; + try + { + uint pid = _host.GetPlayerId(); + if (pid != 0 && _host.TryGetObjectWielderInfo(unchecked((uint)wo.Id), out uint wielder, out uint loc) && wielder == pid) + return unchecked((int)loc); + } + catch { } + return 0; + } + /// The combat mode a weapon puts the character in (0 = unknown). private int WeaponKind(int id) { @@ -4561,6 +4589,40 @@ public partial class CombatManager : IDisposable // Server replies seen when the last combat wield was sent (UseDone / WeenieError sequence). private int _swapUseDoneSeq, _swapWeenieSeq; + // ACE's WeenieError SkillTooLow: the character can't wield the weapon (its wield requirement). + internal const uint SkillTooLowErr = 0x0468; + /// A weapon refused with SkillTooLow is left out of the choice this long (a buff or a + /// skill raise may let it in later). + internal const double SkillTooLowSkipMin = 30; + private readonly Dictionary _skillTooLowUntil = new(); + + /// + /// True while sits out a SkillTooLow refusal. Drakkon (2026-10-16) was + /// sent to a Nodachi he lacked the skill for whenever a monster was weak to Slash: the off hand + /// went into the pack for it, three wields were refused, and it began again two minutes later. + /// + internal bool SkillTooLowFor(int id) + { + if (!_skillTooLowUntil.TryGetValue(id, out DateTime until)) return false; + if (DateTime.Now < until) return true; + _skillTooLowUntil.Remove(id); + return false; + } + + private void NoteSkillTooLow(int id) + { + if (id == 0) return; + bool first = !_skillTooLowUntil.ContainsKey(id); + _skillTooLowUntil[id] = DateTime.Now.AddMinutes(SkillTooLowSkipMin); + _planCache = null; + if (first) + { + string msg = $"0x{(uint)id:X8} '{WeaponName(id)}': the server says your skill is too low to wield it - left out of the weapon choice for {SkillTooLowSkipMin:0} min"; + _host.Log($"[EquipDiag] {msg}"); + _host.WriteToChat($"[RynthAi] {msg}.", 1); + } + } + /// /// Asks the swap tracker about with /// in hand, after folding in a server refusal of the wield in flight. Logs a give-up once. @@ -4701,10 +4763,11 @@ public partial class CombatManager : IDisposable { int pending = tracker.PendingId; if (pending == 0) return; - switch (ServerAnswerSinceSend()) + switch (ServerAnswerSinceSend(out uint err)) { case WieldAnswer.Refused: tracker.Refused(now, WeaponName); + if (err == SkillTooLowErr && ReferenceEquals(tracker, SwapTracker)) NoteSkillTooLow(pending); break; case WieldAnswer.Busy: if (tracker.Busy(now, WeaponName)) @@ -4723,20 +4786,21 @@ public partial class CombatManager : IDisposable /// keeps only the last record, so the 0x1D is usually read as "error 0" (flight recorder /// 2026-10-15 00:44:23-31: three of these, read as no answer, cost all 3 tries). /// - private WieldAnswer ServerAnswerSinceSend() + private WieldAnswer ServerAnswerSinceSend(out uint err) { + err = 0; if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out uint wErr, out uint wEvt, out _) && wSeq != _swapWeenieSeq) { _swapWeenieSeq = wSeq; if (wErr == ActionPacer.TooBusyErr || (wEvt == InventorySaveFailedEvent && wErr == 0)) return WieldAnswer.Busy; - if (wErr != 0) return WieldAnswer.Refused; + if (wErr != 0) { err = wErr; return WieldAnswer.Refused; } } if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out uint uErr) && uSeq != _swapUseDoneSeq) { _swapUseDoneSeq = uSeq; if (uErr == ActionPacer.TooBusyErr) return WieldAnswer.Busy; - if (uErr != 0) return WieldAnswer.Refused; + if (uErr != 0) { err = uErr; return WieldAnswer.Refused; } } return WieldAnswer.None; } @@ -4855,7 +4919,7 @@ public partial class CombatManager : IDisposable // Dual wield: the chosen weapon already swings in the off hand, beside another listed // one-handed weapon in the main hand. Fight with both rather than moving it across. if (inHand != 0 && inHand != targetWeaponId - && (weaponObj.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0 + && (WieldedSlotOf(weaponObj) & OffhandRules.ShieldSlot) != 0 // the slot can read 0: WieldedSlotOf asks the weenie && _worldFilter[inHand] is WorldObject mainObj && MainKindOf(mainObj) == MainHandKind.OneHandedMelee && _settings.ItemRules.Any(r => r.Id == inHand)) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs index 40b580f..0c76b6e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponList.cs @@ -134,13 +134,14 @@ internal static class WeaponList /// "Unknown" for an element not known yet. The panel sends the copies back on an edit; /// maps them onto the saved entries by id. /// - public static List ForDisplay(IEnumerable rules, Func fullName) + public static List ForDisplay(IEnumerable rules, Func fullName, Func? kind = null) { var list = new List(); foreach (var r in rules) list.Add(new ItemRule { Id = r.Id, Name = fullName(r), Action = r.Action, KeepBuffed = r.KeepBuffed, + Kind = kind?.Invoke(r) ?? "", // A shield shows "Shield" in the element column (it has no element). Element = IsShieldRule(r) ? ShieldAction : r.Element.Length > 0 ? r.Element : UnknownLabel, ElementSource = r.ElementSource, diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs index e4d5da9..344a389 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WeaponPlanner.cs @@ -19,6 +19,48 @@ internal sealed record WeaponCandidate(int Id, string Name, int Kind, string Ele /// debuff with, and why. internal readonly record struct WeaponPlan(int WeaponId, string Element, string Source); +/// The kind of damage a character prefers to fight with (a Monsters rule's PreferredDamage). +internal enum DamageStyle { Auto, Melee, Missile, War, Void } + +internal static class DamageStyles +{ + /// The names the Damage panel offers, in order. + public static readonly string[] Names = { "Auto", "Melee", "Missile", "War Magic", "Void Magic" }; + + /// Tolerant of case, spaces and the short forms ("war", "void"); anything unknown is Auto. + public static DamageStyle Parse(string? text) + { + string t = (text ?? "").Replace(" ", "").Replace("_", "").Replace("-", ""); + if (t.Equals("Melee", StringComparison.OrdinalIgnoreCase)) return DamageStyle.Melee; + if (t.Equals("Missile", StringComparison.OrdinalIgnoreCase)) return DamageStyle.Missile; + if (t.Equals("War", StringComparison.OrdinalIgnoreCase) || t.Equals("WarMagic", StringComparison.OrdinalIgnoreCase)) return DamageStyle.War; + if (t.Equals("Void", StringComparison.OrdinalIgnoreCase) || t.Equals("VoidMagic", StringComparison.OrdinalIgnoreCase)) return DamageStyle.Void; + return DamageStyle.Auto; + } + + public static string Name(DamageStyle s) => Names[(int)s]; + + private static bool IsNether(string e) => e.Equals("Nether", StringComparison.OrdinalIgnoreCase); + + /// A weapon belongs to a style by its kind; a caster by its element (Nether = Void, anything else, or none, = War). + public static bool Matches(WeaponCandidate c, DamageStyle s) => s switch + { + DamageStyle.Melee => c.Kind == CombatMode.Melee, + DamageStyle.Missile => c.Kind == CombatMode.Missile, + DamageStyle.War => c.Kind == CombatMode.Magic && !IsNether(c.Element), + DamageStyle.Void => c.Kind == CombatMode.Magic && IsNether(c.Element), + _ => true, + }; + + /// The cast test with the style's school applied: War never casts Nether, Void casts nothing else. + public static Func Restrict(Func canCast, DamageStyle s) => s switch + { + DamageStyle.War => e => !IsNether(e) && canCast(e), + DamageStyle.Void => e => IsNether(e) && canCast(e), + _ => canCast, + }; +} + /// /// The element-and-weapon rule, pure (no host). The weakness decides the weapon, never the /// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always @@ -54,6 +96,12 @@ internal readonly record struct WeaponPlan(int WeaponId, string Element, string /// use its element; nothing known at all: Slash (or the first element the character can cast). /// "Main kind" = the kind of the first usable weapon in the list, so a bow character with a /// buff wand listed isn't switched to magic, and a melee character isn't swapped to a wand. +/// A preferred damage type (a Monsters rule's PreferredDamage: Melee, Missile, War Magic, +/// Void Magic) replaces that: the pool is the listed weapons of that style, for a character +/// who uses two kinds and wants to choose. With none listed (or none the character can use, +/// e.g. Void without Void Magic) it falls back to Auto, the main kind, rather than not fighting. +/// The monster's own Damage tab weapon (step 1) still wins; the DEFAULT row's weapon only when +/// it is of the preferred style; War Magic never casts Nether and Void Magic nothing else. /// internal static class WeaponPlanner { @@ -79,8 +127,29 @@ internal static class WeaponPlanner int learnedBestId = 0, int creatureType = 0, bool fixedIsDefault = false, - double minSwapGain = 0) + double minSwapGain = 0, + string? preferredDamage = null) { + var plan = ChooseCore(listed, ruleElement, weak, canCast, fixedWeaponId, fixedSource, learnedBestId, creatureType, + fixedIsDefault, minSwapGain, DamageStyles.Parse(preferredDamage), out var applied); + return applied == DamageStyle.Auto ? plan : plan with { Source = plan.Source + ", prefers " + DamageStyles.Name(applied) }; + } + + private static WeaponPlan ChooseCore( + IReadOnlyList listed, + string? ruleElement, + CreatureWeakness.Ranking? weak, + Func canCast, + int fixedWeaponId, + string fixedSource, + int learnedBestId, + int creatureType, + bool fixedIsDefault, + double minSwapGain, + DamageStyle style, + out DamageStyle applied) + { + applied = DamageStyle.Auto; string rule = WeaponElements.Normalize(ruleElement); bool ruleSet = rule.Length > 0; WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null; @@ -100,9 +169,24 @@ internal static class WeaponPlanner return new WeaponPlan(0, elem, "none"); } - int mainKind = listed[0].Kind; var pool = new List(); - foreach (var c in listed) if (c.Kind == mainKind) pool.Add(c); + if (style != DamageStyle.Auto) + { + // The preferred style, when the character has a weapon of it it can use: Void needs the + // Nether school, War any school but Nether. Otherwise Auto, below. + var cast = DamageStyles.Restrict(canCast, style); + bool schoolOpen = false; + foreach (string e in FallbackOrder) if (cast(e)) { schoolOpen = true; break; } + if (style is DamageStyle.Melee or DamageStyle.Missile || schoolOpen) + foreach (var c in listed) if (DamageStyles.Matches(c, style)) pool.Add(c); + if (pool.Count > 0) { applied = style; canCast = cast; } + } + if (pool.Count == 0) + { + int mainKind = listed[0].Kind; + foreach (var c in listed) if (c.Kind == mainKind) pool.Add(c); + } + bool styled = applied != DamageStyle.Auto; // 2. A slayer of this monster's creature type. if (creatureType > 0) @@ -119,13 +203,13 @@ internal static class WeaponPlanner } // 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed. - if (fixedPick != null) + if (fixedPick != null && (!styled || pool.Contains(fixedPick))) return FixedPlan(fixedPick, fixedSource, rule, weak, canCast); // 4. An explicit damage type: the listed weapon of that element (main kind first). if (ruleSet) { - var w = BestOf(pool, rule, null) ?? BestOf(listed, rule, null); + var w = BestOf(pool, rule, null) ?? (styled ? null : BestOf(listed, rule, null)); if (w != null) return new WeaponPlan(w.Id, rule, "Monsters rule " + rule); var keep = InHand(pool) ?? pool[0]; // A wand casts its own element: the rule's element only when the weapon has none. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 2a6d242..d8073c4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -292,6 +292,20 @@ internal sealed partial class LegacyDashboardRenderer id => cache[id], wo => WorldObjectCache.IsWieldedByPlayer(_host, wo)); } + /// The Items panel's group for a listed weapon, the same split the weapon planner and + /// the Prefer setting use: Melee, Missile, War Magic, Void Magic (a Nether caster), Shield, Ammo; + /// "" for an item the client doesn't know (not carried). + private string WeaponKindLabel(ItemRule r) + { + if (WeaponList.IsShieldRule(r)) return "Shield"; + var wo = _weaponCache?[r.Id]; + if (wo == null) return ""; + if (CombatManager.IsAmmoItem(wo)) return "Ammo"; + if (WeaponList.IsWand(wo)) + return WeaponElements.Normalize(r.Element).Equals("Nether", StringComparison.OrdinalIgnoreCase) ? "Void Magic" : "War Magic"; + return wo.ObjectClass == AcObjectClass.MissileWeapon ? "Missile" : "Melee"; + } + /// A picker's name for a listed weapon: plus " (missing)" when it isn't carried. private string WeaponPickerName(ItemRule r, HashSet missing) => WeaponDisplayName(r, withElement: true) + (missing.Contains(r.Id) ? WeaponList.MissingSuffix : ""); @@ -1443,7 +1457,7 @@ internal sealed partial class LegacyDashboardRenderer var payload = new ItemsBridgePayload { // Copies: the full name, and "Unknown" for an element not known yet (ApplyItemsJson maps them back by id). - Weapons = WeaponList.ForDisplay(_settings.ItemRules ?? new List(), r => WeaponDisplayName(r, withElement: false)), + Weapons = WeaponList.ForDisplay(_settings.ItemRules ?? new List(), r => WeaponDisplayName(r, withElement: false), WeaponKindLabel), Consumables = _settings.ConsumableRules ?? new List(), EnableManaTapping = _settings.EnableManaTapping, ManaTapMinMana = _settings.ManaTapMinMana, diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index c50f09b..d8ca3fa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -782,6 +782,11 @@ public sealed class MonsterRule public string MatchExpression { get; set; } = ""; public int Priority { get; set; } = 1; public string DamageType { get; set; } = "Auto"; + /// The kind of damage to fight with when the character uses more than one: Auto, Melee, + /// Missile, "War Magic" or "Void Magic" (see DamageStyles). On a monster's own rule, Auto follows + /// the Default row's; on the Default row, Auto is the kind of the first usable weapon in the + /// Items list. Off in files from before 2026-10-16. + public string PreferredDamage { get; set; } = "Auto"; public int WeaponId { get; set; } public bool Fester { get; set; } public bool Broadside { get; set; } @@ -835,6 +840,9 @@ public sealed class ItemRule /// "icon" (UiEffects), "rending" (an imbue), "name", "set" (picked in the Items panel), or "" /// (not known, or an entry from before sources were kept). public string ElementSource { get; set; } = ""; + /// Display only (filled by WeaponList.ForDisplay for the Items panel, never read back): + /// Melee, Missile, "War Magic", "Void Magic", Shield, Ammo, or "" when the item isn't known. + public string Kind { get; set; } = ""; public bool KeepBuffed { get; set; } = true; /// True when this row is a shield (off hand), not a main-hand weapon. diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index 249f6fa..f11f5e9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -319,6 +319,7 @@ internal sealed class ManaStoneManager if (text.Contains("The Mana Stone drains")) { MarkStoneCharged(_activeStoneId); + _stoneTapFailures.Remove(_activeStoneId); _host.Log($"[RynthAi] ManaStone: drained 0x{(uint)_activeItemId:X8} into stone 0x{(uint)_activeStoneId:X8}."); } if (_activeItemId != 0) ForgetTapItem(_activeItemId); // drained and destroyed @@ -625,15 +626,12 @@ internal sealed class ManaStoneManager foreach (var item in _objectCache.AllKnownObjects()) { if (!IsManaStone(item) || IsManaCharge(item)) continue; // keep in sync with FindEmptyStone - if (!IsOwnedByPlayer(item, playerId)) continue; + if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue; if (_stoneKnownCharged.Contains(item.Id)) continue; int? read = ReadStoneMana(item.Id); bool knownEmpty = IsKnownEmpty(item.Id, read); // keep in sync with FindEmptyStone - if (knownEmpty || read == 0) - _stoneTapCooldownUntil.Remove(item.Id); - - if (_stoneTapCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue; + if (StoneParkedForTap(item.Id, knownEmpty, read, now)) continue; if (!knownEmpty && read > 0) continue; count++; } @@ -835,6 +833,42 @@ internal sealed class ManaStoneManager return true; } + // The client's own pack walk (GetDirectInventory: GetContainerContents, plus worn gear), + // rebuilt at most every ThinkIntervalMs. A stone, and an item to drain, must be in it: the + // cache files every object without a world position as inventory (corpse contents too) and + // keeps ids the client has since dropped, and both passed IsOwnedByPlayer. Drakkon drained + // (2026-10-16) with a Major Mana Stone still on the corpse and with a stone the client no + // longer knew ('?'): 12 drains, none completed, and the looter kept taking items for them. + private readonly HashSet _packIds = new(); + private long _packIdsAt = -ThinkIntervalMs; + + private bool InPack(int id) + { + if (!_host.HasGetContainerContents) return true; // no walk: IsOwnedByPlayer decides alone + long now = NowMs; + if (now - _packIdsAt >= ThinkIntervalMs) + { + _packIdsAt = now; + _packIds.Clear(); + foreach (var wo in _objectCache.GetDirectInventory(forceRefresh: false)) _packIds.Add(wo.Id); + } + return _packIds.Contains(id); + } + + /// + /// True while a stone sits out its tap cooldown after a drain that never completed. A stone + /// that reads empty used to come straight back (the read "self-healed" the cooldown), so the + /// 30-minute park after its second failure lasted one think tick: stone 0x801ACCDC failed 36 + /// drains in a row (2026-10-16). The short park after one failure still clears on an empty read. + /// + private bool StoneParkedForTap(int stoneId, bool knownEmpty, int? read, long now) + { + bool longPark = _stoneTapFailures.TryGetValue(stoneId, out int fails) && fails >= 2; + if ((knownEmpty || read == 0) && !longPark) + _stoneTapCooldownUntil.Remove(stoneId); + return _stoneTapCooldownUntil.TryGetValue(stoneId, out long until) && now < until; + } + /// Find a stone with no charge (CurrentMana == 0) — only those can drain an item. private int FindEmptyStone() { @@ -848,7 +882,7 @@ internal sealed class ManaStoneManager // (ACE ManaStoneDestroyChance 1.0). One whose charge wasn't read yet was taken for the // empty stone, and "draining" loot with it poured the whole charge into the loot item. if (!IsManaStone(item) || IsManaCharge(item)) continue; - if (!IsOwnedByPlayer(item, playerId)) continue; + if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue; // Stones AC has explicitly told us are charged ("already full of // mana") are never empty until they're consumed/destroyed. @@ -858,17 +892,8 @@ internal sealed class ManaStoneManager // It gave its mana to worn gear: empty, whatever the (older) read says. bool knownEmpty = IsKnownEmpty(item.Id, read); - // If we can read CurrentMana and it's truly 0, the stone IS empty — - // clear any stale blacklist entry. This makes the cooldown self-heal - // once the cache catches up to the actual state. - if (knownEmpty || read == 0) - _stoneTapCooldownUntil.Remove(item.Id); - - // Skip stones that recently failed a tap so we don't loop on the - // same broken pair. The auto-clear above lets a stone return as - // soon as its real state is known. - if (_stoneTapCooldownUntil.TryGetValue(item.Id, out long until) && now < until) - continue; + // Skip stones that recently failed a tap so we don't loop on the same broken pair. + if (StoneParkedForTap(item.Id, knownEmpty, read, now)) continue; // Treat the stone as empty if CurrentMana is 0 OR unreadable. // Unreadable happens for stones whose CBaseQualities InqInt isn't @@ -899,7 +924,7 @@ internal sealed class ManaStoneManager foreach (var item in _objectCache.AllKnownObjects()) { if (!IsRefillStone(item)) continue; - if (!IsOwnedByPlayer(item, playerId)) continue; + if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue; // Skip stones that timed out on use-on-player recently. if (_stoneUseOnPlayerCooldownUntil.TryGetValue(item.Id, out long until) && now < until) @@ -961,7 +986,7 @@ internal sealed class ManaStoneManager if (item == null) continue; if (IsManaStone(item)) continue; if (!TapItemArrived(id, now)) continue; // its pickup is still on the way - if (!IsOwnedByPlayer(item, playerId)) continue; + if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue; // Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses // retained items). Only items looted for Mana Tap are candidates, and the wielded / diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs index 501a800..94e20c2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs @@ -268,6 +268,7 @@ public static class VirindiTankProfileImporter OffhandId = row.OffhandId, PreferredAmmoItemId = row.PreferredAmmoItemId, PetDamage = row.PetDamage, + PreferredDamage = row.PreferredDamage, }; private static void TryMergeMonsterFile(string jsonPath, LegacyUiSettings settings, Result result) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 837fd2f..42b97aa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -16,6 +16,7 @@ namespace RynthCore.Plugin.RynthAi; // /ra testitem TestItem the selected item against the loot profile // /ra propertydump [0xId] PropertyDump every property of the selection (/ra dumpprops) // /ra recharge Recharge one vitals pass with the Top Off lines +// /ra heal | stam | mana One-touch heal the best kit / spell / potion for that vital now (RynthCore's One-touch hotkeys) // /ra navprio|lootprio|navlootprio [on|off] Boost Nav / Boost Loot Priority (no argument: toggle) // /ra lootthis LootThisCont loot the open corpse or chest now // @@ -57,6 +58,14 @@ public sealed partial class RynthAiPlugin case "testitem": HandleLootCheckSelectedCommand(new[] { "/ra", "lootcheck" }); return true; case "propertydump": HandleDumpPropsCommand(parts); return true; case "recharge": HandleRechargeCommand(); return true; + case "heal": + case "healme": + case "onetouchheal": HandleOneTouchCommand(OneTouchVital.Health); return true; + case "stam": + case "stamina": + case "restam": HandleOneTouchCommand(OneTouchVital.Stamina); return true; + case "mana": + case "remana": HandleOneTouchCommand(OneTouchVital.Mana); return true; case "navprio": HandlePriorityCommand(parts, nav: true, loot: false); return true; case "lootprio": HandlePriorityCommand(parts, nav: false, loot: true); return true; case "navlootprio": HandlePriorityCommand(parts, nav: true, loot: true); return true; @@ -76,6 +85,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra testitem - check the selected item against the loot profile"); ChatLine("[RynthAi] /ra propertydump [0xId] - every property of the selected object"); ChatLine("[RynthAi] /ra recharge - one heal / stamina / mana top-off with the Top Off lines, macro on or off"); + ChatLine("[RynthAi] /ra heal | stam | mana - one touch: the best kit, spell or potion for that vital now, whatever the lines say"); ChatLine("[RynthAi] /ra navprio | lootprio | navlootprio [on|off] - Boost Nav / Boost Loot Priority (toggle)"); ChatLine("[RynthAi] /ra lootthis - loot the open corpse or chest now (never house storage or your own packs)"); } @@ -204,6 +214,14 @@ public sealed partial class RynthAiPlugin _buffManager.RequestRecharge(); // runs on the pump's next heartbeat, says what it did } + // ── One-touch heal / stamina / mana ─────────────────────────────────────── + + private void HandleOneTouchCommand(OneTouchVital vital) + { + if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready (log in first)."); return; } + _buffManager.RequestOneTouch(vital); // runs on the pump's next heartbeat, says what it did + } + // ── LootThisCont ────────────────────────────────────────────────────────── private int _lootThisRequested; // set by /ra lootthis (AC's thread), taken on the pump diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index 9e6ef65..83267e3 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -604,8 +604,19 @@ internal static class ActionPacer /// Past its normal cycle: turn to face the target after this, jump after this. public const long TurnAfterMs = 1000; public const long JumpAfterMs = 2000; - /// A 0x1D to another send breaks our open cast only once it is this old (a recoil refusal is normal). + /// + /// After a held-cast turn goes out, no jump for this long: the turn (up to ~180 deg) and the cast + /// it lets finish. Drakkon (2026-10-16) was turned 91 deg at 5.2 s and jumped 1 s later, while + /// hunting; the cast's UseDone came 0.2 s after the jump. + /// + public const long TurnGraceMs = 2500; + /// + /// A 0x1D to another send breaks our open cast only once it is this old, and RefusalPastCycleMs + /// past its normal cycle (a recoil refusal is normal: a follow-up heal sent as the first one + /// landed was refused, and the landed heal was jumped at 3.0 s, its UseDone due at 3.5 s). + /// public const long RefusalBreakMinMs = 3000; + public const long RefusalPastCycleMs = 1000; /// After the jump: landed once the height is back (and this long passed), or at the max. public const long JumpLandMinMs = 400; public const long JumpLandMaxMs = 1500; @@ -644,6 +655,7 @@ internal static class ActionPacer private static BreakStage _stage; private static long _stageAt; private static PacedAction? _stageFor; + private static long _turnedAt; // when the held-cast turn for _stageFor went out (0 = none) private static long _jumpAt; // 0 = not in the air after a breaker jump private static float _jumpZ; private static int _lastSeenSeq = int.MinValue; @@ -678,6 +690,7 @@ internal static class ActionPacer _stage = BreakStage.None; _stageAt = 0; _stageFor = null; + _turnedAt = 0; _busyLogged.Clear(); } @@ -844,18 +857,22 @@ internal static class ActionPacer long cycle = NormalCycleMs(stuck.Id); long jumpAt = Math.Min(cycle + JumpAfterMs, StuckCastMs); long turnAt = Math.Min(cycle + TurnAfterMs, jumpAt); - long refusalBreakAt = RefusalBreakMinMs; + long refusalBreakAt = Math.Max(RefusalBreakMinMs, cycle + RefusalPastCycleMs); if (stuck.Script) { jumpAt = Math.Max(jumpAt, ScriptCastMinBreakMs); refusalBreakAt = Math.Max(refusalBreakAt, ScriptCastMinBreakMs); } - BreakStage stage; long stageAt; int refusals; - lock (Gate) { stage = _stage; stageAt = _stageAt; refusals = _busyRefusals; } + BreakStage stage; long stageAt; int refusals; long turnedAt; + lock (Gate) { stage = _stage; stageAt = _stageAt; refusals = _busyRefusals; turnedAt = ReferenceEquals(_stageFor, stuck) ? _turnedAt : 0; } - if (stage == BreakStage.None && age >= turnAt && age < jumpAt) + bool refusalBreak = refusals > 0 && age >= refusalBreakAt; + if (stage == BreakStage.None && age >= turnAt && age < jumpAt && !refusalBreak) { SetStage(BreakStage.Turned, now, stuck); - TurnToFace(host, stuck, age); + if (TurnToFace(host, stuck, age)) lock (Gate) _turnedAt = now; return; } - if (stage <= BreakStage.Turned && (age >= jumpAt || (refusals > 0 && age >= refusalBreakAt))) + // The turn gets its time before the timer's jump (StuckCastMs still caps it). + if (turnedAt != 0) + jumpAt = Math.Max(jumpAt, Math.Min(turnedAt - stuck.SentMs + TurnGraceMs, StuckCastMs)); + if (stage <= BreakStage.Turned && (age >= jumpAt || refusalBreak)) { string why = age >= jumpAt ? $"{age} ms with no answer ({cycle} ms is normal for it)" : $"a send was refused 'too busy' while it was open {age} ms"; Jump(host, stuck, age, why, forced: false); @@ -876,7 +893,7 @@ internal static class ActionPacer private static void SetStage(BreakStage stage, long now, PacedAction? forAction) { - lock (Gate) { _stage = stage; _stageAt = now; _stageFor = forAction; } + lock (Gate) { if (!ReferenceEquals(_stageFor, forAction)) _turnedAt = 0; _stage = stage; _stageAt = now; _stageFor = forAction; } } /// In the air after a breaker jump: hold until landed (height back, or JumpLandMaxMs). @@ -971,17 +988,19 @@ internal static class ActionPacer /// Turn to face a held cast's target (once per cast), when RynthAi is not moving the character: /// ACE's fast-tick cast waits for the facing to come within spellcast_max_angle. /// - private static void TurnToFace(RynthCoreHost host, PacedAction stuck, long age) + /// True when the turn went out. + private static bool TurnToFace(RynthCoreHost host, PacedAction stuck, long age) { uint target = stuck.Target; uint player = 0; try { if (host.HasGetPlayerId) player = host.GetPlayerId(); } catch { } - if (target == 0 || target == player || !host.HasTurnToHeading || MoveAudit.OwnMovementActive) return; - if (!TryHeadingTo(host, target, out double want, out double off)) return; - if (off < 10.0) return; // already facing it: the turn is not what holds it - try { host.TurnToHeading((float)want); } catch { return; } + if (target == 0 || target == player || !host.HasTurnToHeading || MoveAudit.OwnMovementActive) return false; + if (!TryHeadingTo(host, target, out double want, out double off)) return false; + if (off < 10.0) return false; // already facing it: the turn is not what holds it + try { host.TurnToHeading((float)want); } catch { return false; } lock (Gate) _heldTurns++; - Log(host, $"[Pace] held cast: {Describe(stuck.Kind, stuck.Label)} unanswered {age} ms; turning {off:0} deg to face 0x{target:X8} (heading {want:0})"); + Log(host, $"[Pace] held cast: {Describe(stuck.Kind, stuck.Label)} unanswered {age} ms; turning {off:0} deg to face 0x{target:X8} (heading {want:0}); no jump for {TurnGraceMs / 1000.0:0.#} s"); + return true; } /// The heading to (AC degrees: 0 north, 90 east) and how far off the player faces. diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 4a45e12..20bfc46 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -126,6 +126,7 @@ internal static class Program LootPacingTests.Register(runner); CorpseCloseTests.Register(runner); VTankHotkeyTests.Register(runner); + OneTouchHealTests.Register(runner); SaveFailureTests.Register(runner); DoorTests.Register(runner); ServerPolicyTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 3c436b2..a82cad0 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -1250,8 +1250,8 @@ internal static class CombatHookTests RunPacer(own.Host, 3500); Check.Eq(FakeHost.TapJumps, 0, "control: no jump before the refusal"); RefuseAnother(own.Host); - RunPacer(own.Host, 200); - Check.Eq(FakeHost.TapJumps, 1, "control: a 0x1D past 3 s jumps RynthAi's own cast at once"); + RunPacer(own.Host, 600); + Check.Eq(FakeHost.TapJumps, 1, "control: a 0x1D past its cycle + 1 s (4 s) jumps RynthAi's own cast at once"); } finally { PaceOff(); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs index ba5b780..fd91b76 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -33,6 +33,8 @@ internal static class ManaStoneChoiceTests r.Add("mana tapping: one item at a time - the stone first, then one item, drained before the next", OneTapItemAtATime); r.Add("mana tapping: no drain until the pickup is confirmed in the pack", NoDrainBeforeArrival); r.Add("mana tapping: a drain that never completes keeps the item's place, tries the next stone, then gives up", FailedDrainKeepsPlace); + r.Add("mana tapping: only a stone in the client's pack is used or counted (not one on a corpse, not a stale id)", StoneMustBeInPack); + r.Add("mana tapping: a stone that failed two drains stays parked though it reads empty", FailedStoneStaysParked); } private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033; @@ -227,10 +229,11 @@ internal static class ManaStoneChoiceTests /// The engine can identify objects (RequestId). public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false, string stoneName = "Moderate Mana Stone", int maceMana = 0, bool identify = true, - bool ringArrived = true) + bool ringArrived = true, bool contents = false) { FakeHost.Reset(); FakeHost.UseOnCalls = true; + FakeHost.ContentsCalls = contents; // the client's pack walk (GetContainerContents) FakeHost.WeaponCalls = identify; // RequestId, HasAppraisalData FakeHost.Names[Player] = "Stone Tester"; _stoneName = stoneName; @@ -375,6 +378,38 @@ internal static class ManaStoneChoiceTests Check.True(FakeHost.Chat.Any(c => c.Contains("would not drain")), "the player is told"); } + // 2026-10-16: Drakkon drained with a Major Mana Stone still on the corpse and with a stone id + // the client no longer knew. The cache files objects without a world position as inventory, + // so both counted as empty stones in the pack: no drain completed and the looter went on + // taking items to tap. + private static void StoneMustBeInPack() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, 0) }, ringToDrain: true, maceMana: 5000, contents: true); + FakeHost.Containers.Remove(StoneA); // gone from the client's pack; the cache still has it + rig.Run(3000); + Check.Eq(rig.OnRing.Count, 0, "no drain with a stone that is not in the pack"); + Check.Eq(rig.M.CountEmptyStones(), 0, "it is not counted as an empty stone"); + rig.AddStone(StoneB, 0); + System.Threading.Thread.Sleep(1100); // the cache walks the pack again after 1 s of real time + rig.Run(2000); + Check.Eq(rig.OnRing.Count, 1, "a stone that is in the pack drains the ring"); + Check.Eq(rig.OnRing[0], StoneB, "stone B"); + } + + // 2026-10-16: the 30-minute park after a stone's second failed drain was undone on the next + // think tick because the stone reads empty: one stone failed 36 drains in a row. + private static void FailedStoneStaysParked() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, 0) }, ringToDrain: true, maceMana: 5000, contents: true); + rig.Run(1000); + Check.Eq(rig.OnRing.Count, 1, "first try"); + rig.Run(9000 + 21_000); + Check.Eq(rig.OnRing.Count, 2, "second try, the same (only) stone"); + rig.Run(9000 + 60_000); + Check.Eq(rig.OnRing.Count, 2, "failed twice: the stone stays parked though it reads empty"); + Check.Eq(rig.M.CountEmptyStones(), 0, "and no item is looted for it"); + } + private static void KnownChargedRefills() { using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null) }, ringToDrain: true); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs index afdeb78..7f5acd8 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs @@ -37,6 +37,8 @@ internal static class OffhandTests r.Add("swap speed: a weapon in hand -> one use of the wand (the client swaps); the pack move only as the fallback", CasterDirectSwap); r.Add("swap speed: the gate lets the next step go once the server is done, else after 3 s", SwapGateSettles); r.Add("offhand: dual wield with the Dual Wield skill", DualWield); + r.Add("offhand: the weapon in hand is the main hand's when the wielded slot reads 0 (the weenie's wielder record)", InHandFromWielderInfo); + r.Add("weapons: a weapon refused 'skill too low' is left out of the choice (the off hand stays)", SkillTooLowLeftOut); r.Add("offhand: no Dual Wield skill -> the shield", NoSkillShield); r.Add("offhand: None -> hands off (a worn shield is never taken off)", NoneHandsOff); r.Add("offhand: an unlisted shield is never wielded", UnlistedNeverUsed); @@ -118,10 +120,12 @@ internal static class OffhandTests private readonly MethodInfo _equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", BindingFlags.Instance | BindingFlags.NonPublic)!; private readonly FieldInfo _lastEquip = typeof(CombatManager).GetField("_lastEquipTime", BindingFlags.Instance | BindingFlags.NonPublic)!; - public Rig(bool dualWieldSkill = false, bool shieldOn = false, bool wieldCalls = true) + public Rig(bool dualWieldSkill = false, bool shieldOn = false, bool wieldCalls = true, bool wielderInfo = false, bool weenieErrors = false) { FakeHost.Reset(); FakeHost.WeaponCalls = true; + FakeHost.SalvageCalls = wielderInfo; // GetObjectWielderInfo (answering FakeHost.Wielded) + FakeHost.WeenieErrorCalls = weenieErrors; FakeHost.WieldCalls = wieldCalls; FakeHost.CombatModeValue = CombatMode.Melee; Item(Sword, "Long Sword", 0x1, MeleeSlot, combatUse: 1); @@ -138,7 +142,7 @@ internal static class OffhandTests if (shieldOn) Wield(Shield, ShieldSlot); FakeHost.Wcids[Monster] = Wcid; FakeHost.Skills[(Player, 49)] = dualWieldSkill ? (220, 2) : (10, 1); - var host = FakeHost.Create(); + var host = FakeHost.Create(wielderInfo ? Player : 0); var cache = FakeHost.MakeCache(host, Player, new[] { Sword, Dagger, Great, Shield, Round, Bow, Arrows, Wand }); C = new CombatManager(host, S, cache); C.SetPlayerId(Player); @@ -427,6 +431,41 @@ internal static class OffhandTests Check.Eq(rig2.ShieldWields(Dagger), 1, "Monsters rule 'Offhand weapon': the dagger"); } + // 2026-10-16: Drakkon dual wielding two Hand Wraps; CurrentWieldedLocation read 0, so both + // counted as in hand and the later listed one (the off hand's) was taken for the main weapon. + private static void InHandFromWielderInfo() + { + var rig = new Rig(dualWieldSkill: true, wielderInfo: true); + rig.List(Sword, Dagger); + Rig.Unwield(Sword); // the slot reads 0 for both + FakeHost.Wielded[Sword] = (uint)MeleeSlot; + FakeHost.Wielded[Dagger] = (uint)ShieldSlot; + rig.C.InHandOverride = null; + Check.Eq(unchecked((uint)rig.C.InHandWeaponId(fresh: true)), Sword, "the main hand: the sword, not the off-hand dagger"); + Check.Eq(unchecked((uint)rig.C.OffhandInSlot(fresh: true)), Dagger, "the off hand: the dagger"); + } + + // 2026-10-16: a Nodachi the character lacked the skill for was chosen whenever a monster was + // weak to Slash: refused three times, then again two minutes later, the off hand dequipped each time. + private static void SkillTooLowLeftOut() + { + var rig = new Rig(dualWieldSkill: true, weenieErrors: true); + rig.List(Sword, Great); + rig.Store.SetManualWeapon(Wcid, Great); + rig.Tick(); + Check.True(FakeHost.Uses.Contains(Great), "the greatsword's wield goes out"); + FakeHost.WeenieError(CombatManager.SkillTooLowErr, 0x00A0, Great); + rig.Unpace(); + rig.Tick(); + Check.True(rig.C.SkillTooLowFor(unchecked((int)Great)), "refused 'skill too low': left out"); + Check.True(FakeHost.Logs.Any(l => l.Contains("skill is too low to wield it")), "logged"); + Check.True(FakeHost.Chat.Any(c => c.Contains("skill is too low")), "the player is told"); + int uses = FakeHost.Uses.Count(u => u == Great); + for (int i = 0; i < 5; i++) { rig.Unpace(); rig.Tick(); } + Check.Eq(FakeHost.Uses.Count(u => u == Great), uses, "never sent again"); + Check.False(rig.C.ListedCandidates().Any(c => c.Id == unchecked((int)Great)), "not a candidate"); + } + private static void NoSkillShield() { var rig = new Rig(dualWieldSkill: false); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OneTouchHealTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OneTouchHealTests.cs new file mode 100644 index 0000000..347d57a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OneTouchHealTests.cs @@ -0,0 +1,327 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Threading; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// One-touch heal / stamina / mana (BuffManager.OneTouch.cs; /ra heal, /ra stam, /ra mana, and RynthCore's +// "One-touch" hotkeys): one request uses the best kit, spell or potion for that vital now, whatever +// the Heal At / Top Off lines say, with the macro off. The choice is the vitals step's own +// (AttemptHealChain, AttemptStaminaChain, AttemptManaRefill), so these tests check the order and the +// waiting, not the individual attempts (VitalsTests, RecoveryRetryTests, ...). +internal static class OneTouchHealTests +{ + private const uint Player = 0x50000C01; + private const uint Kit = 0x80004C01, StamKit = 0x80004C02, HealPotion = 0x80004C03, StamPotion = 0x80004C04; + private const uint STypeLife = 33; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("one-touch: a vital that is full says so and sends nothing", FullSaysSo); + r.Add("one-touch: heal ignores the lines and casts Heal Self in Magic stance, macro off", HealCastsInMagic); + r.Add("one-touch: heal with a weapon out takes the kit, then the potion, before the spell (no wand swap)", HealItemsBeforeSpellInMelee); + r.Add("one-touch: heal in Magic stance keeps the vitals step's order: Heal Self before the potion", HealSpellBeforePotionInMagic); + r.Add("one-touch: heal falls to Stamina to Health only when that feature is on and stamina is over its floor", HealStaminaToHealthLast); + r.Add("one-touch: with nothing to heal with it says why for the kit, the spell and the potion", HealNothingSaysWhy); + r.Add("one-touch: a request waits out a kit in flight, then goes; a second press while waiting is not a second heal", HealWaitsForKit); + r.Add("one-touch: a request that stays blocked gives up after OneTouchWaitMs and says why", HealGivesUp); + r.Add("one-touch: stamina takes a stamina kit, a listed potion out of Magic stance, else Revitalize", StaminaChoice); + r.Add("one-touch: mana casts Stamina to Mana; with stamina at the floor it refills stamina first", ManaChoice); + r.Add("one-touch: /ra heal, /ra stam and /ra mana request a pass (and say so before login)", Commands); + } + + private sealed class Rig + { + public BuffManager B = null!; + public LegacyUiSettings S = null!; + public PlayerVitalsCache V = null!; + public RynthCoreHost Host; + } + + /// A character with every spell known, Life Magic trained, the macro off and every line at 0 (so no + /// vitals step would act): the one-touch request is the only thing that can. + private static Rig Make(int mode, uint hp = 40, uint st = 100, uint mn = 100, bool spells = true, bool kit = false, + bool stamKit = false, bool healPotion = false, bool stamPotion = false, byte lifeTraining = 2, Action? tweak = null) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.CombatModeValue = mode; + if (spells) foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, lifeTraining); + var ids = new System.Collections.Generic.List(); + if (kit) { FakeHost.Names[Kit] = "Peerless Healing Kit"; ids.Add(Kit); } + if (stamKit) { FakeHost.Names[StamKit] = "Greater Stamina Kit"; ids.Add(StamKit); } + if (healPotion) { FakeHost.Names[HealPotion] = "Health Tincture"; ids.Add(HealPotion); } + if (stamPotion) { FakeHost.Names[StamPotion] = "Stamina Tincture"; ids.Add(StamPotion); } + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings + { + IsMacroRunning = false, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + RestamAt = 0, TopOffStam = 0, GetManaAt = 0, TopOffMana = 0, UsePotions = healPotion || stamPotion, + KitMinSuccessPct = 0, PeaceModeForKits = false, UseKitsInMagicMode = true, EnableBuffing = false, + }; + if (healPotion) s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)HealPotion), Name = "Health Tincture", Type = "HealthPotion" }); + if (stamPotion) s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)StamPotion), Name = "Stamina Tincture", Type = "Stamina" }); + tweak?.Invoke(s); + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = hp, MaxStamina = 100, CurrentStamina = st, MaxMana = 100, CurrentMana = mn }; + var b = new BuffManager(host, s, sm, v); + b.SetCharacterSkills(skills); + b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, ids)); + ActionPacer.Reset(); + return new Rig { B = b, S = s, V = v, Host = host }; + } + + /// Heartbeats until the request is taken (or 400 ms): what the pump does after the command. + private static void Pump(BuffManager b, OneTouchVital v) + { + for (int i = 0; i < 40 && b.OneTouchPending(v); i++) { b.OnHeartbeat(); Thread.Sleep(10); } + } + + private static bool Said(string part) => FakeHost.Chat.Any(c => c.Contains(part, StringComparison.Ordinal)); + private static string AllChat => string.Join(" | ", FakeHost.Chat); + + /// The cast spell is a level of the family of (top levels have names of their own). + private static bool IsFamily(int spellId, string levelOne) => + SpellTableStub.GetById(spellId)?.Family == SpellTableStub.GetById(SpellTable.Rows.First(r => r.Name == levelOne).Id)?.Family; + + private static void FullSaysSo() + { + var r = Make(CombatMode.Magic, hp: 100, st: 100, mn: 100); + foreach (var v in new[] { OneTouchVital.Health, OneTouchVital.Stamina, OneTouchVital.Mana }) + { + r.B.RequestOneTouch(v); + Check.True(r.B.OneTouchPending(v), v + ": pending until a heartbeat"); + Pump(r.B, v); + Check.False(r.B.OneTouchPending(v), v + ": taken"); + } + Check.Eq(FakeHost.Casts.Count, 0, "nothing cast"); + Check.Eq(FakeHost.UsesOn.Count + FakeHost.Uses.Count, 0, "nothing used"); + Check.True(Said("Heal: health is full") && Said("Stamina: stamina is full") && Said("Mana: mana is full"), AllChat); + } + + private static void HealCastsInMagic() + { + // 95% health: over Heal At and Top Off HP (both 0 here, and 90 in a real setup): no vitals step would act. + var r = Make(CombatMode.Magic, hp: 95); + Check.False(r.B.CheckVitals(), "the normal step does nothing at 95%"); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count, 1, "one cast"); + Check.True(IsFamily(FakeHost.Casts[0].SpellId, "Heal Self I"), "a Heal Self (the top level known)"); + Check.True(Said("Heal: casting "), AllChat); + Check.False(r.S.IsMacroRunning, "the macro stayed off"); + } + + private static void HealItemsBeforeSpellInMelee() + { + // Melee, kit and potion and every spell: the kit goes, no cast (the wand swap is seconds). + var r = Make(CombatMode.Melee, hp: 60, kit: true, healPotion: true); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.True(FakeHost.UsesOn.Any(u => u.Source == Kit && u.Target == Player), "the kit is used on yourself"); + Check.Eq(FakeHost.Casts.Count, 0, "no cast"); + Check.False(FakeHost.Uses.Contains(HealPotion), "and no potion on top of it"); + Check.True(Said("Heal: using a healing kit"), AllChat); + + // No kit: the potion, still before the spell. + r = Make(CombatMode.Melee, hp: 60, healPotion: true); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.True(FakeHost.Uses.Contains(HealPotion), "melee, no kit: the potion is drunk"); + Check.Eq(FakeHost.Casts.Count, 0, "melee: no Heal Self (a wand swap) while a potion can do it"); + Check.True(Said("Heal: drinking a potion"), AllChat); + + // Neither: the spell (the wand swap / Magic stance steps are the vitals step's). + r = Make(CombatMode.Melee, hp: 60); + r.B.RequestOneTouch(OneTouchVital.Health); + for (int i = 0; i < 40 && r.B.OneTouchPending(OneTouchVital.Health) && FakeHost.Casts.Count == 0; i++) { r.B.OnHeartbeat(); Thread.Sleep(10); } + // Either the cast went out or a stance step is in flight (still pending); never a "nothing could heal". + Check.False(Said("nothing could heal"), "a spell is possible: " + AllChat); + } + + private static void HealSpellBeforePotionInMagic() + { + var r = Make(CombatMode.Magic, hp: 60, healPotion: true); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count, 1, "Magic stance: the spell, as the vitals step does"); + Check.False(FakeHost.Uses.Contains(HealPotion), "the potion is the fallback, not the first choice"); + + // A kit still goes before the spell when kits are allowed in Magic mode (the step's own order) ... + r = Make(CombatMode.Magic, hp: 60, kit: true); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.True(FakeHost.UsesOn.Any(u => u.Source == Kit), "Use Kits in Magic Mode on: the kit first"); + Check.Eq(FakeHost.Casts.Count, 0, "and no cast on top of it"); + + // ... and not when they are not. + r = Make(CombatMode.Magic, hp: 60, kit: true, tweak: s => s.UseKitsInMagicMode = false); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.UsesOn.Count, 0, "Use Kits in Magic Mode off: no kit"); + Check.Eq(FakeHost.Casts.Count, 1, "the spell instead"); + } + + private static void HealStaminaToHealthLast() + { + // Only Stamina to Health Self is known: used when the feature is on and stamina is over its floor. + static Rig OnlyStamToHealth(uint stamina, int at) + { + var r = Make(CombatMode.Magic, hp: 70, st: stamina, spells: false, tweak: s => { s.StaminaToHealthAt = at; s.StaminaToHealthMinStamina = 20; }); + foreach (var row in SpellTable.Rows.Where(x => x.Name.StartsWith("Stamina to Health Self"))) FakeHost.Spellbook.Add((uint)row.Id); + return r; + } + + var r = OnlyStamToHealth(80, 30); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count, 1, "Stamina to Health Self is cast"); + Check.True(IsFamily(FakeHost.Casts[0].SpellId, "Stamina to Health Self I"), "Stamina to Health Self"); + + r = OnlyStamToHealth(10, 30); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count, 0, "stamina under its floor: not cast"); + Check.True(Said("stamina 10% is not over 20%"), AllChat); + + r = OnlyStamToHealth(80, 0); + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count, 0, "Stamina To Health At 0 (off): not cast"); + Check.True(Said("Stamina to Health: not on"), AllChat); + } + + private static void HealNothingSaysWhy() + { + var r = Make(CombatMode.Magic, hp: 40, lifeTraining: 1); // Life Magic untrained + r.B.RequestOneTouch(OneTouchVital.Health); + Pump(r.B, OneTouchVital.Health); + Check.Eq(FakeHost.Casts.Count + FakeHost.UsesOn.Count + FakeHost.Uses.Count, 0, "nothing sent"); + Check.True(Said("Heal: nothing could heal (health 40%"), AllChat); + Check.True(Said("kit: no healing kit") && Said("Heal Self: Life Magic not usable") && Said("potion: Use Potions is off"), AllChat); + Check.False(r.B.OneTouchPending(OneTouchVital.Health), "and the request is over"); + } + + private static void HealWaitsForKit() + { + var r = Make(CombatMode.Magic, hp: 40); + r.B.MarkKitUsed(); // a kit went out a moment ago and its result hasn't come + r.B.RequestOneTouch(OneTouchVital.Health); + r.B.RequestOneTouch(OneTouchVital.Health); // pressed again: still one request + for (int i = 0; i < 10; i++) { r.B.OnHeartbeat(); Thread.Sleep(10); } + Check.True(r.B.OneTouchPending(OneTouchVital.Health), "waiting for the kit"); + Check.Eq(FakeHost.Casts.Count, 0, "nothing cast meanwhile"); + + r.B.OnChatWindowText("You heal yourself for 30 Health points.", 0); + Thread.Sleep(800); // the vitals' grace after the result line + Pump(r.B, OneTouchVital.Health); + Check.False(r.B.OneTouchPending(OneTouchVital.Health), "taken once the kit is done"); + Check.Eq(FakeHost.Casts.Count, 1, "one heal, not two"); + Check.Eq(FakeHost.Chat.Count(c => c.StartsWith("[RynthAi] Heal:")), 1, "said once: " + AllChat); + } + + private static void HealGivesUp() + { + var r = Make(CombatMode.Magic, hp: 40); + r.B.MarkKitUsed(); + r.B.RequestOneTouch(OneTouchVital.Health); + // Make the request old, as if it had been waiting OneTouchWaitMs. + var at = (long[])typeof(BuffManager).GetField("_oneTouchAt", Any)!.GetValue(r.B)!; + at[(int)OneTouchVital.Health] = Environment.TickCount64 - BuffManager.OneTouchWaitMs - 100; + r.B.OnHeartbeat(); + Check.False(r.B.OneTouchPending(OneTouchVital.Health), "given up"); + Check.True(Said("Heal: not done, the character stayed busy (a kit is in flight)"), AllChat); + Check.Eq(FakeHost.Casts.Count, 0, "nothing cast"); + } + + private static void StaminaChoice() + { + // A stamina kit first. + var r = Make(CombatMode.Magic, st: 40, stamKit: true); + r.B.RequestOneTouch(OneTouchVital.Stamina); + Pump(r.B, OneTouchVital.Stamina); + Check.True(FakeHost.UsesOn.Any(u => u.Source == StamKit && u.Target == Player), "the stamina kit is used"); + Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize"); + Check.True(Said("Stamina: using a stamina kit"), AllChat); + + // Melee with a listed potion and no kit: the potion, not Revitalize (a wand swap). + r = Make(CombatMode.Melee, st: 40, stamPotion: true); + r.B.RequestOneTouch(OneTouchVital.Stamina); + Pump(r.B, OneTouchVital.Stamina); + Check.True(FakeHost.Uses.Contains(StamPotion), "melee: the stamina potion"); + Check.Eq(FakeHost.Casts.Count, 0, "melee: no Revitalize"); + + // Magic stance, nothing else: Revitalize. + r = Make(CombatMode.Magic, st: 40); + r.B.RequestOneTouch(OneTouchVital.Stamina); + Pump(r.B, OneTouchVital.Stamina); + Check.Eq(FakeHost.Casts.Count, 1, "Revitalize Self"); + Check.True(IsFamily(FakeHost.Casts[0].SpellId, "Revitalize Self I"), "Revitalize Self"); + } + + private static void ManaChoice() + { + var r = Make(CombatMode.Magic, st: 100, mn: 20); + r.B.RequestOneTouch(OneTouchVital.Mana); + Pump(r.B, OneTouchVital.Mana); + Check.Eq(FakeHost.Casts.Count, 1, "one cast"); + Check.True(IsFamily(FakeHost.Casts[0].SpellId, "Stamina to Mana Self I"), "Stamina to Mana Self"); + Check.True(Said("Mana: casting "), AllChat); + + // Stamina at the floor: a stamina kit first, so Stamina to Mana has something to spend. + r = Make(CombatMode.Magic, st: 10, mn: 20, stamKit: true); + r.B.RequestOneTouch(OneTouchVital.Mana); + Pump(r.B, OneTouchVital.Mana); + Check.True(FakeHost.UsesOn.Any(u => u.Source == StamKit), "stamina kit first"); + Check.Eq(FakeHost.Casts.Count, 0, "no Stamina to Mana yet"); + Check.True(Said("stamina first, for Stamina to Mana"), AllChat); + } + + private static void Commands() + { + var r = Make(CombatMode.Magic, hp: 40); + var p = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi }); + typeof(RynthAiPlugin).GetField("_buffManager", Any)!.SetValue(p, r.B); + void Ra(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + + foreach (var (line, vital) in new[] + { + ("/ra heal", OneTouchVital.Health), ("/ra stam", OneTouchVital.Stamina), ("/ra mana", OneTouchVital.Mana), + ("/ra stamina", OneTouchVital.Stamina), ("/ra healme", OneTouchVital.Health), + }) + { + Ra(line); + Check.True(r.B.OneTouchPending(vital), line + " requests " + vital); + r.B.RequestOneTouch(vital); + // Drain it without a heartbeat: the requests are plain flags. + var at = (long[])typeof(BuffManager).GetField("_oneTouchAt", Any)!.GetValue(r.B)!; + at[(int)vital] = 0; + } + + // Before login there is no buff manager: said, not thrown. + typeof(RynthAiPlugin).GetField("_buffManager", Any)!.SetValue(p, null); + FakeHost.Chat.Clear(); + Ra("/ra heal"); + Check.True(Said("Buff manager not ready"), AllChat); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs index 7783e8c..5ff705b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/StuckCastTests.cs @@ -23,9 +23,10 @@ internal static class StuckCastTests { r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy); r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen); - r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump at cycle + 2 s; a normal 4 s cast trips neither", TurnThenJump); + r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump TurnGraceMs after the turn; a normal 4 s cast trips neither", TurnThenJump); + r.Add("stuck cast: already facing the target (no turn), the jump is at cycle + 2 s", JumpWithoutTurn); r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump); - r.Add("stuck cast: a 'too busy' answer while our cast is open past 3 s breaks it at once; before 3 s it does not", RefusalWhileOpen); + r.Add("stuck cast: a 'too busy' answer while our cast is open past its cycle + 1 s (and 3 s) breaks it at once; before, it does not", RefusalWhileOpen); r.Add("stuck cast: StuckCastMs 0 turns nothing and breaks nothing; no TapJump -> Peace mode", BreakerOffAndNoJump); r.Add("move settle: no start in the tick of a movement change; 150 ms and a clear motion queue (or 600 ms) let it go", MoveSettle); r.Add("stuck cast: the HP failsafe's forced break jumps once and holds starts until landed", ForcedBreak); @@ -46,8 +47,8 @@ internal static class StuckCastTests FakeHost.Names[Player] = "Mira"; FakeHost.PlayerPose = Me0; FakeHost.Positions[Player] = Me0; - FakeHost.HeadingDeg = 0; // facing north - FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); // due east: 90 deg off + FakeHost.HeadingDeg = 90; // facing east: no held-cast turn (TurnThenJump faces north) + FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + 10f, Me0.Y, Me0.Z); // due east var host = FakeHost.Create(Player); _t = 90_000_000; ActionPacer.Reset(); @@ -197,7 +198,8 @@ internal static class StuckCastTests Check.Eq(FakeHost.Turns + FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "a normal 4 s cast: no turn, no jump, no mode change"); Check.Eq(ActionPacer.NormalCycleMs(DrainHealthOtherI), 4000L, "the cycle learned from it"); - // The next one is held open: turn at 4 + 1 s, jump at 4 + 2 s. + // The next one is held open, facing north (90 deg off): turn at 4 + 1 s, jump TurnGraceMs later. + FakeHost.HeadingDeg = 0; Cast(host); long sent = _t; while (_t - sent < 4900) { _t += 100; May(host); } @@ -206,11 +208,12 @@ internal static class StuckCastTests Check.Eq(FakeHost.Turns, 1, "turned at cycle + 1 s"); Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "to face the target (east)"); Check.True(FakeHost.Logs.Any(l => l.Contains("held cast:") && l.Contains("turning 90 deg to face 0x80116781")), "logged"); - while (_t - sent < 5900) { _t += 100; Check.False(May(host), "held"); } - Check.Eq(FakeHost.TapJumps, 0, "no jump before cycle + 2 s"); + // 2026-10-16: the jump came 1 s after a 91 deg turn, 0.2 s before the cast's answer. + while (_t - sent < 5000 + ActionPacer.TurnGraceMs - 100) { _t += 100; Check.False(May(host), "held"); } + Check.Eq(FakeHost.TapJumps, 0, "no jump while the turn has its time (cycle + 2 s is past)"); _t += 100; May(host); - Check.Eq(FakeHost.TapJumps, 1, "the breaker jump at cycle + 2 s"); - Check.True(FakeHost.Logs.Any(l => l.Contains("[Pace] stuck cast broken by jump after 6000 ms")), "logged with the time"); + Check.Eq(FakeHost.TapJumps, 1, "the breaker jump TurnGraceMs after the turn"); + Check.True(FakeHost.Logs.Any(l => l.Contains($"[Pace] stuck cast broken by jump after {5000 + ActionPacer.TurnGraceMs} ms")), "logged with the time"); Run(host, 2000); Check.Eq(FakeHost.TapJumps, 1, "one jump"); Check.Eq(FakeHost.Turns, 1, "one turn"); @@ -222,6 +225,22 @@ internal static class StuckCastTests finally { Done(); } } + private static void JumpWithoutTurn() + { + var host = Setup(); + try + { + // Facing the monster (Setup): no turn goes out. + Check.True(May(host), "free"); + Cast(host); + long sent = _t; + while (FakeHost.TapJumps == 0 && _t - sent < 10_000) { _t += 100; May(host); } + Check.Eq(FakeHost.Turns, 0, "no turn"); + Check.Eq(_t - sent, ActionPacer.DefaultCycleMs + ActionPacer.JumpAfterMs, "the jump at cycle + 2 s"); + } + finally { Done(); } + } + private static void AfterTheJump() { var host = Setup(); @@ -279,7 +298,9 @@ internal static class StuckCastTests _t += 100; May(host); Check.Eq(FakeHost.TapJumps, 0, "a 0x1D at 2 s: no jump"); _t += 900; May(host); - Check.Eq(FakeHost.TapJumps, 1, "past RefusalBreakMinMs with a 0x1D in: jump at once (before cycle + 2 s)"); + Check.Eq(FakeHost.TapJumps, 0, "3 s with a 0x1D in, not yet RefusalPastCycleMs past its cycle: no jump (it may have landed, its UseDone due)"); + _t += ActionPacer.RefusalPastCycleMs; May(host); + Check.Eq(FakeHost.TapJumps, 1, "past cycle + 1 s with a 0x1D in: jump at once (before cycle + 2 s)"); Check.True(FakeHost.Logs.Any(l => l.Contains("was refused 'too busy' while it was open")), "the reason is logged"); } finally { Done(); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs index 866ffc6..7046a5d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/WeaponTests.cs @@ -36,6 +36,10 @@ internal static class WeaponTests r.Add("element choice: a matching rending wins for its element", ChoiceRending); r.Add("element choice: a wand always casts its own element (rule, Damage tab, no match)", ChoiceWandCastsOwn); r.Add("element choice: elements the character can't cast are skipped", ChoiceCastable); + r.Add("preferred damage: Melee/Missile/War/Void picks the pool; Auto keeps the first listed kind", PreferredPicksPool); + r.Add("preferred damage: War never casts Nether, Void nothing else; an unusable preference falls back to Auto", PreferredSchools); + r.Add("preferred damage: other-kind slayers, the Default row's weapon and the rule's element obey it; the monster's own pick doesn't", PreferredVsOtherSteps); + r.Add("preferred damage: names parse tolerantly; a new rule is Auto", PreferredParse); r.Add("slayer: beats the weakness and the Monsters rule's damage type", SlayerBeatsWeaknessAndRule); r.Add("slayer: only this monster's own Damage tab weapon beats it, not the DEFAULT row's", SlayerVsDamageTab); r.Add("slayer (owner's rule 2026-10-05): a Slash slayer beats a Pierce weapon the monster is weaker to", SlayerBeatsLowerResist); @@ -231,6 +235,116 @@ internal static class WeaponTests private static bool All(string e) => true; + private static WeaponCandidate Weapon(int id, int kind, string elem = "", bool inHand = false) + => new(id, "Weapon " + id, kind, elem, "", inHand); + + private static void PreferredPicksPool() + { + // A sword listed first, a bow, a fire wand and a nether wand: Auto fights with the first kind (melee). + var list = new List + { + Weapon(1, CombatMode.Melee, "Slash"), Weapon(2, CombatMode.Missile, "Pierce"), + Weapon(3, CombatMode.Magic, "Fire"), Weapon(4, CombatMode.Magic, "Nether"), + }; + var weak = Rank(("Fire", 1.5), ("Nether", 1.4), ("Slash", 1.0), ("Pierce", 1.0)); + Check.Eq(WeaponPlanner.Choose(list, "", weak, All).WeaponId, 1, "Auto: the first listed kind (melee), the Slash sword"); + Check.Eq(WeaponPlanner.Choose(list, "", weak, All, preferredDamage: "Auto").WeaponId, 1, "Auto spelled out"); + + var melee = WeaponPlanner.Choose(list, "", weak, All, preferredDamage: "Melee"); + Check.Eq(melee.WeaponId, 1, "Melee: the sword"); + Check.True(melee.Source.EndsWith("prefers Melee"), "Melee: the source says why (" + melee.Source + ")"); + var missile = WeaponPlanner.Choose(list, "", weak, All, preferredDamage: "Missile"); + Check.Eq(missile.WeaponId, 2, "Missile: the bow, though the monster is weaker to Fire and Nether"); + var war = WeaponPlanner.Choose(list, "", weak, All, preferredDamage: "War Magic"); + Check.Eq(war.WeaponId, 3, "War Magic: the fire wand"); + Check.Eq(war.Element, "Fire", "casting Fire"); + var voidP = WeaponPlanner.Choose(list, "", weak, All, preferredDamage: "Void Magic"); + Check.Eq(voidP.WeaponId, 4, "Void Magic: the nether wand"); + Check.Eq(voidP.Element, "Nether", "casting Nether"); + + // Weakness unknown: the weapon in hand within the pool, else the first of the pool. + var hand = new List + { + Weapon(1, CombatMode.Melee, "Slash", inHand: true), Weapon(2, CombatMode.Magic, "Fire"), Weapon(3, CombatMode.Magic, "Cold"), + }; + Check.Eq(WeaponPlanner.Choose(hand, "", null, All, preferredDamage: "War Magic").WeaponId, 2, "unknown weakness: the first War wand, not the sword in hand"); + } + + private static void PreferredSchools() + { + // A wand with no element: War casts the weakest non-Nether element, Void casts Nether. + var plain = new List { Weapon(1, CombatMode.Magic, "", inHand: true) }; + var weak = Rank(("Nether", 1.6), ("Fire", 1.4), ("Cold", 1.0)); + Check.Eq(WeaponPlanner.Choose(plain, "", weak, All).Element, "Nether", "Auto: the weakest castable, Nether"); + Check.Eq(WeaponPlanner.Choose(plain, "", weak, All, preferredDamage: "War Magic").Element, "Fire", "War Magic: Nether is out, Fire"); + var voidPlain = WeaponPlanner.Choose(plain, "", weak, All, preferredDamage: "Void Magic"); + Check.Eq(voidPlain.WeaponId, 1, "an element-less wand is a War wand: no Void pool, so Auto keeps the same wand"); + Check.False(voidPlain.Source.Contains("prefers"), "and the source doesn't claim the preference"); + + // An unusable preference falls back to Auto and doesn't claim the preference. + var mixed = new List { Weapon(1, CombatMode.Melee, "Slash"), Weapon(2, CombatMode.Magic, "Fire") }; + var noVoid = WeaponPlanner.Choose(mixed, "", null, All, preferredDamage: "Void Magic"); + Check.Eq(noVoid.WeaponId, 1, "no nether wand listed: Auto, the first kind"); + Check.False(noVoid.Source.Contains("prefers"), "and the source doesn't claim the preference"); + var noVoidSkill = WeaponPlanner.Choose( + new List { Weapon(1, CombatMode.Melee, "Slash"), Weapon(2, CombatMode.Magic, "Nether") }, "", null, + e => e != "Nether", preferredDamage: "Void Magic"); + Check.Eq(noVoidSkill.WeaponId, 1, "a nether wand but no Void Magic: Auto"); + var noWarSkill = WeaponPlanner.Choose(mixed, "", null, e => false, preferredDamage: "War Magic"); + Check.Eq(noWarSkill.WeaponId, 1, "a fire wand but nothing castable: Auto"); + var noMissile = WeaponPlanner.Choose(mixed, "", null, All, preferredDamage: "Missile"); + Check.Eq(noMissile.WeaponId, 1, "no launcher listed: Auto"); + Check.Eq(WeaponPlanner.Choose(new List(), "", null, All, preferredDamage: "Melee").WeaponId, 0, "nothing listed: nothing"); + } + + private static void PreferredVsOtherSteps() + { + var list = new List + { + Weapon(1, CombatMode.Melee, "Slash"), Weapon(2, CombatMode.Magic, "Fire"), Weapon(3, CombatMode.Magic, "Nether"), + }; + + // A slayer of another kind is not a candidate (like a melee slayer for a mage). + var slayer = new List + { + new(1, "Sword", CombatMode.Melee, "Slash", "", false, SlayerType: 5, SlayerBonus: 2), + Weapon(2, CombatMode.Magic, "Fire"), + }; + Check.Eq(WeaponPlanner.Choose(slayer, "", null, All, creatureType: 5).WeaponId, 1, "Auto: the melee slayer"); + Check.Eq(WeaponPlanner.Choose(slayer, "", null, All, creatureType: 5, preferredDamage: "War Magic").WeaponId, 2, "War Magic: the slayer isn't used"); + + // The Default row's weapon (fixedIsDefault) only when it is of the preferred kind. + Check.Eq(WeaponPlanner.Choose(list, "", null, All, fixedWeaponId: 1, fixedIsDefault: true, preferredDamage: "War Magic").WeaponId, 2, + "Default row's sword, War Magic preferred: a wand"); + Check.Eq(WeaponPlanner.Choose(list, "", null, All, fixedWeaponId: 2, fixedIsDefault: true, preferredDamage: "War Magic").WeaponId, 2, + "Default row's fire wand, War Magic preferred: kept"); + Check.Eq(WeaponPlanner.Choose(list, "", null, All, fixedWeaponId: 1, fixedIsDefault: true).WeaponId, 1, "Auto: the Default row's sword"); + + // The monster's own Damage tab weapon is the player's explicit pick: it wins. + Check.Eq(WeaponPlanner.Choose(list, "", null, All, fixedWeaponId: 1, fixedIsDefault: false, preferredDamage: "War Magic").WeaponId, 1, + "this monster's own sword pick, War Magic preferred: the sword"); + + // The rule's element picks within the preferred kind; none of it there: stay in the kind. + var cast = WeaponPlanner.Choose(list, "Nether", null, All, preferredDamage: "Void Magic"); + Check.Eq(cast.WeaponId, 3, "rule Nether + Void Magic: the nether wand"); + var other = WeaponPlanner.Choose(list, "Slash", null, All, preferredDamage: "War Magic"); + Check.Eq(other.WeaponId, 2, "rule Slash + War Magic: no Slash wand, so the war wand, not the sword"); + } + + private static void PreferredParse() + { + Check.Eq(DamageStyles.Parse("war magic"), DamageStyle.War, "lower case with a space"); + Check.Eq(DamageStyles.Parse("WarMagic"), DamageStyle.War, "joined"); + Check.Eq(DamageStyles.Parse("Void"), DamageStyle.Void, "short form"); + Check.Eq(DamageStyles.Parse("Void Magic"), DamageStyle.Void, "panel name"); + Check.Eq(DamageStyles.Parse("Melee"), DamageStyle.Melee, "melee"); + Check.Eq(DamageStyles.Parse("Missile"), DamageStyle.Missile, "missile"); + Check.Eq(DamageStyles.Parse(null), DamageStyle.Auto, "null"); + Check.Eq(DamageStyles.Parse("Fire"), DamageStyle.Auto, "unknown"); + foreach (string n in DamageStyles.Names) Check.Eq(DamageStyles.Name(DamageStyles.Parse(n)), n, "round trip " + n); + Check.Eq(new MonsterRule().PreferredDamage, "Auto", "a new rule is Auto"); + } + private static void ChoiceRule() { var wands = new List { Wand(1, "Fire", inHand: true), Wand(2, "Cold") };