RynthSuite/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
Daniel Wallace 23c3359f77 Vitals: no wand swap for a vital spell while a kit or potion heals
Kits are the standard heal, and the shield stays on: putting the shield
away for a wand costs more damage than a small heal spell buys back. A
melee character under Heal At put its shield away and pulled a wand for
Heal Self with kits in the pack; the wand was skipped only at Emergency
Heal At.

CastVital (Heal Self, Stamina to Health, Revitalize, Stamina to Mana and
the script hook's heal) now refuses as not handled when the character is
out of Magic mode, no caster is in hand, and a usable kit or potion for
that vital is carried (BuffManager.VitalWandGate.cs). The chain falls
through to the potion and the kit despite Kit Min Success.

- With no kit and no potion at all the swap is still allowed.
- A caster already wielded still gets the Magic stance change (no weapon
  moves); the wielded-wand check is extracted from EnsureMagicMode into
  IsBuffWandWielded so the gate and the swap agree. With no wand found
  the Magic stance goes bare-handed (no weapon moves): not gated either.
- A swap already under way finishes.
- Stamina to Mana never swaps in a fight (InCombatNow), potion or not;
  out of a fight it may, even with a mana potion carried.
- A kit counts only if the kit picks would use it: the live pack walk,
  minus a kit its line called used up, minus a kit the server refused 3
  times within 10 s. A streak with no refusal for 10 s ages out; a kit
  landing, or the macro stopping, ends every streak.
- The stamina sources share one order (AttemptStaminaRestore) for the
  stamina step, the mana step's refill and the buffing mana floor, ending
  with the stamina kit despite Stamina Kit Min Success % as the last
  resort, since Revitalize is refused here.
- Buffing is unchanged and still swaps.

Tests: VitalWandGateTests (new, 17).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 09:35:14 -08:00

187 lines
9.7 KiB
C#

// ============================================================================
// RynthSuite - Combat/BuffManager.VitalWandGate.cs
// No wand swap for a vital spell while a kit or potion can do the job.
//
// Kits are the standard heal, and the shield stays on: putting the shield away for a wand costs more
// damage than a small heal spell buys back. A melee character under Heal At used to put its shield away
// and pull a wand for Heal Self with kits in the pack (the wand was skipped only at Emergency Heal At).
//
// Out of Magic mode with no caster in hand, a vital spell (Heal Self, Stamina to Health, Revitalize,
// Stamina to Mana, the script hook's heal) would start a weapon swap to the wand. VitalSpellWouldSwap
// refuses it (CastVital: not handled), so the chain falls through to the potion, the kit, and the kit
// despite Kit Min Success. The exceptions:
// - nothing else can restore that vital (no usable kit, no potion Use Potions may drink): the swap is
// the only heal there is, so it goes;
// - a caster already wielded needs only the stance change (no weapon moves): allowed;
// - no wand found (FindWandInItems 0): the Magic stance goes bare-handed and no weapon moves: allowed;
// - a swap already under way finishes (refusing it mid-way left the shield in the pack);
// - Stamina to Mana never swaps in a fight (InCombatNow), potion or not; out of a fight it may, even
// with a mana potion carried (buffing is about to swap to the wand anyway).
// Buffing (EnsureMagicMode forBuff) is not gated and still swaps.
//
// A kit the gate counts is one the kit picks would use: the live pack walk (ConsumableLookup,
// GetDirectInventory), minus a kit its line called used up (BuffManager.KitUsedUp.cs), minus a kit the
// server refused KitRefusedStreakMax times within KitRefusedStreakMs (a UseDone error or "You're too
// busy!" is no answer the kit wait drops, so such a kit would block every spell heal forever). A streak
// with no refusal for KitRefusedStreakMs ages out; a kit landing, or the macro stopping, ends them all.
//
// The stamina sources share one order with a last resort (AttemptStaminaRestore): with Revitalize
// refused here, a stamina kit skipped for Stamina Kit Min Success % would leave nothing.
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
internal const int KitRefusedStreakMax = 3;
internal const double KitRefusedStreakMs = 10_000;
private readonly Dictionary<int, (int Count, DateTime First, DateTime Last)> _kitRefusedStreak = new();
/// <summary>True when the vital spell for <paramref name="label"/> must not start a wand swap now (see the header).</summary>
private bool VitalSpellWouldSwap(string label, out string why)
{
why = "";
if (_wandSwap.Active) return false; // a swap already under way finishes
if (CurrentCombatMode == CombatMode.Magic) return false;
int wandId = FindWandInItems();
if (wandId == 0 || IsBuffWandWielded(wandId)) return false; // bare-handed Magic, or the stance change only: no weapon moves
if (label == LabelMana)
{
if (!InCombatNow()) return false;
why = "no wand swap for Stamina to Mana in a fight (the shield stays on)";
return true;
}
bool other = label == LabelStamina
? HasUsableStaminaKit() || HasAnyPotion("StaminaPotion", "Stamina")
: HasUsableHealthKit() || HasAnyPotion("HealthPotion"); // Healing and the script heal
if (!other) return false;
why = "no wand swap for a vital spell (kits are the standard heal; the shield stays on)";
return true;
}
private void NoteKitRefusedStreak(int kitId)
{
if (kitId == 0) return;
DateTime now = Now;
PruneKitRefusedStreaks(now);
_kitRefusedStreak[kitId] = _kitRefusedStreak.TryGetValue(kitId, out var s) && (now - s.First).TotalMilliseconds <= KitRefusedStreakMs
? (s.Count + 1, s.First, now)
: (1, now, now);
}
/// <summary>Drops streaks with no refusal for KitRefusedStreakMs: the kit counts for the gate again.</summary>
private void PruneKitRefusedStreaks(DateTime now)
{
if (_kitRefusedStreak.Count == 0) return;
List<int>? stale = null;
foreach (var kv in _kitRefusedStreak)
if ((now - kv.Value.Last).TotalMilliseconds > KitRefusedStreakMs) (stale ??= new()).Add(kv.Key);
if (stale != null) foreach (int id in stale) _kitRefusedStreak.Remove(id);
}
/// <summary>Ends every refusal streak (a kit landed, or the macro stopped).</summary>
private void ClearKitRefusedStreaks() => _kitRefusedStreak.Clear();
/// <summary>A kit the gate does not count: called used up, or refused KitRefusedStreakMax times with the last
/// refusal under KitRefusedStreakMs ago.</summary>
private bool KitOutForGate(int id)
{
if (KitUsedUp(id)) return true;
PruneKitRefusedStreaks(Now);
return _kitRefusedStreak.TryGetValue(id, out var s) && s.Count >= KitRefusedStreakMax;
}
/// <summary>A healing kit AttemptHealthKitUse could pick (a listed one, else the pack's).</summary>
private bool HasUsableHealthKit()
{
if (_worldObjectCache == null) return false;
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_worldObjectCache, r, KitOutForGate) is WorldObject wo
&& IsUseOnSelfKit(wo))
return true;
return HasPackKit("Healing Kit");
}
/// <summary>A stamina kit AttemptStaminaKitUse could pick.</summary>
private bool HasUsableStaminaKit() => _host.HasUseObjectOn && HasPackKit("Stamina Kit");
/// <summary>A kit named "... <paramref name="suffix"/>" in the pack the gate still counts (BestPack*Kit's match).</summary>
private bool HasPackKit(string suffix)
{
if (_worldObjectCache == null) return false;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
if ((wo.Name ?? "").EndsWith(suffix, StringComparison.OrdinalIgnoreCase) && !KitOutForGate(wo.Id))
return true;
return false;
}
/// <summary>A potion of <paramref name="types"/> AttemptPotion could drink (listed or in the pack), with Use Potions on.</summary>
private bool HasAnyPotion(params string[] types)
{
if (!_settings.UsePotions || _worldObjectCache == null) return false;
if (HasListedPotion(types)) return true;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
{
string? kind = LegacyWeaponsUi.PotionType(wo);
if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue;
if (IsKitName(wo.Name)) continue;
return true;
}
return false;
}
/// <summary>
/// The stamina sources in order, shared by the stamina step, the mana step's refill (AttemptManaRefill)
/// and the buffing mana floor: a kit, a listed potion first when <paramref name="listedPotionFirst"/>,
/// Revitalize, any potion, then the kit Stamina Kit Min Success % skipped as the last resort.
/// </summary>
private bool AttemptStaminaRestore(bool listedPotionFirst = false)
{
if (AttemptStaminaKit(false, out bool underMinSuccess)
|| (listedPotionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
|| AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina"))
return true;
// Last resort, as the heal chain's: the stamina kit Stamina Kit Min Success % skipped. With
// Revitalize refused by the wand gate and no potion, nothing else restores stamina.
if (underMinSuccess && AttemptStaminaKit(true, out _))
{
_host.Log("[RynthAi] Vitals: no spell or potion could restore stamina; using the stamina kit despite Stamina Kit Min Success %.");
return true;
}
return false;
}
/// <summary>
/// True when <paramref name="wandId"/> (FindWandInItems' pick) is in the player's hand: EnsureMagicMode
/// then needs no weapon move, only the stance change. Shared by EnsureMagicMode and VitalSpellWouldSwap.
/// </summary>
private bool IsBuffWandWielded(int wandId)
{
if (wandId == 0) return false;
// Primary check: CurrentWieldedLocation (stype=10) - works even before the
// phys-obj offset probe fires, mirrors CombatManager.EquipWeaponAndSetStance.
bool alreadyWielded = false;
var wandObj = _worldObjectCache?[wandId];
if (wandObj != null)
alreadyWielded = wandObj.Values(LongValueKey.CurrentWieldedLocation, 0) > 0;
// Secondary check via API if primary didn't confirm
if (EquippedState.IsWielded(_host, wandId) is bool trackedWand) alreadyWielded = trackedWand; // the server's word
else if (!alreadyWielded && _host.HasGetObjectWielderInfo)
{
uint playerId = _host.GetPlayerId();
if (playerId != 0 &&
_host.TryGetObjectWielderInfo((uint)wandId, out uint wielder, out _) &&
wielder == playerId && _worldObjectCache?.InPackWalk(wandId) != true) // a stale record (the wand in a pack)
alreadyWielded = true;
}
return alreadyWielded;
}
}