diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs new file mode 100644 index 0000000..71ce66b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.ScriptHook.cs @@ -0,0 +1,104 @@ +using System; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +// The heal seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs): +// CheckVitals asks the script for the heal spell (and its target: the player, or a monster for a +// drain) before kits. The cast itself goes through CastVital, the same steps as Heal Self. +public partial class BuffManager +{ + /// + /// True when the hook handled this vitals check: waiting for the answer, or the answer was + /// cast (or its wand swap is in flight). False = the native order (kit, Heal Self, potion). + /// + private bool TryScriptHeal(int healLine, bool inCombat) + { + // AC just said "You're too busy!": the same pacing as a Heal Self (AttemptVitalCast). + if (DateTime.Now < _busyBackoffUntil && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs) + { + _vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms"; + _healWaitKind = "too-busy backoff"; + return true; + } + + var slot = CombatHook.Heal; + // The request names RynthAi's current fight target (informational: the monster with live + // health data, e.g. for a drain); a fight target change re-asks. The answer's target 0 + // still means the player. + var cm = _combatManager; + uint fight = cm == null ? 0u : unchecked((uint)cm.activeTargetId); + var outcome = CombatHook.Step(slot, fight, () => BuildHealRequest(healLine, inCombat), s => _host.Log(s), + out uint spell, out uint target, out _); + switch (outcome) + { + case CombatHook.Outcome.Native: + return false; + case CombatHook.Outcome.Wait: + _vitalWhy = $"waiting for '{CombatHook.Owner}' to choose the heal"; + _healWaitKind = "script choosing the heal"; + return true; + } + + uint player = (uint)_host.GetPlayerId(); + if (target == 0) target = player; + string? why = ScriptHealProblem(spell, target, player); + if (why != null) + { + CombatHook.Reject(slot, why, s => _host.Log(s)); + return false; + } + string name = SpellTableStub.GetById((int)spell)?.Name ?? $"spell {spell}"; + bool handled = CastVital((int)spell, target, LabelHealing, name + " (script)", out bool sent); + if (!handled) + { + CombatHook.Reject(slot, _vitalWhy.Length > 0 ? _vitalWhy : "it couldn't be cast", s => _host.Log(s)); + return false; + } + // A script-chosen heal takes no early nudge (HeldNudgeUrgent): its result can come later + // than RynthAi's own heals' (Vitality Siphon: 2.42-2.75 s after the incantation, 2026-10-10 + // log), or never (a resisted or dead target), and an early nudge steps the character. + if (sent && _cast.Current is { } sentCast && sentCast.SpellId == (int)spell) sentCast.Script = true; + // Handled: cast, or a swap step to Magic mode is in flight (the next check asks again). + CombatHook.Cast(slot, sent ? spell : 0, sent ? target : 0); + if (sent) _host.Log($"[RynthAi] Vitals: script heal id={spell} '{name}' at 0x{target:X8} (owner '{CombatHook.Owner}')."); + return true; + } + + /// Why the script's heal can't be cast, or null when it can. + private string? ScriptHealProblem(uint spell, uint target, uint player) + { + if (!_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known"; + // The refusal memory RynthAi's own heal honours (AttemptVitalCast): a level the server + // said there are no components for. + if (LevelLacksComponents((int)spell)) return $"spell {spell} has no components (refused by the server; RynthAi uses a lower level)"; + if (target == player) return null; + var cm = _combatManager; + bool listed = cm != null && unchecked((uint)cm.activeTargetId) == target; + if (!listed && cm != null) + foreach (var t in cm.ScannedTargets) + if (unchecked((uint)t.Id) == target) { listed = true; break; } + if (!listed) return "the target is not the player, the fight target or a scanned monster"; + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(target)) return "the target is not attackable"; + return null; + } + + private CombatRequestV1 BuildHealRequest(int healLine, bool inCombat) + { + bool known = _vitals.MaxHealth > 0; + var cm = _combatManager; + float fightHealth = cm?.FightTargetHealthRatio ?? -1f; + return new CombatRequestV1 + { + TargetHealth = fightHealth, + HealthPct = known ? _vitals.HealthPct : -1, + StaminaPct = _vitals.MaxStamina > 0 ? _vitals.StaminaPct : -1, + ManaPct = _vitals.MaxMana > 0 ? _vitals.ManaPct : -1, + HealLine = healLine, + InCombat = inCombat ? 1 : 0, + CombatMode = CurrentCombatMode, + }; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index 15c1682..0bcf5e5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -6,7 +6,7 @@ using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi; -public class BuffManager : IDisposable +public partial class BuffManager : IDisposable { private readonly RynthCoreHost _host; private readonly LegacyUiSettings _settings; @@ -453,6 +453,19 @@ public class BuffManager : IDisposable /// mana is under the spell's own cost (it would be refused), or under the refill line while /// vitals can refill it (Stamina to Mana goes first). /// + /// + /// For CombatManager's script hook, before : false when + /// costs more than the character's max mana, so the cost hold would + /// never lift. Same cost source and the same guards as OffensiveCastHold (no hold, no veto: + /// macro off, or max mana unknown); an unknown cost (0) is affordable. + /// + internal bool CanEverAfford(int spellId) + { + if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return true; + int cost = SpellManaCost(spellId); + return cost <= 0 || cost <= _vitals.MaxMana; + } + internal string? OffensiveCastHold(int spellId) { if (!_settings.IsMacroRunning || _vitals.MaxMana == 0) return null; @@ -1681,6 +1694,15 @@ public class BuffManager : IDisposable // works: no spell, Life Magic untrained, or out of components). if (curHealthPct < hpThreshold) { + // A script holding the heal kind (RynthAi.Combat) is asked first, before kits: a class + // that heals by draining monsters must not have a kit pre-empt it. The emergency step + // above stays native (the safety floor). Waiting for the answer counts as handled; a + // decline, a bad answer or no answer in time falls through to kit, Heal Self, potion. + if (CombatHook.IsActive(RynthAiCombat.KindHeal) && TryScriptHeal(hpThreshold, inCombat)) + { + _isHealingSelf = true; + return true; + } _vitalWhy = ""; bool healed = AttemptHealthKitUse(); string kitWhy = _vitalWhy; @@ -1929,6 +1951,20 @@ public class BuffManager : IDisposable spellId = payable; } } + return CastVital(spellId, (uint)_host.GetPlayerId(), VitalLabel(baseName), baseName, out _); + } + + /// + /// The cast step of a vital spell, shared by AttemptVitalCast (self vitals) and the script + /// hook's heal (a drain at a monster id goes through the same steps): the family park, the + /// wand swap / Magic stance, the pending-vital bookkeeping (confirmed by chat; released with + /// no strike when the line is late) and the heal latency. Returns "handled" as + /// AttemptVitalCast does (true also while a swap step is in flight); + /// says whether the cast actually went out. + /// + private bool CastVital(int spellId, uint targetId, string label, string what, out bool sent) + { + sent = false; // Parked after a hard server refusal (see OnChatWindowText) — the same // per-family cooldown the buff selectors honour. int family = SpellTableStub.GetById(spellId)?.Family ?? 0; @@ -1938,7 +1974,7 @@ public class BuffManager : IDisposable return VitalNo($"parked for {(coolUntil - DateTime.Now).TotalSeconds:0} s more after a refusal or no-show"); if (CurrentCombatMode != CombatMode.Magic && DateTime.Now < _vitalSwapBlockedUntil) return VitalNo("wand swap blocked, retrying shortly"); - bool urgentHeal = baseName is "Heal Self" or "Stamina to Health Self" && HealIsUrgent(_vitals.HealthPct, _vitals.StaminaPct); + bool urgentHeal = label == LabelHealing && 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 @@ -1952,21 +1988,22 @@ public class BuffManager : IDisposable // strike. Mirror the buff path: not handled, so the potion gets its turn. _pendingSpellId = spellId; _pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry - _pendingVitalLabel = VitalLabel(baseName); - bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", - SpellTableStub.GetById(spellId)?.Name ?? baseName); + _pendingVitalLabel = label; + bool castOk = _host.CastSpellFor(targetId, spellId, "Buff", + SpellTableStub.GetById(spellId)?.Name ?? what); _lastCastAttempt = DateTime.Now; if (!castOk) { _pendingSpellId = 0; return VitalNo($"the client refused the cast (spell {spellId})"); } + sent = true; NoteCastIssued(spellId); if (_pendingVitalLabel == LabelMana) _manaStarvedLogged = false; // the next starved spell logs again if (_pendingVitalLabel == LabelHealing) { _healSpellIds.Add(spellId); - _healLatency.HealSent(Now, baseName); + _healLatency.HealSent(Now, what); } return true; } @@ -3733,15 +3770,47 @@ public class BuffManager : IDisposable return; } + // A script heal (a transfer such as Vitality Siphon) cast at a monster that resists it: + // "Doorheld Surveyor resists your spell" is its only result, no "due to casting" line + // follows. Closed here as CombatManager reads the same line for its own casts. + if (lower.Contains("resists your spell")) + { + var c = _cast.Open is { Done: false } o ? o + : _cast.Current is { Done: false, Refused: false } cur ? cur : null; + if (c != null && c.Script) + { + _cast.Result(null, "resisted"); + _host.Log($"[BuffChat] script heal '{c.Name}' resisted; pending={_pendingSpellId} cleared."); + _pendingSpellId = 0; + _onCastResolved?.Invoke("resisted"); + return; + } + } + // "You cast Incantation of Flame Bane on Gelidite Robe, refreshing ..." // "You cast Strength Self VIII" // The leading 'Y' is stripped by AC's chat-glyph layer before our handler // sees it — text actually arrives as "ou cast …". IndexOf works for both. + // A transfer to the caster names the spell after "due to casting " instead. + const string DueToCasting = "due to casting "; int castIdx = lower.IndexOf("ou cast ", StringComparison.Ordinal); + int skip = 8; // "ou cast " + bool viaDueToCasting = false; + if (castIdx < 0) + { + // A transfer to the caster names the spell after "due to casting": "You gain 51 points + // of health due to casting Vitality Siphon on Doorheld Surveyor" (a heal the script + // hook casts at a monster). Unread, the heal stayed "held" and its early nudge (autorun + // on/off) went out mid-cast: the character stepped forward (2026-10-10 log, 13 of 14 + // nudges). + castIdx = lower.IndexOf(DueToCasting, StringComparison.Ordinal); + skip = DueToCasting.Length; + viaDueToCasting = castIdx >= 0; + } if (castIdx < 0) return; - // Extract spell name: everything after "ou cast " up to " on " or "," - string afterCast = text.Substring(castIdx + 8); // skip "ou cast " + // Extract spell name: everything after "ou cast " (or "due to casting ") up to " on " or "," + string afterCast = text.Substring(castIdx + skip); int onIdx = afterCast.IndexOf(" on ", StringComparison.OrdinalIgnoreCase); int commaIdx = afterCast.IndexOf(','); int endIdx = afterCast.Length; @@ -3753,6 +3822,18 @@ public class BuffManager : IDisposable // line, "You cast Revitalize Self V and restore 70 points...", has no " on " or comma). var tracked = _cast.Result(afterCast, "result"); + // A "due to casting" line that matches no open cast is only a result when it names the + // pending spell (its cast closed first, on a UseDone). Otherwise it is not ours to read: + // one transfer can print several lines (Crimson Harvest, 2026-10-10), and RynthAi's own + // drain attacks (CombatManager, never tracked here) print one each. Read as results they + // recorded a timer, ended a too-busy backoff and resolved a cast that was still running. + if (viaDueToCasting && tracked == null) + { + string? pendingName = _pendingSpellId != 0 ? SpellTableStub.GetById(_pendingSpellId)?.Name : null; + if (pendingName == null || !string.Equals(spellName, pendingName, StringComparison.OrdinalIgnoreCase)) + return; + } + // Try to find the spell by name first (authoritative — this is what was actually cast) int spellId = SpellDatabase.GetIdByName(spellName); SpellInfo? spellInfo = spellId > 0 ? SpellTableStub.GetById(spellId) : null; @@ -3803,7 +3884,7 @@ public class BuffManager : IDisposable var ps = SpellTableStub.GetById(_pendingSpellId); if (ps != null) _forceRebuffCastFamilies.Add(ps.Family); } - _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via ou-cast match name='{spellName}' resolvedId={spellId}"); + _host.Log($"[BuffChat] CLEARED pending={_pendingSpellId} via {(viaDueToCasting ? "due-to-casting" : "ou-cast")} match name='{spellName}' resolvedId={spellId}"); } _pendingSpellId = 0; _onCastResolved?.Invoke($"cast '{spellName}'"); @@ -3897,11 +3978,12 @@ public class BuffManager : IDisposable SendCastNudge(urgent: true); } - /// The held cast is a heal, or health is under a heal line: nudge it early. + /// The held cast is a heal, or health is under a heal line: nudge it early. Never a + /// cast the script hook chose (CastTracker.Cast.Script): those wait HeldAfterIncantMs. private bool HeldNudgeUrgent() { var held = _cast.Held; - if (held == null) return false; + if (held == null || held.Script) return false; return IsHealCast(held.SpellId) || (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct)); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs index 7d64663..b6f92c1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CastTracker.cs @@ -38,6 +38,9 @@ internal sealed class CastTracker public bool Done; // its result line, or UseDone(0) after its incantation public bool Nudged; // the one movement nudge for this held cast has gone out public bool StuckLogged; + // The script combat hook chose this cast (a heal): no early nudge, HeldAfterIncantMs only. + // A Vitality Siphon's result can come 2.75 s after its incantation (2026-10-10 log). + public bool Script; public bool HasIncantation => IncantAt != DateTime.MinValue; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs new file mode 100644 index 0000000..e0aeda2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.ScriptHook.cs @@ -0,0 +1,285 @@ +using System; +using RynthCore.PluginSdk; +using RynthCore.Plugin.RynthAi.Combat; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +// The attack seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs): +// with a script holding the attack kind, AttackWithMagic asks it for the spell after its debuffs +// and before its own shape choice. RynthAi keeps everything around the cast: the scan, the +// target lock, the stance, the cadence and busy gates, and the cast bookkeeping. The script only +// names the spell (and optionally another scanned monster, or the player). +public partial class CombatManager +{ + // True on a tick where AttackWithMagic sent nothing because it is waiting on the script's + // answer: Think then ends the tick without stamping lastAttackCmd (like the wall hold). + private bool _scriptHeld; + + /// The player's vitals, for the hook's request (set by the plugin; null in tests that don't need it). + internal PlayerVitalsCache? Vitals { get; set; } + + /// The fight target's last known health ratio (0-1), or -1 when unknown or no target. + internal float FightTargetHealthRatio => activeTargetId == 0 ? -1f : _worldFilter.GetHealthRatio(activeTargetId); + + /// Host tests: true after a tick that held for the script's answer. + internal bool ScriptHeld => _scriptHeld; + + /// + /// True when the hook handled this attack cycle: held for the answer, or cast the script's + /// spell. False = RynthAi chooses as usual (no hook, a decline, a rejected answer, a timeout). + /// + private bool TryScriptAttack(WorldObject target, string element) + { + if (!CombatHook.IsActive(RynthAiCombat.KindAttack)) return false; // no hook: no per-tick lambdas + var slot = CombatHook.Attack; + uint forTarget = unchecked((uint)activeTargetId); + var outcome = CombatHook.Step(slot, forTarget, () => BuildAttackRequest(target), s => _host.Log(s), + out uint spell, out uint castTarget, out uint flags); + switch (outcome) + { + case CombatHook.Outcome.Native: + return false; + case CombatHook.Outcome.Wait: + _scriptHeld = true; + LastCombatSkipReason = "script-wait"; // D4 record-only + return true; + } + + if (castTarget == 0) castTarget = forTarget; + string? why = ScriptAttackProblem(spell, castTarget); + if (why != null) + { + CombatHook.Reject(slot, why, s => _host.Log(s)); + return false; + } + // A spell that costs more than max mana can never be paid, so the mana hold below would + // never lift: rejected, and RynthAi chooses its own spell this same tick. + bool affordable = true; + try { affordable = ManaCanEverAfford?.Invoke((int)spell) ?? true; } catch { affordable = true; } + if (!affordable) + { + CombatHook.Reject(slot, "costs more than max mana", s => _host.Log(s)); + return false; + } + // RynthAi's mana reserve holds the script's spell as it holds its own (ManaHoldsCast: mana + // under the spell's cost, or under the reserve kept for Stamina to Mana): nothing is sent, + // Think ends the tick on _manaCastHeld, and the answer is kept for the next tick. It is not + // a rejection, so RynthAi does not cast a spell of its own choosing instead. Once the + // request is past its deadline + StaleGraceMs, Step drops the answer and asks again. + if (ManaHoldsCast((int)spell)) return true; + if (!IssueScriptCast((int)spell, castTarget, flags, element)) + { + CombatHook.Reject(slot, "the client refused the cast", s => _host.Log(s)); + return false; + } + CombatHook.Cast(slot, spell, castTarget); + return true; + } + + /// Why the script's answer can't be cast, or null when it can. + private string? ScriptAttackProblem(uint spell, uint castTarget) + { + if (_spellManager == null || !_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known"; + // A script spell the server refused outright (no components): parked like a vital level. + if (_scriptParkedUntil.TryGetValue((int)spell, out DateTime parked) && DateTime.Now < parked) + return $"spell {spell} was refused by the server, parked for {(parked - DateTime.Now).TotalSeconds:0} s more"; + uint player = _playerId != 0 ? _playerId : _host.GetPlayerId(); + if (castTarget == player) return null; + bool listed = castTarget == unchecked((uint)activeTargetId); + for (int i = 0; !listed && i < _scannedTargets.Count; i++) + if (unchecked((uint)_scannedTargets[i].Id) == castTarget) listed = true; + if (!listed) return "the target is not the fight target, a scanned monster or the player"; + // The same veto as RynthAi's own casts: never offensive magic at something AC says isn't attackable. + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(castTarget)) return "the target is not attackable"; + return null; + } + + private CombatRequestV1 BuildAttackRequest(WorldObject target) + { + var v = Vitals; + bool vitalsKnown = v != null && v.MaxHealth > 0; + return new CombatRequestV1 + { + TargetHealth = _worldFilter.GetHealthRatio(activeTargetId), + HealthPct = vitalsKnown ? v!.HealthPct : -1, + StaminaPct = vitalsKnown && v!.MaxStamina > 0 ? v.StaminaPct : -1, + ManaPct = vitalsKnown && v!.MaxMana > 0 ? v.ManaPct : -1, + HealLine = 0, + InCombat = 1, + CombatMode = CurrentCombatMode, + }; + } + + /// + /// Sends the script's spell with RynthAi's own cast bookkeeping: the cadence guard + /// (MarkCombatCastIssued), the attack interval and the area flag. The pending-offensive + /// judgement (blacklist on no damage) is armed only for a single-target cast at the fight + /// target without NOJUDGE. A damaging cast at the fight target (not NOJUDGE) is tagged for + /// the Damage tab like RynthAi's own: wielded wand, element and level from the spell, the + /// fight's cast count and the last-fight snapshot; a single-target one also runs the + /// kill-shot prediction (EvaluateKillShot), as RynthAi's own cast does. + /// + private bool IssueScriptCast(int spellId, uint castTarget, uint flags, string fallbackElement) + { + bool area = (flags & RynthAiCombat.FlagArea) != 0; + bool noJudge = (flags & RynthAiCombat.FlagNoJudge) != 0; + string name = SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}"; + bool ok; + try { ok = _host.CastSpellFor(castTarget, spellId, "Combat", name + " (script)"); } + catch { ok = false; } + if (!ok) return false; + + MarkCombatCastIssued(); + StartCastChatTrace(spellId, unchecked((int)castTarget)); // the server's answers, logged as for RynthAi's own casts + SessionAttackCasts++; + CastsSinceLastKill++; + _lastSpellCast = DateTime.Now; + _scriptCastSpellId = spellId; + _scriptCastAt = DateTime.Now; + _scriptCastSent = ActionPacer.CastsSent; // includes this cast: any later send changes it + bool atFight = castTarget == unchecked((uint)activeTargetId); + bool judged = atFight && !area && !noJudge; + _lastCastWasRing = !judged; // anything else gets no per-target judgement + _wallFaceAt = DateTime.MinValue; + if (judged) + { + // What the NO DAMAGE report names as the last cast (ReportNoDamageCasts). + _lastOffensiveCastLine = $"script id={spellId} '{name}' target=0x{castTarget:X8}"; + _pendingOffensiveSpellId = spellId; + _pendingOffensiveCastAt = DateTime.Now; + _pendingOffensiveTargetId = activeTargetId; + } + // As the native block: a throw here must not fail the cast that already went out (the + // slot would stay Decided and the same answer be cast again). + // A single-target damaging cast at the fight target also takes part in RynthAi's kill-shot + // swap (Think arms it, the deferred swap moves on while the projectile flies), with the + // weapon, element and tier just tagged. Area, nojudge and off-target casts never do. + _predictKillSwap = false; + if (atFight && !noJudge) + { + try + { + TagScriptCast(spellId, area, fallbackElement); + if (!area) EvaluateKillShot(_lastCastWeaponId, _lastCastElement, _lastCastTier, isRing: false); + } + catch { } + } + LastCombatSkipReason = "script-cast"; // D4 record-only + string tags = (area ? " (area)" : "") + (noJudge ? " (nojudge)" : ""); + _host.Log($"[CombatCast] script id={spellId} '{name}' at 0x{castTarget:X8}{tags} " + + $"fight=0x{activeTargetId:X8} owner='{CombatHook.Owner}'"); + return true; + } + + /// + /// The damage attribution RynthAi's own cast does (AttackWithMagic), for a script's cast at + /// the fight target: the weapon, element and tier the pushed damage is filed under, the + /// Damage tab's latest tier, the casts-to-kill count and the last-fight snapshot. + /// + private void TagScriptCast(int spellId, bool area, string fallbackElement) + { + int castWand = InHandWeaponId(); + if (castWand == 0 || !IsWandObject(_worldFilter[castWand] ?? new WorldObject(0, ""))) castWand = FindWandInItems(); + _lastCastWeaponId = unchecked((uint)castWand); + // No element in the spell (a Life drain, say) on a caster with no War or Void: the plan's + // element (a weapon-weakness pick like "Slash") would be wrong, so it is filed under + // "Physical", the key RynthAi's own damage path already uses for vital drains. + _lastCastElement = ScriptSpellElement(spellId) ?? (AttackMagicTrained ? fallbackElement : "Physical"); + int castLevel = SpellTableStub.GetById(spellId)?.Level ?? 0; + if (castLevel <= 0 && SpellDatabase.TryGetCategoryAndPower(spellId, out _, out int castPower)) + castLevel = SpellDatabase.LevelFromPower(castPower); + if (castLevel <= 0) + castLevel = Math.Max(_spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0, + _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0); + _lastCastTier = area ? -castLevel : castLevel; // area casts filed with the rings (negative) + if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName); + _fightCastCount++; + if (_fightTargetWcid != 0) + { + _lastFightWcid = _fightTargetWcid; + _lastFightName = _worldFilter[activeTargetId]?.Name ?? _fightTargetName; + _lastFightWeaponId = _lastCastWeaponId; + _lastFightElement = _lastCastElement; + _lastFightTier = _lastCastTier; + _lastFightCount = _fightCastCount; + StampRecentFight(); + } + } + + /// + /// The element of a war/void attack spell, from RynthAi's own shape tables (base name, tier-7 + /// lore names, ring lore names, wall categories), else from its name's words; null when + /// none of those says. + /// + internal static string? ScriptSpellElement(int spellId) + { + string? name = SpellTableStub.GetById(spellId)?.Name; + if (string.IsNullOrEmpty(name)) return null; + string n = name.Trim(); + if (n.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) n = n.Substring(15).Trim(); + int sp = n.LastIndexOf(' '); + if (sp > 0 && IsRoman(n.Substring(sp + 1))) n = n.Substring(0, sp); + + // Blade and Slash share their spells: answer Slash (the Damage tab's element name). + foreach (var kv in SpellShapes) + if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase) + && Array.Exists(kv.Value, b => b.Equals(n, StringComparison.OrdinalIgnoreCase))) + return kv.Key; + foreach (var table in new[] { WarTier7Lore, RingLoreNames }) + foreach (var kv in table) + if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase) + && Array.Exists(kv.Value, b => b.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase))) + return kv.Key; + if (SpellDatabase.TryGetCategoryAndPower(spellId, out int category, out _)) + foreach (var kv in WallCategories) + if (kv.Value == category && !kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)) return kv.Key; + string byWords = PetChoice.ElementFromName(name); + return byWords.Length > 0 ? byWords : null; + + static bool IsRoman(string s) + { + if (s.Length == 0) return false; + foreach (char c in s) if (c != 'I' && c != 'V' && c != 'X') return false; + return true; + } + } + + // -- Refusal memory for script casts -- + + // The script's last cast, while it is still the last cast this plugin sent (ActionPacer counts + // every send: combat, buffs and heals, nav, commands, meta): a hard refusal arriving soon after + // it is the script spell's, and parks that spell. Forgotten once any other cast goes out, the + // spell's own success line arrives, or the window passes. + private int _scriptCastSpellId; + private DateTime _scriptCastAt = DateTime.MinValue; + private long _scriptCastSent; + private readonly System.Collections.Generic.Dictionary _scriptParkedUntil = new(); + + /// How long a script spell the server refused outright is rejected (as BuffManager parks a vital level). + internal const double ScriptParkSec = 600.0; + /// A refusal later than this after the script's cast is not attributed to it. + internal const double ScriptRefusalWindowMs = 2_000.0; + + /// Host tests: true while is parked after a refusal. + internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && DateTime.Now < u; + + /// A chat line: park the script's last spell on a hard refusal (missing components, unknown spell). + private void NoteScriptCastRefusal(string text) + { + if (_scriptCastSpellId == 0) return; + if (ActionPacer.CastsSent != _scriptCastSent + || (DateTime.Now - _scriptCastAt).TotalMilliseconds > ScriptRefusalWindowMs) { _scriptCastSpellId = 0; return; } + string lo = text.ToLowerInvariant(); + string? own = SpellTableStub.GetById(_scriptCastSpellId)?.Name; + if (own != null && lo.Contains("ou cast " + own.ToLowerInvariant())) { _scriptCastSpellId = 0; return; } // it landed + if (!(lo.Contains("missing some required") || lo.Contains("you do not have the") + || lo.Contains("have all the components for this spell"))) return; + int spell = _scriptCastSpellId; + _scriptCastSpellId = 0; + _scriptParkedUntil[spell] = DateTime.Now.AddSeconds(ScriptParkSec); + _host.Log($"[CombatCast] script spell id={spell} '{SpellTableStub.GetById(spell)?.Name}' refused: '{text.Trim()}'. " + + $"Rejected for {ScriptParkSec / 60:0} min (RynthAi chooses instead while the script asks for it)."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 21bbf75..1bffe3b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -296,6 +296,11 @@ public partial class CombatManager : IDisposable /// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11). /// public Func? ManaReserveHold { get; set; } + /// + /// BuffManager.CanEverAfford, for the script hook: false when a spell costs more than max mana, + /// so ManaReserveHold would hold it forever. Null hook = always affordable. + /// + public Func? ManaCanEverAfford { get; set; } private bool _manaCastHeld; // AttackWithMagic held its cast for mana this tick private bool _manaHoldLogged; @@ -787,6 +792,9 @@ public partial class CombatManager : IDisposable PickedWeaponWieldLoc = weaponWieldLoc, HasWieldedAmmoFlag = hasAmmo, LastCombatSkipReason = LastCombatSkipReason, + ScriptHookOwner = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Owner : "", + ScriptHookKinds = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Kinds : 0, + ScriptHook = CombatHook.Describe(), }; } @@ -817,6 +825,11 @@ public partial class CombatManager : IDisposable public int PickedWeaponWieldLoc; public bool HasWieldedAmmoFlag; public string LastCombatSkipReason; + /// The script holding the combat hook (RynthAi.Combat), "" when none; and its kinds (RynthAiCombat.Kind* bits). + public string ScriptHookOwner; + public uint ScriptHookKinds; + /// The hook's one-line summary (owner, lease, per-kind counters). + public string ScriptHook; } /// @@ -1530,6 +1543,9 @@ public partial class CombatManager : IDisposable // BuffManager's categorisation so a war spell the char can't actually // cast gets marked unresolvable and FindBestOffensiveSpellId drops to // an alternative, instead of silently re-firing the dead spell forever. + // A script's cast (RynthAi.Combat) is remembered on its own: it may not have armed the + // pending judgement (an area, nojudge or off-target cast) yet must not be re-cast forever. + NoteScriptCastRefusal(text); if (_pendingOffensiveSpellId != 0) { string lo = text.ToLowerInvariant(); @@ -3141,6 +3157,15 @@ public partial class CombatManager : IDisposable return true; } + // Waiting on a script's choice of spell (RynthAi.Combat): nothing was sent. The same + // as the wall hold: the attack interval doesn't start, the target and scan stay as they + // are, and the next tick asks again (bounded by the request's deadline). + if (_scriptHeld) + { + _tickWait = CombatLatencyTracker.Wait.Other; + return true; + } + // Don't restore the physical weapon on top of a cast just issued this tick // (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would // truncate the in-flight gesture and strand Player.IsBusy. Defer one windup @@ -4039,11 +4064,32 @@ public partial class CombatManager : IDisposable /// The Items list's usable weapons, in list order, with their kind, element, rending and whether each is in hand. internal List ListedCandidates() { + var list = ListedCandidates(admitCasters: false, out List? leftOut); + // A script choosing the attack spells (RynthAi.Combat) can attack with a caster whatever + // War/Void training says, but only when the list has no melee/missile weapon to use: + // a fighter's listed buff wand must not pull it out of melee. + if (list.Count == 0 && leftOut != null && ScriptPicksAttack) + return ListedCandidates(admitCasters: true, out _); + if (list.Count == 0 && leftOut != null) + foreach (int id in leftOut) + if (_wandRejectedNoted.Add(id)) + _host.Log($"[EquipDiag] caster 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' is not a combat weapon: {CanMagicDiag()}"); + return list; + } + + /// Take listed casters even with War and Void untrained. + /// The casters skipped for that (null when none). + private List ListedCandidates(bool admitCasters, out List? leftOut) + { + leftOut = null; int inHand = InHandWeaponId(); var list = new List(); foreach (var r in _settings.ItemRules) { - if (r.Id == 0 || !IsUsableCombatWeapon(r.Id)) continue; + if (r.Id == 0) continue; + var cand = _worldFilter[r.Id]; + if (cand == null) continue; + if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List()).Add(r.Id); continue; } if (list.Any(c => c.Id == r.Id)) continue; var wo = _worldFilter[r.Id]; if (wo == null) continue; @@ -4290,7 +4336,7 @@ public partial class CombatManager : IDisposable if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5) { _lastEquipDiagAt = DateTime.Now; - _host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}') — proceeding unarmed"); + _host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}', {CanMagicDiag()}) - proceeding unarmed"); } return EnsureUnarmedStance(); } @@ -5299,6 +5345,7 @@ public partial class CombatManager : IDisposable { _wallFaceHeld = false; _manaCastHeld = false; + _scriptHeld = false; if (_spellManager == null || target == null) return; // Hard safety veto: never cast offensive magic at something AC's combat @@ -5399,6 +5446,11 @@ public partial class CombatManager : IDisposable } } + // A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for + // its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no + // answer in time falls through to RynthAi's own choice below, this same tick. + if (TryScriptAttack(target, element)) return; + if (rule != null && PickBaseShape(rule) < 0) { _host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast"); @@ -5596,13 +5648,32 @@ public partial class CombatManager : IDisposable private static bool IsWandObject(WorldObject wo) => WeaponList.IsWand(wo); - /// War or Void Magic trained — the character can attack with a caster. - /// Skills not read yet count as trained, like the other skill gates here. - private bool CanAttackWithMagic => + /// War or Void Magic trained. Skills not read yet count as trained, like the + /// other skill gates here. + private bool AttackMagicTrained => _charSkills == null || _charSkills[AcSkillType.WarMagic].Training >= 2 || _charSkills[AcSkillType.VoidMagic].Training >= 2; + /// A script holds the attack kind (RynthAi.Combat): it picks the attack spell, from + /// any school, so a caster is the combat weapon whatever War/Void training says. + private static bool ScriptPicksAttack => CombatHook.IsActive(RynthAiCombat.KindAttack); + + /// The character can attack with a caster: War or Void Magic trained, or a script + /// choosing the attack spells (a Life-only caster whose script drains, for one). Gates the + /// wand fallback when no weapon was chosen; the Items list itself admits a caster under the + /// hook only when it has no melee/missile weapon (ListedCandidates). + private bool CanAttackWithMagic => AttackMagicTrained || ScriptPicksAttack; + + /// For the [EquipDiag] lines: canMagic and whether the script hook made it true. + private string CanMagicDiag() + { + bool trained = AttackMagicTrained, hook = ScriptPicksAttack; + return $"canMagic={trained || hook}" + (hook && !trained ? " (script attack hook)" : ""); + } + + private readonly HashSet _wandRejectedNoted = new(); + /// A weapon combat may fight with: anything the character has (in the world /// cache) but a caster when the character has no attack magic. Debuff casting picks its /// wand separately. An id missing from the cache is not a candidate: a weapon that was @@ -5613,7 +5684,7 @@ public partial class CombatManager : IDisposable { var wo = _worldFilter[id]; if (wo == null) return false; - return CanAttackWithMagic || !IsWandObject(wo); + return AttackMagicTrained || !IsWandObject(wo); } private static List BuildDebuffList(MonsterRule rule, string element) diff --git a/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs new file mode 100644 index 0000000..6547f52 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CombatHookInterface.cs @@ -0,0 +1,379 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// The script-provided combat hook (Shared/RynthAiCombatApi.cs): who holds it, for which kinds, +/// until when, and one request slot per kind. Static, like the interface table that serves it, +/// so it survives a re-Init of the plugin instance; everything runs on the plugin pump thread. +/// +/// RynthAi asks (CombatManager.AttackWithMagic for an attack, BuffManager.CheckVitals for a heal) +/// with : the first call opens a request and says Wait; later calls say Wait +/// until the answer is in (Decided), the answer is a decline (Native), or the deadline passes +/// (Native). The hook is active only while its lease is live, so a script plugin that stops +/// renewing (unloaded, crashed, stopped) leaves RynthAi native within one lease. +/// +internal static class CombatHook +{ + /// What a consumer does this tick. + internal enum Outcome { Native, Wait, Decided } + + /// One kind's request slot. + internal sealed class Slot + { + public readonly uint Kind; + public Slot(uint kind) => Kind = kind; + + public bool Open; + public CombatRequestV1 Request; + public bool Decided; + public uint DecidedSpell, DecidedTarget, DecidedFlags; + + // The last decision consumed (handed back in the next request). + public uint LastSeq, LastSpell, LastTarget; + public long LastAtMs; + + // Counters for /ra combat and the tests. + public int Opened, Casts, Declines, Timeouts, Rejects; + public long LastTimeoutLogMs = long.MinValue; + public long LastRejectLogMs = long.MinValue; + + public void Reset() + { + Open = false; Decided = false; Request = default; + DecidedSpell = DecidedTarget = DecidedFlags = 0; + LastSeq = LastSpell = LastTarget = 0; LastAtMs = 0; + Opened = Casts = Declines = Timeouts = Rejects = 0; + LastTimeoutLogMs = LastRejectLogMs = long.MinValue; + } + } + + /// Milliseconds clock (Environment.TickCount64; the host tests replace it). + internal static Func Clock = static () => Environment.TickCount64; + internal static long Now => Clock(); + + /// A timeout is logged at most this often per kind. + internal const long TimeoutLogIntervalMs = 60_000; + private const long RejectLogIntervalMs = 5_000; + /// A request this long past its deadline when RynthAi next asks is dropped and asked again. + internal const long StaleGraceMs = 1_000; + + public static string Owner { get; private set; } = ""; + public static uint Kinds { get; private set; } + public static long LeaseUntilMs { get; private set; } + public static uint AttackTimeoutMs { get; private set; } = RynthAiCombat.DefaultAttackTimeoutMs; + public static uint HealTimeoutMs { get; private set; } = RynthAiCombat.DefaultHealTimeoutMs; + + public static readonly Slot Attack = new(RynthAiCombat.KindAttack); + public static readonly Slot Heal = new(RynthAiCombat.KindHeal); + + private static uint _seq; + + /// Forget everything (plugin shutdown, host tests). + public static void Reset() + { + Owner = ""; + Kinds = 0; + LeaseUntilMs = 0; + AttackTimeoutMs = RynthAiCombat.DefaultAttackTimeoutMs; + HealTimeoutMs = RynthAiCombat.DefaultHealTimeoutMs; + Attack.Reset(); + Heal.Reset(); + _seq = 0; + } + + public static Slot? SlotFor(uint kind) => kind == RynthAiCombat.KindAttack ? Attack : kind == RynthAiCombat.KindHeal ? Heal : null; + + /// True while is held and the lease is live. + public static bool IsActive(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntilMs; + + private static bool LeaseLive => Kinds != 0 && Now < LeaseUntilMs; + + /// Takes or renews the hook. Returns the kinds granted (0 = another owner's lease is live). + public static uint Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, string owner) + { + owner = (owner ?? "").Trim(); + if (owner.Length > RynthAiCombat.MaxOwnerLength) owner = owner.Substring(0, RynthAiCombat.MaxOwnerLength); + kinds &= RynthAiCombat.KindsAll; + long now = Now; + bool live = LeaseLive; + if (live && !string.Equals(Owner, owner, StringComparison.Ordinal)) return 0; + + // Kinds this owner no longer claims: their open requests are dropped (native that tick). + uint dropped = live ? Kinds & ~kinds : RynthAiCombat.KindsAll; + if ((dropped & RynthAiCombat.KindAttack) != 0) Cancel(Attack); + if ((dropped & RynthAiCombat.KindHeal) != 0) Cancel(Heal); + + if (kinds == 0) + { + Owner = ""; + Kinds = 0; + LeaseUntilMs = 0; + return 0; + } + Owner = owner; + Kinds = kinds; + LeaseUntilMs = now + RynthAiCombat.ClampLease(leaseMs); + AttackTimeoutMs = RynthAiCombat.ClampTimeout(attackTimeoutMs, RynthAiCombat.DefaultAttackTimeoutMs); + HealTimeoutMs = RynthAiCombat.ClampTimeout(healTimeoutMs, RynthAiCombat.DefaultHealTimeoutMs); + return kinds; + } + + /// Drops now; their open requests are cancelled. + public static void Release(uint kinds) + { + kinds &= RynthAiCombat.KindsAll; + if ((kinds & RynthAiCombat.KindAttack) != 0) Cancel(Attack); + if ((kinds & RynthAiCombat.KindHeal) != 0) Cancel(Heal); + Kinds &= ~kinds; + if (Kinds == 0) { Owner = ""; LeaseUntilMs = 0; } + } + + /// 1 when a request of is open and unanswered (copied to ). + public static bool Poll(uint kind, out CombatRequestV1 request) + { + request = default; + Slot? s = SlotFor(kind); + if (s == null || !IsActive(kind) || !s.Open || s.Decided || Now > s.Request.DeadlineMs) return false; + request = s.Request; + request.LastSeq = s.LastSeq; + request.LastSpell = s.LastSpell; + request.LastTarget = s.LastTarget; + request.LastAtMs = s.LastAtMs; + return true; + } + + /// The answer to request . False = stale. + public static bool Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags) + { + Slot? s = SlotFor(kind); + if (s == null || !IsActive(kind) || !s.Open || s.Decided || s.Request.Seq != seq || Now > s.Request.DeadlineMs) return false; + s.Decided = true; + s.DecidedSpell = spellId; + s.DecidedTarget = targetId; + s.DecidedFlags = flags; + return true; + } + + private static void Cancel(Slot s) + { + s.Open = false; + s.Decided = false; + } + + /// + /// One consumer step for . is what the request + /// is about (the attack target; for a heal the fight target, informational, 0 when none): an open request about another target is dropped + /// and a fresh one opened. fills a new request's context (RynthAi's + /// view of the fight); Seq, Kind, TargetId and the times are set here. + /// + public static Outcome Step(Slot slot, uint forTarget, Func build, Action? log, + out uint spellId, out uint targetId, out uint flags) + { + spellId = targetId = flags = 0; + if (!IsActive(slot.Kind)) + { + Cancel(slot); + return Outcome.Native; + } + long now = Now; + if (slot.Open && slot.Request.TargetId != forTarget) Cancel(slot); // the target moved on: ask afresh + // RynthAi stopped asking for a while (its gates held the cast, or health came back over the + // line): an answer, or a missing one, from back then is stale. Ask afresh, no timeout counted. + if (slot.Open && now > slot.Request.DeadlineMs + StaleGraceMs) Cancel(slot); + + if (!slot.Open) + { + CombatRequestV1 r = build(); + r.StructSize = (uint)Unsafe.SizeOf(); + if (++_seq == 0) _seq = 1; + r.Seq = _seq; + r.Kind = slot.Kind; + r.TargetId = forTarget; + r.IssuedAtMs = now; + r.DeadlineMs = now + (slot.Kind == RynthAiCombat.KindAttack ? AttackTimeoutMs : HealTimeoutMs); + slot.Request = r; + slot.Open = true; + slot.Decided = false; + slot.Opened++; + return Outcome.Wait; + } + + if (slot.Decided) + { + if (slot.DecidedSpell == 0) + { + Consume(slot, 0, 0); + slot.Declines++; + return Outcome.Native; + } + spellId = slot.DecidedSpell; + targetId = slot.DecidedTarget; + flags = slot.DecidedFlags; + return Outcome.Decided; // the consumer validates, then Cast or Reject + } + + if (now > slot.Request.DeadlineMs) + { + Cancel(slot); + slot.Timeouts++; + if (slot.LastTimeoutLogMs == long.MinValue || now - slot.LastTimeoutLogMs >= TimeoutLogIntervalMs) + { + slot.LastTimeoutLogMs = now; + log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {slot.Request.Seq} unanswered after " + + $"{slot.Request.DeadlineMs - slot.Request.IssuedAtMs} ms ('{Owner}'): RynthAi chose instead " + + $"({slot.Timeouts} timeout(s) so far; logged at most once a minute)"); + } + return Outcome.Native; + } + return Outcome.Wait; + } + + /// The decided spell went out (or was waited on): the request is done. + public static void Cast(Slot slot, uint spellId, uint targetId) + { + Consume(slot, spellId, targetId); + if (spellId != 0) slot.Casts++; // 0: handled without a cast (a wand swap step in flight) + } + + /// The decided spell failed RynthAi's checks: the request is done, RynthAi chooses. + public static void Reject(Slot slot, string why, Action? log) + { + uint seq = slot.Request.Seq, spell = slot.DecidedSpell, target = slot.DecidedTarget; + Consume(slot, 0, 0); + slot.Rejects++; + long now = Now; + if (slot.LastRejectLogMs == long.MinValue || now - slot.LastRejectLogMs >= RejectLogIntervalMs) + { + slot.LastRejectLogMs = now; + log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {seq}: spell {spell} at 0x{target:X8} rejected ({why}); RynthAi chose instead"); + } + } + + private static void Consume(Slot slot, uint spellId, uint targetId) + { + slot.LastSeq = slot.Request.Seq; + slot.LastSpell = spellId; + slot.LastTarget = targetId; + slot.LastAtMs = Now; + slot.Open = false; + slot.Decided = false; + } + + /// One line for /ra combat. + public static string Describe() + { + long now = Now; + bool live = LeaseLive; + string head = live + ? $"hook: '{Owner}' holds {RynthAiCombat.KindNames(Kinds)} (lease {Math.Max(0, LeaseUntilMs - now) / 1000.0:0.0}s)" + : "hook: none (RynthAi chooses every spell)"; + static string S(Slot s) => $"{s.Opened} asked, {s.Casts} cast, {s.Declines} declined, {s.Timeouts} timed out, {s.Rejects} rejected" + + (s.Open ? $", request {s.Request.Seq} open" : ""); + return $"{head} attack: {S(Attack)} heal: {S(Heal)}"; + } +} + +/// +/// RynthAi's side of the "RynthAi.Combat" interface: the table RynthPluginQueryInterface hands +/// out, and the functions behind it (pump thread, current plugin instance). +/// +internal static unsafe class CombatHookInterface +{ + private static RynthAiCombatApiV1* _table; + + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthAiCombatApiV1.InterfaceName || version == 0 || version > RynthAiCombatApiV1.InterfaceVersion) return IntPtr.Zero; + if (_table == null) + { + var t = (RynthAiCombatApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiCombatApiV1)); + t->Version = RynthAiCombatApiV1.InterfaceVersion; + t->StructSize = (uint)sizeof(RynthAiCombatApiV1); + t->Claim = &Claim; + t->Release = &Release; + t->Poll = &Poll; + t->Decide = &Decide; + t->GetScanned = &GetScanned; + _table = t; + } + return (IntPtr)_table; + } + + /// Frees the table and drops the hook (plugin shutdown). Callers resolve it every tick. + public static void Shutdown() + { + var t = _table; + _table = null; + if (t != null) NativeMemory.Free(t); + CombatHook.Reset(); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, byte* owner) + { + try + { + string name = owner == null ? "" : Marshal.PtrToStringUTF8((IntPtr)owner) ?? ""; + return (int)CombatHook.Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, name); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void Release(uint kinds) + { + try { CombatHook.Release(kinds); } catch { } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Poll(uint kind, CombatRequestV1* req) + { + try + { + if (req == null || !CombatHook.Poll(kind, out CombatRequestV1 r)) return 0; + uint room = req->StructSize; + uint size = (uint)sizeof(CombatRequestV1); + if (room == 0 || room > size) room = size; // an older caller passes less; never write past it + r.StructSize = room; + Buffer.MemoryCopy(&r, req, room, room); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags) + { + try { return CombatHook.Decide(seq, kind, spellId, targetId, flags) ? 1 : 0; } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetScanned(uint* ids, float* distances, int capacity) + { + try { return PluginExports.Runtime.Plugin?.CombatHookScanned(ids, distances, capacity) ?? 0; } + catch { return 0; } + } +} + +public sealed partial class RynthAiPlugin +{ + /// RynthAi.Combat GetScanned: the combat scan list, nearest first as scanned. + internal unsafe int CombatHookScanned(uint* ids, float* distances, int capacity) + { + var list = _combatManager?.ScannedTargets; + if (list == null) return 0; + int n = list.Count; + if (ids != null) + for (int i = 0; i < n && i < capacity; i++) + { + ids[i] = unchecked((uint)list[i].Id); + if (distances != null) distances[i] = (float)list[i].Distance; + } + return n; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index b19cdcc..715ea87 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -15,7 +15,8 @@ public static unsafe class PluginExports // Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthAi.Script" v1 // for RynthLua, "RynthAi.Status" v1 for RynthNet (the bot state it shares with the other clients), - // "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way). + // "RynthAi.Activity" v1 for RynthSort (what the bot is doing, so pack moves stay out of its way), + // "RynthAi.Combat" v1 for RynthLua (a script choosing attack and heal spells, Shared/RynthAiCombatApi.cs). // Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) @@ -25,7 +26,8 @@ public static unsafe class PluginExports string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; IntPtr table = ScriptInterface.Query(iface, version); if (table == IntPtr.Zero) table = StatusInterface.Query(iface, version); - return table != IntPtr.Zero ? table : ActivityInterface.Query(iface, version); + if (table == IntPtr.Zero) table = ActivityInterface.Query(iface, version); + return table != IntPtr.Zero ? table : CombatHookInterface.Query(iface, version); } catch { @@ -42,6 +44,7 @@ public static unsafe class PluginExports Runtime.Shutdown(); StatusInterface.Release(); ActivityInterface.Release(); + CombatHookInterface.Shutdown(); // the hook goes native at once (RynthLua re-claims after a reload) // The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload. foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) }) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 9a66bc1..30ddcf2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -1905,6 +1905,7 @@ public sealed partial class RynthAiPlugin ChatLine($"[RynthAi] scanned={s.ScannedCount} closest=0x{(uint)s.ClosestScannedId:X8} '{s.ClosestScannedName}' @ {s.ClosestScannedDist:F1}yd"); ChatLine($"[RynthAi] weapon=0x{(uint)s.PickedWeaponId:X8} '{s.PickedWeaponName}' ({s.PickedWeaponWhy}) wieldLoc={s.PickedWeaponWieldLoc} ammoWielded={s.HasWieldedAmmoFlag}"); ChatLine($"[RynthAi] busy={s.BusyCount} sinceAtk={sinceAttackS:F1}s sinceStance={sinceStanceS:F1}s sinceEquip={sinceEquipS:F1}s sinceLost={sinceLostS:F1}s"); + ChatLine($"[RynthAi] script {s.ScriptHook}"); // Dump every cache-known object that's wielded — using Host.TryGetObjectWielderInfo // as the authoritative check, not the cached WieldedLocation/Wielder fields diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index dba556c..c2f731c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -635,8 +635,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager); _combatManager.SetWeaponSwapGate(_weaponSwapGate); + _combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals _combatManager.HoldIdlePeace = LootHoldsIdlePeace; _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve + _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); _buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count if (_buffManager != null) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 5c0a421..af070b5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -35,6 +35,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs b/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs new file mode 100644 index 0000000..391d63a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLua/CombatHookPump.cs @@ -0,0 +1,359 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MoonSharp.Interpreter; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthLua; + +/// +/// RynthLua's side of RynthAi's combat hook ("RynthAi.Combat", Shared/RynthAiCombatApi.cs): +/// scripts register an attack and/or heal handler (rynth.ai SetAttackHandler / SetHealHandler), +/// and every tick, before the scripts run, this pump renews RynthAi's lease for the kinds that +/// have a handler, polls each kind, and starts the handler as a script thread for a new request. +/// When the thread ends its answer goes back with Decide. The handler never runs inside RynthAi: +/// it is an ordinary script thread (it may yield; auto-yield keeps a runaway one from freezing the +/// client), and RynthAi casts what it answers. RynthAi waits up to the request's deadline, then +/// chooses for itself. +/// +/// One script per kind (the first to register owns it; the same script registering again +/// replaces its handler). A handler error declines that request; three in a row unregister the +/// handler. A stopped script releases its kinds; an unloaded or stalled RynthLua stops renewing +/// and RynthAi goes native when the lease lapses. +/// +public sealed partial class RynthLuaPlugin +{ + /// Consecutive handler errors that unregister a handler. + internal const int CombatHandlerMaxErrors = 3; + + /// + /// How long past its request's deadline a handler thread may run before it is aborted and + /// counted as an error (a handler that never returns would otherwise hold its kind forever). + /// + internal const long CombatHandlerStallMs = 1_000; + + private const string CombatStallError = "the handler did not answer within the deadline"; + + private sealed class CombatHandler + { + public required ScriptContext Ctx; + public required uint Kind; + public DynValue Fn = DynValue.Nil; + public int Errors; + public bool InFlight; + public object? Thread; // the in-flight handler thread (LuaScriptHost.Abort) + public uint InFlightSeq; + public long StartedDeadlineMs; // the in-flight request's deadline (RynthAi's clock) + // The last request started, by seq AND issue time: RynthAi's seq restarts when it reloads. + public uint LastStartedSeq; + public long LastStartedIssuedAtMs; + } + + /// The pump's clock; must match RynthAi's (CombatHook.Clock, Environment.TickCount64). + internal static Func CombatClock = () => Environment.TickCount64; + + private readonly Dictionary _combatHandlers = new(); + // Scripts whose KeepAlive / OnStop hooks are registered: once per run (ScriptContext.Clear + // drops both lists when the script stops, and the OnStop hook takes the script out of here). + private readonly HashSet _combatHooked = new(); + private uint _combatClaimedKinds; + private string _combatClaimOwner = string.Empty; + private bool _combatRefusedLogged; + + internal static string CombatKindName(uint kind) => kind == RynthAiCombat.KindAttack ? "attack" : "heal"; + + /// The script holding , or null. + internal string? CombatOwner(uint kind) => _combatHandlers.TryGetValue(kind, out var h) ? h.Ctx.Name : null; + + /// True when RynthAi granted the kinds last claimed (this tick's claim). + internal bool CombatClaimed => _combatClaimedKinds != 0; + + /// + /// Sets (fn a function) or clears (fn nil) 's handler for . + /// Returns null on success, or why it was refused. + /// + internal string? SetCombatHandler(ScriptContext ctx, uint kind, DynValue fn) + { + if (fn.IsNil()) + { + if (_combatHandlers.TryGetValue(kind, out var mine) && mine.Ctx == ctx) DropCombatHandler(kind, release: true); + return null; + } + if (fn.Type != DataType.Function) return "the handler must be a function (or nil to clear it)"; + if (!_ai.CombatAvailable) return "RynthAi has no combat hook"; + if (_combatHandlers.TryGetValue(kind, out var held) && held.Ctx != ctx) + return $"the {CombatKindName(kind)} handler is already set by {held.Ctx.Name}"; + + // The replaced handler's request: already answered, skip it; still running (aborted here, + // its answer no longer counts), start the new handler on it. + bool restart = held != null && held.InFlight; + _combatHandlers[kind] = new CombatHandler + { + Ctx = ctx, Kind = kind, Fn = fn, + LastStartedSeq = restart ? 0 : held?.LastStartedSeq ?? 0, + LastStartedIssuedAtMs = restart ? 0 : held?.LastStartedIssuedAtMs ?? 0, + }; + if (restart) held!.Ctx.Host.Abort(held.Thread); + if (_combatHooked.Add(ctx)) + { + // A script with only handlers stays running; stopping it releases what it holds. + ctx.KeepAlive.Add(() => _combatHandlers.Values.Count(h => h.Ctx == ctx)); + ctx.OnStop.Add(() => + { + ClearCombatHandlers(ctx); + _combatHooked.Remove(ctx); + }); + } + return null; + } + + /// Drops every handler holds and releases those kinds in RynthAi. + internal void ClearCombatHandlers(ScriptContext ctx) + { + foreach (uint kind in _combatHandlers.Where(kv => kv.Value.Ctx == ctx).Select(kv => kv.Key).ToArray()) + DropCombatHandler(kind, release: true); + } + + /// Test harness only: how many KeepAlive / OnStop hooks a script has registered. + internal (int KeepAlive, int OnStop) ScriptHookCounts(string name) + => _scripts.TryGetValue(name, out var ctx) ? (ctx.KeepAlive.Count, ctx.OnStop.Count) : (0, 0); + + private void DropCombatHandler(uint kind, bool release) + { + if (_combatHandlers.TryGetValue(kind, out var h) && h.InFlight) h.Ctx.Host.Abort(h.Thread); + _combatHandlers.Remove(kind); + if (release) + { + try { _ai.CombatRelease(kind); } catch { } + _combatClaimedKinds &= ~kind; + } + } + + /// Releases every kind (plugin shutdown); RynthAi goes native at once. + private void ReleaseCombatHook() + { + _combatHandlers.Clear(); + _combatHooked.Clear(); + if (_combatClaimedKinds != 0) + { + try { _ai.CombatRelease(RynthAiCombat.KindsAll); } catch { } + _combatClaimedKinds = 0; + } + } + + /// One pump pass (OnTick, before the scripts run). + private void PumpCombatHook() + { + // A handler whose script is gone (stopped without its stop handlers, or never ran). + foreach (var kv in _combatHandlers.Where(kv => !kv.Value.Ctx.Host.Loaded).ToArray()) + DropCombatHandler(kv.Key, release: true); + if (_combatHandlers.Count == 0) return; + if (!_ai.CombatAvailable) { _combatClaimedKinds = 0; return; } // RynthAi not loaded (yet): nothing to renew + + // A handler past its request's deadline plus the stall budget never answered (a loop that + // sleeps forever, an await that never finishes): abort it so the kind isn't held forever. + long now = CombatClock(); + foreach (CombatHandler h in _combatHandlers.Values.ToArray()) + if (h.InFlight && now > h.StartedDeadlineMs + CombatHandlerStallMs) + { + h.Ctx.Host.Abort(h.Thread); + OnCombatHandlerDone(h, h.InFlightSeq, null, CombatStallError); + } + if (_combatHandlers.Count == 0) return; + + uint kinds = 0; + foreach (uint k in _combatHandlers.Keys) kinds |= k; + string owner = CombatOwnerName(); + if (owner != _combatClaimOwner && _combatClaimedKinds != 0) + _ai.CombatRelease(RynthAiCombat.KindsAll); // same plugin, new name: RynthAi refuses a rename while the lease is live + _combatClaimOwner = owner; + uint before = _combatClaimedKinds; + _combatClaimedKinds = _ai.CombatClaim(kinds, RynthAiCombat.DefaultLeaseMs, 0, 0, owner); + // A kind granted again after a gap (a lapse, a refusal, RynthAi reloaded): its seq may have + // restarted, so the last started seq no longer identifies a request already handled. + foreach (CombatHandler h in _combatHandlers.Values) + if ((before & h.Kind) == 0 && (_combatClaimedKinds & h.Kind) != 0) + h.LastStartedSeq = 0; + if (_combatClaimedKinds == 0) + { + if (!_combatRefusedLogged) + { + _combatRefusedLogged = true; + Log($"[RynthLua] combat hook: RynthAi refused the claim for {RynthAiCombat.KindNames(kinds)} (another owner holds it); retrying every tick."); + } + return; + } + _combatRefusedLogged = false; + + foreach (CombatHandler h in _combatHandlers.Values.ToArray()) + { + if ((_combatClaimedKinds & h.Kind) == 0 || h.InFlight) continue; + if (!_ai.CombatPoll(h.Kind, out CombatRequestV1 req)) continue; + if (req.Seq == h.LastStartedSeq && req.IssuedAtMs == h.LastStartedIssuedAtMs) continue; + Script? s = h.Ctx.Host.Lua; + if (s == null) continue; + DynValue ctxTable; + try { ctxTable = BuildCombatContext(s, req); } + catch (Exception ex) { h.Ctx.Host.Print($"error: combat {CombatKindName(h.Kind)} context: {ex.Message}"); continue; } + uint seq = req.Seq; + CombatHandler started = h; + h.LastStartedSeq = seq; + h.LastStartedIssuedAtMs = req.IssuedAtMs; + h.Thread = h.Ctx.Host.Start(h.Fn, new[] { ctxTable }, (result, error) => OnCombatHandlerDone(started, seq, result, error)); + h.InFlight = h.Thread != null; + h.InFlightSeq = seq; + h.StartedDeadlineMs = req.DeadlineMs; + } + } + + private string CombatOwnerName() + { + var names = _combatHandlers.Values.Select(h => h.Ctx.Name).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(n => n, StringComparer.OrdinalIgnoreCase); + string owner = "RynthLua/" + string.Join("+", names); + return owner.Length > RynthAiCombat.MaxOwnerLength ? owner.Substring(0, RynthAiCombat.MaxOwnerLength) : owner; + } + + /// The handler's thread ended: decide with its answer, or decline on an error. + private void OnCombatHandlerDone(CombatHandler h, uint seq, DynValue? result, string? error) + { + h.InFlight = false; + h.Thread = null; + string? bad = null; + if (error == null && TryReadCombatAnswer(result, out uint spell, out uint target, out uint flags, out bad)) + { + h.Errors = 0; + _ai.CombatDecide(seq, h.Kind, spell, target, flags); // stale (0) when RynthAi moved on: harmless + return; + } + error ??= bad; + + // An error (raised, or an answer that isn't spellId, targetId [, "area"]): decline at once + // rather than make RynthAi wait out the deadline. + _ai.CombatDecide(seq, h.Kind, 0, 0, 0); + bool current = _combatHandlers.TryGetValue(h.Kind, out var now) && ReferenceEquals(now, h); + if (!current) return; // replaced or removed meanwhile: its errors don't count + string kindName = CombatKindName(h.Kind); + h.Errors++; + h.Ctx.Host.Print($"combat {kindName} handler: {error} (declined; {h.Errors}/{CombatHandlerMaxErrors} in a row)"); + if (h.Errors >= CombatHandlerMaxErrors) + { + DropCombatHandler(h.Kind, release: true); + string what = error == CombatStallError ? "did not answer within the deadline" : "failed"; + string msg = $"{h.Ctx.Name}: the {kindName} handler {what} {CombatHandlerMaxErrors} times in a row and was removed; RynthAi chooses the {kindName} spells again."; + h.Ctx.Host.Print(msg); + ChatLine(msg); + Log("[RynthLua] combat hook: " + msg); + } + } + /// + /// Reads a handler's return: nil / false / nothing = decline; otherwise spellId (a number), + /// targetId (a number or an object; nil = the request's target) and optional flags: "area" + /// (or true), "nojudge", or a table { area = true, nojudge = true }. + /// + internal static bool TryReadCombatAnswer(DynValue? result, out uint spell, out uint target, out uint flags, out string? error) + { + spell = target = flags = 0; + error = null; + DynValue[] values = result == null ? Array.Empty() + : result.Type == DataType.Tuple ? result.Tuple ?? Array.Empty() + : new[] { result }; + DynValue first = values.Length > 0 ? values[0] : DynValue.Nil; + if (first.IsNil() || first.Type == DataType.Void || (first.Type == DataType.Boolean && !first.Boolean)) return true; // decline + if (first.Type != DataType.Number || first.Number < 0 || first.Number > uint.MaxValue || first.Number != Math.Floor(first.Number)) + { + error = $"returned {first.Type.ToString().ToLowerInvariant()} '{first.ToPrintString()}', expected a spell id (or nil to decline)"; + return false; + } + spell = (uint)first.Number; + DynValue second = values.Length > 1 ? values[1] : DynValue.Nil; + if (!second.IsNil() && second.Type != DataType.Void) + { + target = LuaArgs.Id(second); + if (target == 0 && !(second.Type == DataType.Number && second.Number == 0)) + { + error = $"returned target '{second.ToPrintString()}', expected an object id or object (or nil for the request's target)"; + return false; + } + } + DynValue third = values.Length > 2 ? values[2] : DynValue.Nil; + switch (third.Type) + { + case DataType.Nil: + case DataType.Void: + break; + case DataType.Boolean: // true = "area" (the v1 form); false = no flags + if (third.Boolean) flags |= RynthAiCombat.FlagArea; + break; + case DataType.String: + if (!TryCombatFlag(third.String, out uint f)) + { + error = $"returned flag '{third.String}', expected \"area\", \"nojudge\" or a table {{ area = true, nojudge = true }}"; + return false; + } + flags |= f; + break; + case DataType.Table: + foreach (TablePair p in third.Table.Pairs) + { + if (p.Key.Type != DataType.String || !TryCombatFlag(p.Key.String, out uint tf)) + { + error = $"returned flag '{p.Key.ToPrintString()}', expected the keys area and nojudge"; + return false; + } + if (p.Value.CastToBool()) flags |= tf; + } + break; + default: + error = $"returned {third.Type.ToString().ToLowerInvariant()} flags, expected \"area\", \"nojudge\" or a table {{ area = true, nojudge = true }}"; + return false; + } + return true; + } + + private static bool TryCombatFlag(string name, out uint flag) + { + flag = name.Trim().ToLowerInvariant() switch + { + "area" => RynthAiCombat.FlagArea, + "nojudge" => RynthAiCombat.FlagNoJudge, + _ => 0u, + }; + return flag != 0; + } + + /// The ctx table a handler gets. + private DynValue BuildCombatContext(Script s, in CombatRequestV1 r) + { + var t = new Table(s); + t["seq"] = (double)r.Seq; + t["kind"] = CombatKindName(r.Kind); + t["targetId"] = (double)r.TargetId; + t["targetHealth"] = (double)r.TargetHealth; + t["healthPct"] = (double)r.HealthPct; + t["staminaPct"] = (double)r.StaminaPct; + t["manaPct"] = (double)r.ManaPct; + t["healLine"] = (double)r.HealLine; + t["inCombat"] = r.InCombat != 0; + t["combatMode"] = (double)r.CombatMode; + t["issuedAt"] = (double)r.IssuedAtMs; + t["deadline"] = (double)r.DeadlineMs; + + var monsters = new Table(s); + foreach (var (id, distance) in _ai.CombatScanned()) + { + var m = new Table(s); + m["id"] = (double)id; + m["distance"] = Math.Round(distance, 2); + monsters.Append(DynValue.NewTable(m)); + } + t["monsters"] = monsters; + + var last = new Table(s); + last["seq"] = (double)r.LastSeq; + last["spell"] = (double)r.LastSpell; + last["target"] = (double)r.LastTarget; + last["at"] = (double)r.LastAtMs; + t["last"] = last; + return DynValue.NewTable(t); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthLua/Examples/README.md b/Plugins/RynthCore.Plugin.RynthLua/Examples/README.md index bb992cd..915cb74 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/Examples/README.md +++ b/Plugins/RynthCore.Plugin.RynthLua/Examples/README.md @@ -13,6 +13,7 @@ Scripts that listen for events keep running until you stop them (`/lua stop = 0 and ctx.targetHealth < FINISH_BELOW then + return FINISHER_SPELL + end + return nil -- RynthAi casts its own choice +end + +local function onHeal(ctx) + if HEAL_SPELL ~= 0 and ctx.healthPct >= 0 and ctx.healthPct < HEAL_BELOW then + return HEAL_SPELL, 0 -- target 0 = yourself + end + return nil -- kits, Heal Self and potions as usual +end + +local enabled = false + +local function enable() + local okAttack, whyAttack = ai.SetAttackHandler(onAttack) + if not okAttack then print("attack handler refused: " .. tostring(whyAttack)) end + local okHeal, whyHeal = ai.SetHealHandler(onHeal) + if not okHeal then print("heal handler refused: " .. tostring(whyHeal)) end + enabled = okAttack or okHeal + print("combat handlers " .. (enabled and "on" or "off")) +end + +local function disable() + ai.ClearCombatHandlers() + enabled = false + print("combat handlers off: RynthAi chooses every spell") +end + +game.RegisterCommand("/combathook", function() + if enabled then disable() else enable() end +end) + +-- Stopping the script releases the handlers anyway; clearing them here says so explicitly. +game.OnScriptEnd.Add(function() ai.ClearCombatHandlers() end) + +enable() diff --git a/Plugins/RynthCore.Plugin.RynthLua/LibraryRynthAi.cs b/Plugins/RynthCore.Plugin.RynthLua/LibraryRynthAi.cs index 28331b9..a56f7e0 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/LibraryRynthAi.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/LibraryRynthAi.cs @@ -19,6 +19,11 @@ namespace RynthCore.Plugin.RynthLua; /// ai.DistanceTo(objectOrId) metres, -1 when unknown /// ai.IsPathClear(objectOrIdOrName) line of sight /// ai.Command(text) (SubmitCommand) a chat line as if typed (/ra, /vt, ...; AC's parser without RynthAi) +/// ai.SetAttackHandler(fn) this script chooses RynthAi's attack spells (CombatHookPump.cs); +/// ai.SetHealHandler(fn) ... and its heal spells, asked before kits. true, or false and why. +/// fn(ctx) returns spellId, targetId [, "area"], or nil to let RynthAi choose +/// ai.ClearCombatHandlers() drops this script's handlers (stopping the script does too) +/// ai.CombatHook { Supported, AttackOwner, HealOwner, Claimed } /// /// Everything except Available and Command raises "RynthAi isn't loaded ..." when RynthAi /// isn't there, so a script can check ai.Available first or pcall. @@ -144,6 +149,23 @@ public sealed partial class RynthLuaPlugin m.Set("Command", command); m.Set("SubmitCommand", command); + // The combat hook (RynthAi.Combat): handlers run as script threads started by the pump. + DynValue SetHandler(CallbackArguments a, uint kind, string what) + { + DynValue fn = LuaArgs.At(LuaArgs.Of(a, m), 0); + if (!fn.IsNil() && fn.Type != DataType.Function) + throw new ScriptRuntimeException($"rynth.ai.{what}(fn) needs a function (or nil to clear it)"); + string? refused = SetCombatHandler(ctx, kind, fn); + return refused == null ? DynValue.True : DynValue.NewTuple(DynValue.False, DynValue.NewString(refused)); + } + m.Set("SetAttackHandler", DynValue.NewCallback((c, a) => SetHandler(a, RynthCore.Plugin.Shared.RynthAiCombat.KindAttack, "SetAttackHandler"))); + m.Set("SetHealHandler", DynValue.NewCallback((c, a) => SetHandler(a, RynthCore.Plugin.Shared.RynthAiCombat.KindHeal, "SetHealHandler"))); + m.Set("ClearCombatHandlers", DynValue.NewCallback((c, a) => + { + ClearCombatHandlers(ctx); + return DynValue.Nil; + })); + // Live fields: Available / IsLoaded, MacroRunning (read and write). var mt = new Table(s); mt.Set("__index", DynValue.NewCallback((c, a) => @@ -156,6 +178,15 @@ public sealed partial class RynthLuaPlugin return DynValue.NewBoolean(_ai.Available); case "MacroRunning": return DynValue.NewBoolean(_ai.MacroRunning); + case "CombatHook": + { + var h = new Table(s); + h["Supported"] = _ai.CombatAvailable; + h["AttackOwner"] = CombatOwner(RynthCore.Plugin.Shared.RynthAiCombat.KindAttack) is string ao ? DynValue.NewString(ao) : DynValue.Nil; + h["HealOwner"] = CombatOwner(RynthCore.Plugin.Shared.RynthAiCombat.KindHeal) is string ho ? DynValue.NewString(ho) : DynValue.Nil; + h["Claimed"] = CombatClaimed; + return DynValue.NewTable(h); + } default: return DynValue.Nil; } @@ -172,6 +203,7 @@ public sealed partial class RynthLuaPlugin return DynValue.Nil; case "Available": case "IsLoaded": + case "CombatHook": throw new ScriptRuntimeException($"rynth.ai.{key} is read-only"); default: // Script's own fields on the module are fine. diff --git a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs index 55312a1..00be58c 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs @@ -34,6 +34,8 @@ internal sealed class LuaScriptHost public Func? WaitFor; // await: resume only once this is true public DynValue[] Args = Array.Empty(); public bool Started; + /// Called once when the thread ends: its return values, or the error message. + public Action? OnDone; } private readonly Action _log; @@ -206,12 +208,42 @@ internal sealed class LuaScriptHost } /// Starts as a new script thread. - public void Start(DynValue fn, DynValue[] args) + public void Start(DynValue fn, DynValue[] args) => Start(fn, args, onDone: null); + + /// + /// Starts as a new script thread and calls once + /// it ends: with its return values (a tuple for several, Nil for none) and a null error, or with + /// a null result and the error message when it raised one. Not called when the script stops + /// first (its stop handlers clean up), nor after . Returns the thread's + /// handle (for Abort), or null when nothing was started. + /// + public object? Start(DynValue fn, DynValue[] args, Action? onDone) { - if (_script == null || fn.Type != DataType.Function) return; + if (_script == null || fn.Type != DataType.Function) return null; DynValue co = _script.CreateCoroutine(fn); co.Coroutine.AutoYieldCounter = AutoYieldCounter; - _threads.Add(new LuaThread { Co = co, Args = args }); + var t = new LuaThread { Co = co, Args = args, OnDone = onDone }; + _threads.Add(t); + return t; + } + + /// + /// Ends the thread (from ) + /// without resuming it again; its onDone is not called. Returns false when it had already ended. + /// + public bool Abort(object? handle) + { + if (handle is not LuaThread t) return false; + t.OnDone = null; + if (ReferenceEquals(_botTickThread, t)) _botTickThread = null; + return _threads.Remove(t); + } + + private static void Done(LuaThread t, DynValue? result, string? error) + { + Action? cb = t.OnDone; + t.OnDone = null; + try { cb?.Invoke(result, error); } catch { } } /// Calls every v1 handler registered for , each on its own thread. @@ -276,11 +308,12 @@ internal sealed class LuaScriptHost } _current = t; + DynValue r = DynValue.Nil; try { while (_script != null) { - DynValue r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args); + r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args); t.Started = true; if (t.Co.Coroutine.State == CoroutineState.Dead) break; // Forced (auto) yield: keep going while this tick has budget. @@ -292,18 +325,24 @@ internal sealed class LuaScriptHost { Print("error: " + (ex.DecoratedMessage ?? ex.Message)); _threads.Remove(t); + Done(t, null, ex.DecoratedMessage ?? ex.Message); continue; } catch (Exception ex) { Print("error: " + ex.Message); _threads.Remove(t); + Done(t, null, ex.Message); continue; } finally { _current = null; } if (_script == null) return; - if (t.Co.Coroutine.State == CoroutineState.Dead) _threads.Remove(t); + if (t.Co.Coroutine.State == CoroutineState.Dead) + { + _threads.Remove(t); + Done(t, r, null); + } if (OverBudget()) break; } } diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthAiBridge.cs b/Plugins/RynthCore.Plugin.RynthLua/RynthAiBridge.cs index 6531ee6..f1f1752 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthAiBridge.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthAiBridge.cs @@ -42,11 +42,88 @@ internal sealed unsafe class RynthAiBridge } } - /// Forget the table (logout, RynthAi reload); the next call looks it up again. + /// Forget the tables (logout, RynthAi reload); the next call looks them up again. public void Reset() { _t = null; _checked = false; + _c = null; + _cChecked = false; + } + + // -- RynthAi.Combat (Shared/RynthAiCombatApi.cs): the script-provided combat hook -- + + private RynthAiCombatApiV1* _c; + private bool _cChecked; + private long _cCheckedAt; + + private RynthAiCombatApiV1* Combat + { + get + { + long now = Environment.TickCount64; + if (_cChecked && now - _cCheckedAt < RecheckMs) return _c; + _cChecked = true; + _cCheckedAt = now; + IntPtr p = _host.GetPluginInterface("RynthAi", RynthAiCombatApiV1.InterfaceName, RynthAiCombatApiV1.InterfaceVersion); + var t = (RynthAiCombatApiV1*)p; + _c = t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiCombatApiV1) ? t : null; + return _c; + } + } + + /// True when RynthAi serves the combat hook right now. + public bool CombatAvailable => Combat != null; + + /// Takes or renews the hook; the kinds granted (0 = refused or no RynthAi). + public uint CombatClaim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, string owner) + { + var t = Combat; + if (t == null) return 0; + using var o = new Utf8(owner); + return unchecked((uint)t->Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, o.P)); + } + + public void CombatRelease(uint kinds) + { + var t = Combat; + if (t != null) t->Release(kinds); + } + + /// True when a request of is open and unanswered. + public bool CombatPoll(uint kind, out CombatRequestV1 request) + { + request = default; + var t = Combat; + if (t == null) return false; + CombatRequestV1 r = default; + r.StructSize = (uint)sizeof(CombatRequestV1); + if (t->Poll(kind, &r) == 0) return false; + request = r; + return true; + } + + /// The answer to request ; false = stale (or no RynthAi). + public bool CombatDecide(uint seq, uint kind, uint spellId, uint targetId, uint flags) + { + var t = Combat; + return t != null && t->Decide(seq, kind, spellId, targetId, flags) != 0; + } + + /// RynthAi's scanned targets (id, metres), nearest first. + public (uint Id, float Distance)[] CombatScanned() + { + var t = Combat; + if (t == null) return Array.Empty<(uint, float)>(); + const int Cap = 64; + uint* ids = stackalloc uint[Cap]; + float* dist = stackalloc float[Cap]; + int n = t->GetScanned(ids, dist, Cap); + if (n <= 0) return Array.Empty<(uint, float)>(); + n = Math.Min(n, Cap); + var list = new (uint, float)[n]; + for (int i = 0; i < n; i++) list[i] = (ids[i], dist[i]); + return list; } private static string Copy(byte* s) => s == null ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)s) ?? string.Empty; diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj index 3d3962d..bac8d36 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthCore.Plugin.RynthLua.csproj @@ -40,6 +40,8 @@ + + diff --git a/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPlugin.cs b/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPlugin.cs index 9ba4bcb..d9d4f15 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/RynthLuaPlugin.cs @@ -105,6 +105,7 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase List resume = new(); try { resume = CaptureResume(); } catch { } try { StopAll("stopped: RynthLua unloaded"); } catch (Exception ex) { Log("[RynthLua] shutdown: " + ex.Message); } + try { ReleaseCombatHook(); } catch { } // RynthAi goes native now, not when the lease lapses try { ShutdownHuds(); } catch { } FlushHudMemory(); SaveEditor(); @@ -134,6 +135,10 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase try { PollHudEvents(); } // script windows: input first, so this tick's passes see it catch (Exception ex) { LogHudFault("events", ex); } TickApi(); + // RynthAi's combat hook: renew the lease, start handlers for new requests (they run in + // TickScripts just below, so a handler that doesn't yield answers in this same tick). + try { PumpCombatHook(); } + catch (Exception ex) { Log("[RynthLua] combat hook: " + ex.Message); } TickScripts(); try { TickHuds(); } // render passes that are due, then submit what changed catch (Exception ex) { LogHudFault("passes", ex); } diff --git a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua index db2876a..f25432a 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua +++ b/Plugins/RynthCore.Plugin.RynthLua/Types/rynthlua.d.lua @@ -1410,6 +1410,7 @@ function FileSystemModule.GetCustom() end ---@field Available boolean RynthAi is loaded. ---@field IsLoaded boolean Same as Available. ---@field MacroRunning boolean Read, or assign true/false to start/stop the macro. +---@field CombatHook RynthLua.CombatHookInfo The combat hook's state (read-only; a fresh table each read). local RynthAiModule = {} ---A meta expression; numbers come back as numbers. ---@param expression string @@ -1453,6 +1454,85 @@ function RynthAiModule.Command(text) end ---Same as Command. ---@param text string function RynthAiModule.SubmitCommand(text) end +---This script chooses RynthAi's attack spells. RynthAi still picks the target, keeps the stance, +---the pacing and its debuffs, and casts what the handler answers. The handler runs as a script +---thread when RynthAi is about to cast (after its debuffs) and may yield, but RynthAi waits only +---until `ctx.deadline` (1 s by default) and then casts its own choice. It must not cast itself. +---Return `spellId, targetId [, flags]`, or nil to let RynthAi choose this time. targetId nil = +---ctx.targetId; it may also be another of `ctx.monsters` or the player. flags is "area" (or true), +---"nojudge", or a table `{ area = true, nojudge = true }`; anything else is an error. "area" marks +---a ring/wall/chain cast: no miss counting on the fight target, filed with the rings. "nojudge" +---marks a cast not meant to damage (a debuff, a drain): no miss counting (so no blacklist) and +---nothing on the Damage tab (no tier, element or fight cast count), but it still counts in the +---session attack-cast and casts-per-kill counters like any cast. A damaging cast at the fight +---target is tagged like RynthAi's own (wielded wand, element and level from the spell), and a +---single-target one takes part in RynthAi's kill-shot swap: a predicted kill moves RynthAi to +---another target while the projectile flies, and the next request names the new target. An +---unknown spell, a target that isn't the fight target, a scanned monster or the player, or a spell +---the server refused outright right after the script cast it (no components) is rejected and +---RynthAi casts its own; a rejected request reads as last.spell = 0. A refused spell stays parked +---for 600 s (as RynthAi parks a vital level); restocking components does not unpark it sooner. +---One script per kind: the first to register owns it; the same script registering again replaces +---its handler; nil clears it. An error declines that request; a handler still running 1 s past +---ctx.deadline is stopped and counts as an error; 3 errors in a row remove the handler. +---Stopping the script releases it. Keeps the script running while set. The deadlines (1 s attack, +---750 ms heal) and the lease are fixed: the RynthAi.Combat Claim's timeout parameters are reserved. +---While a script holds the attack kind, RynthAi treats the character as able to attack with magic +---even with War and Void untrained: a listed caster counts as the combat weapon when no usable +---listed melee/missile weapon exists. +---@param handler fun(ctx: RynthLua.CombatContext): (integer?, (integer|RynthLua.ObjectRef)?, ("area"|"nojudge"|boolean|{area: boolean?, nojudge: boolean?})?)|nil +---@return boolean ok +---@return string? why "RynthAi has no combat hook", or "the attack handler is already set by