RynthAi.Combat v1: let a RynthLua script choose RynthAi's attack and heal spells

Adds a polling hand-off ("RynthAi.Combat" v1 interface table) so a script can
pick the spell RynthAi casts for an attack or an HP heal, while RynthAi keeps
scanning, targeting, the arbiter, nav/loot gating, thresholds, buffs, stance and
wand. Decline, invalid answers, timeouts and lease lapse all fall back to
native selection in the same tick; the emergency heal path is untouched; the
hook is inert when no script registers. RynthAi's mana reserve holds a script's
attack spell as it holds its own (the answer is kept, nothing native is cast
instead, and the script is asked again after the deadline plus 1 s); a spell
costing more than max mana is rejected so RynthAi chooses its own. Lua API:
ai.SetAttackHandler, ai.SetHealHandler, ai.ClearCombatHandlers, ai.CombatHook.
Includes host and compat tests and Examples/combat-handler.lua. No
RynthCore/SDK changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-10-10 10:26:25 -07:00
commit 10e2c2eb0a
30 changed files with 3620 additions and 27 deletions

View file

@ -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
{
/// <summary>
/// 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).
/// </summary>
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;
}
/// <summary>Why the script's heal can't be cast, or null when it can.</summary>
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,
};
}
}

View file

@ -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).
/// </summary>
/// <summary>
/// For CombatManager's script hook, before <see cref="OffensiveCastHold"/>: false when
/// <paramref name="spellId"/> 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.
/// </summary>
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 _);
}
/// <summary>
/// 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); <paramref name="sent"/>
/// says whether the cast actually went out.
/// </summary>
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);
}
/// <summary>The held cast is a heal, or health is under a heal line: nudge it early.</summary>
/// <summary>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.</summary>
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));
}

View file

@ -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;
}

View file

@ -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;
/// <summary>The player's vitals, for the hook's request (set by the plugin; null in tests that don't need it).</summary>
internal PlayerVitalsCache? Vitals { get; set; }
/// <summary>The fight target's last known health ratio (0-1), or -1 when unknown or no target.</summary>
internal float FightTargetHealthRatio => activeTargetId == 0 ? -1f : _worldFilter.GetHealthRatio(activeTargetId);
/// <summary>Host tests: true after a tick that held for the script's answer.</summary>
internal bool ScriptHeld => _scriptHeld;
/// <summary>
/// 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).
/// </summary>
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;
}
/// <summary>Why the script's answer can't be cast, or null when it can.</summary>
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,
};
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
/// <summary>
/// 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.
/// </summary>
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<int, DateTime> _scriptParkedUntil = new();
/// <summary>How long a script spell the server refused outright is rejected (as BuffManager parks a vital level).</summary>
internal const double ScriptParkSec = 600.0;
/// <summary>A refusal later than this after the script's cast is not attributed to it.</summary>
internal const double ScriptRefusalWindowMs = 2_000.0;
/// <summary>Host tests: true while <paramref name="spellId"/> is parked after a refusal.</summary>
internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && DateTime.Now < u;
/// <summary>A chat line: park the script's last spell on a hard refusal (missing components, unknown spell).</summary>
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).");
}
}

View file

@ -296,6 +296,11 @@ public partial class CombatManager : IDisposable
/// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11).
/// </summary>
public Func<int, string?>? ManaReserveHold { get; set; }
/// <summary>
/// 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.
/// </summary>
public Func<int, bool>? 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;
/// <summary>The script holding the combat hook (RynthAi.Combat), "" when none; and its kinds (RynthAiCombat.Kind* bits).</summary>
public string ScriptHookOwner;
public uint ScriptHookKinds;
/// <summary>The hook's one-line summary (owner, lease, per-kind counters).</summary>
public string ScriptHook;
}
/// <summary>
@ -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
/// <summary>The Items list's usable weapons, in list order, with their kind, element, rending and whether each is in hand.</summary>
internal List<WeaponCandidate> ListedCandidates()
{
var list = ListedCandidates(admitCasters: false, out List<int>? 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;
}
/// <param name="admitCasters">Take listed casters even with War and Void untrained.</param>
/// <param name="leftOut">The casters skipped for that (null when none).</param>
private List<WeaponCandidate> ListedCandidates(bool admitCasters, out List<int>? leftOut)
{
leftOut = null;
int inHand = InHandWeaponId();
var list = new List<WeaponCandidate>();
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<int>()).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);
/// <summary>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.</summary>
private bool CanAttackWithMagic =>
/// <summary>War or Void Magic trained. Skills not read yet count as trained, like the
/// other skill gates here.</summary>
private bool AttackMagicTrained =>
_charSkills == null
|| _charSkills[AcSkillType.WarMagic].Training >= 2
|| _charSkills[AcSkillType.VoidMagic].Training >= 2;
/// <summary>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.</summary>
private static bool ScriptPicksAttack => CombatHook.IsActive(RynthAiCombat.KindAttack);
/// <summary>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).</summary>
private bool CanAttackWithMagic => AttackMagicTrained || ScriptPicksAttack;
/// <summary>For the [EquipDiag] lines: canMagic and whether the script hook made it true.</summary>
private string CanMagicDiag()
{
bool trained = AttackMagicTrained, hook = ScriptPicksAttack;
return $"canMagic={trained || hook}" + (hook && !trained ? " (script attack hook)" : "");
}
private readonly HashSet<int> _wandRejectedNoted = new();
/// <summary>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<string> BuildDebuffList(MonsterRule rule, string element)

View file

@ -0,0 +1,379 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// 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 <see cref="Step"/>: 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.
/// </summary>
internal static class CombatHook
{
/// <summary>What a consumer does this tick.</summary>
internal enum Outcome { Native, Wait, Decided }
/// <summary>One kind's request slot.</summary>
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;
}
}
/// <summary>Milliseconds clock (Environment.TickCount64; the host tests replace it).</summary>
internal static Func<long> Clock = static () => Environment.TickCount64;
internal static long Now => Clock();
/// <summary>A timeout is logged at most this often per kind.</summary>
internal const long TimeoutLogIntervalMs = 60_000;
private const long RejectLogIntervalMs = 5_000;
/// <summary>A request this long past its deadline when RynthAi next asks is dropped and asked again.</summary>
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;
/// <summary>Forget everything (plugin shutdown, host tests).</summary>
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;
/// <summary>True while <paramref name="kind"/> is held and the lease is live.</summary>
public static bool IsActive(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntilMs;
private static bool LeaseLive => Kinds != 0 && Now < LeaseUntilMs;
/// <summary>Takes or renews the hook. Returns the kinds granted (0 = another owner's lease is live).</summary>
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;
}
/// <summary>Drops <paramref name="kinds"/> now; their open requests are cancelled.</summary>
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; }
}
/// <summary>1 when a request of <paramref name="kind"/> is open and unanswered (copied to <paramref name="request"/>).</summary>
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;
}
/// <summary>The answer to request <paramref name="seq"/>. False = stale.</summary>
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;
}
/// <summary>
/// One consumer step for <paramref name="slot"/>. <paramref name="forTarget"/> 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. <paramref name="build"/> fills a new request's context (RynthAi's
/// view of the fight); Seq, Kind, TargetId and the times are set here.
/// </summary>
public static Outcome Step(Slot slot, uint forTarget, Func<CombatRequestV1> build, Action<string>? 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<CombatRequestV1>();
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;
}
/// <summary>The decided spell went out (or was waited on): the request is done.</summary>
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)
}
/// <summary>The decided spell failed RynthAi's checks: the request is done, RynthAi chooses.</summary>
public static void Reject(Slot slot, string why, Action<string>? 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;
}
/// <summary>One line for /ra combat.</summary>
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)}";
}
}
/// <summary>
/// RynthAi's side of the "RynthAi.Combat" interface: the table RynthPluginQueryInterface hands
/// out, and the functions behind it (pump thread, current plugin instance).
/// </summary>
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;
}
/// <summary>Frees the table and drops the hook (plugin shutdown). Callers resolve it every tick.</summary>
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
{
/// <summary>RynthAi.Combat GetScanned: the combat scan list, nearest first as scanned.</summary>
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;
}
}

View file

@ -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) })

View file

@ -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

View file

@ -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)

View file

@ -35,6 +35,8 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- RynthSort reads what the bot is doing through RynthAi.Activity (read only). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- RynthLua's scripts choose attack and heal spells through RynthAi.Combat. -->
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- RynthNav's navmesh path queries (stuck-recovery detours outdoors). -->
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
<!-- Reading our hits out of the combat log (victim + amount); RynthTracker reads the same lines. -->

View file

@ -0,0 +1,359 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// 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.
/// </summary>
public sealed partial class RynthLuaPlugin
{
/// <summary>Consecutive handler errors that unregister a handler.</summary>
internal const int CombatHandlerMaxErrors = 3;
/// <summary>
/// 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).
/// </summary>
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;
}
/// <summary>The pump's clock; must match RynthAi's (CombatHook.Clock, Environment.TickCount64).</summary>
internal static Func<long> CombatClock = () => Environment.TickCount64;
private readonly Dictionary<uint, CombatHandler> _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<ScriptContext> _combatHooked = new();
private uint _combatClaimedKinds;
private string _combatClaimOwner = string.Empty;
private bool _combatRefusedLogged;
internal static string CombatKindName(uint kind) => kind == RynthAiCombat.KindAttack ? "attack" : "heal";
/// <summary>The script holding <paramref name="kind"/>, or null.</summary>
internal string? CombatOwner(uint kind) => _combatHandlers.TryGetValue(kind, out var h) ? h.Ctx.Name : null;
/// <summary>True when RynthAi granted the kinds last claimed (this tick's claim).</summary>
internal bool CombatClaimed => _combatClaimedKinds != 0;
/// <summary>
/// Sets (fn a function) or clears (fn nil) <paramref name="ctx"/>'s handler for <paramref name="kind"/>.
/// Returns null on success, or why it was refused.
/// </summary>
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;
}
/// <summary>Drops every handler <paramref name="ctx"/> holds and releases those kinds in RynthAi.</summary>
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);
}
/// <summary>Test harness only: how many KeepAlive / OnStop hooks a script has registered.</summary>
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;
}
}
/// <summary>Releases every kind (plugin shutdown); RynthAi goes native at once.</summary>
private void ReleaseCombatHook()
{
_combatHandlers.Clear();
_combatHooked.Clear();
if (_combatClaimedKinds != 0)
{
try { _ai.CombatRelease(RynthAiCombat.KindsAll); } catch { }
_combatClaimedKinds = 0;
}
}
/// <summary>One pump pass (OnTick, before the scripts run).</summary>
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;
}
/// <summary>The handler's thread ended: decide with its answer, or decline on an error.</summary>
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);
}
}
/// <summary>
/// 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 }.
/// </summary>
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<DynValue>()
: result.Type == DataType.Tuple ? result.Tuple ?? Array.Empty<DynValue>()
: 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;
}
/// <summary>The ctx table a handler gets.</summary>
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);
}
}

View file

@ -13,6 +13,7 @@ Scripts that listen for events keep running until you stop them (`/lua stop <nam
- `hunt-settings.lua`: a settings form saved with `storage` (checkbox, slider, 0-based combo, text box) and a button that sets your combat mode; `/hunt` shows or hides it.
- `salvage-list.lua`: a list with buttons: your salvage, gathered in a spawned loop, a filter box, a scrolling region with `PushID` rows, and Use / Give buttons (Give waits for its result in a thread of its own). The buttons really act.
- `item-icons.lua`: an item list with icons: your pack items drawn with their AC icons (`views.Huds.GetObjectIconTexture`, `ImGui.ImageButton`, `ImGui.Image`), an `InputInt` for how many rows and a `DragFloat` for the icon size. Nothing acts on the game. Needs an engine from 2026-09-30 or later.
- `combat-handler.lua`: RynthAi's combat hook (`rynth.ai` SetAttackHandler / SetHealHandler): an attack handler that casts a set spell while the target's health is under a line and otherwise lets RynthAi choose, a heal handler that heals you under a health line, the refusal reasons printed, and `/combathook` to turn them on and off. Set its spell ids first; it needs RynthAi running.
The window examples need RynthCore API v71 with ImGui on; see "Script windows" in the reference.

View file

@ -0,0 +1,56 @@
-- combat-handler.lua: choose RynthAi's attack and heal spells from a script (the combat hook).
--
-- RynthAi still picks the target, the stance and the pacing. When it is about to cast it asks
-- the handler, waits until ctx.deadline at most, and casts the answer. A handler returns
-- spellId [, targetId [, flags]] targetId nil = ctx.targetId (attack) / yourself (heal)
-- nil let RynthAi choose this time
-- flags: "area" (a ring/wall cast) or "nojudge" (not meant to damage; no miss counting).
-- /combathook turns the handlers on and off. Set the spell ids below to spells you know.
local ai = require("rynth.ai")
local FINISHER_SPELL = 0 -- attack spell id, cast while the target is under FINISH_BELOW
local FINISH_BELOW = 0.30 -- the target's health ratio, 0..1
local HEAL_SPELL = 0 -- heal spell id, cast on yourself under HEAL_BELOW
local HEAL_BELOW = 50 -- your health percent
local function onAttack(ctx)
-- ctx.targetHealth is -1 while RynthAi has no health for the target.
if FINISHER_SPELL ~= 0 and ctx.targetHealth >= 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()

View file

@ -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 <c>ai.Available</c> 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.

View file

@ -34,6 +34,8 @@ internal sealed class LuaScriptHost
public Func<bool>? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty<DynValue>();
public bool Started;
/// <summary>Called once when the thread ends: its return values, or the error message.</summary>
public Action<DynValue?, string?>? OnDone;
}
private readonly Action<string> _log;
@ -206,12 +208,42 @@ internal sealed class LuaScriptHost
}
/// <summary>Starts <paramref name="fn"/> as a new script thread.</summary>
public void Start(DynValue fn, DynValue[] args)
public void Start(DynValue fn, DynValue[] args) => Start(fn, args, onDone: null);
/// <summary>
/// Starts <paramref name="fn"/> as a new script thread and calls <paramref name="onDone"/> 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 <see cref="Abort"/>. Returns the thread's
/// handle (for Abort), or null when nothing was started.
/// </summary>
public object? Start(DynValue fn, DynValue[] args, Action<DynValue?, string?>? 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;
}
/// <summary>
/// Ends the thread <paramref name="handle"/> (from <see cref="Start(DynValue, DynValue[], Action{DynValue?, string?}?)"/>)
/// without resuming it again; its onDone is not called. Returns false when it had already ended.
/// </summary>
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<DynValue?, string?>? cb = t.OnDone;
t.OnDone = null;
try { cb?.Invoke(result, error); } catch { }
}
/// <summary>Calls every v1 handler registered for <paramref name="evt"/>, each on its own thread.</summary>
@ -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;
}
}

View file

@ -42,11 +42,88 @@ internal sealed unsafe class RynthAiBridge
}
}
/// <summary>Forget the table (logout, RynthAi reload); the next call looks it up again.</summary>
/// <summary>Forget the tables (logout, RynthAi reload); the next call looks them up again.</summary>
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;
}
}
/// <summary>True when RynthAi serves the combat hook right now.</summary>
public bool CombatAvailable => Combat != null;
/// <summary>Takes or renews the hook; the kinds granted (0 = refused or no RynthAi).</summary>
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);
}
/// <summary>True when a request of <paramref name="kind"/> is open and unanswered.</summary>
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;
}
/// <summary>The answer to request <paramref name="seq"/>; false = stale (or no RynthAi).</summary>
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;
}
/// <summary>RynthAi's scanned targets (id, metres), nearest first.</summary>
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;

View file

@ -40,6 +40,8 @@
<ItemGroup>
<!-- RynthAi's script interface (RynthAi.Script v1), shared source with RynthAi. -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- RynthAi's combat hook (RynthAi.Combat v1): scripts choose attack and heal spells. -->
<Compile Include="..\Shared\RynthAiCombatApi.cs" Link="Shared\RynthAiCombatApi.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
</ItemGroup>

View file

@ -105,6 +105,7 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
List<string> 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); }

View file

@ -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 <script>".
function RynthAiModule.SetAttackHandler(handler) end
---This script chooses the vitals heal: asked when health is under Heal At (in combat) or Top Off HP
---(idle), before kits, Heal Self and potions (the emergency kit / Stamina to Health step stays
---RynthAi's). Same contract as SetAttackHandler; ctx.healLine is the line, and ctx.targetId /
---ctx.targetHealth are informational: RynthAi's current fight target (0 when none) and its health.
---Return a heal and target 0/nil for YOURSELF (never the fight target), or e.g. a drain spell and
---a monster from `ctx.monsters` or ctx.targetId. A level the server had no components for is
---rejected for 600 s (RynthAi's own heal skips it as long; restocking does not unpark it sooner).
---The deadline is 750 ms; nil or no
---answer = kit, Heal Self, potion.
---@param handler fun(ctx: RynthLua.CombatContext): (integer?, (integer|RynthLua.ObjectRef)?, ("area"|"nojudge"|boolean|{area: boolean?, nojudge: boolean?})?)|nil
---@return boolean ok
---@return string? why
function RynthAiModule.SetHealHandler(handler) end
---Drops this script's attack and heal handlers (RynthAi chooses again at once).
function RynthAiModule.ClearCombatHandlers() end
---What a combat handler gets (one table per request).
---@class RynthLua.CombatContext
---@field seq integer The request's id.
---@field kind "attack"|"heal"
---@field targetId integer Attack: RynthAi's locked target. Heal: RynthAi's current fight target (informational; 0 when none).
---@field targetHealth number That target's health 0..1; -1 unknown or no target.
---@field healthPct integer Your health %, -1 unknown.
---@field staminaPct integer Your stamina %, -1 unknown.
---@field manaPct integer Your mana %, -1 unknown.
---@field healLine integer Heal: the health line you are under (Heal At / Top Off HP). Attack: 0.
---@field inCombat boolean A monster is engaged or within Monster Range.
---@field combatMode integer 1 NonCombat, 2 Melee, 4 Missile, 8 Magic.
---@field issuedAt number clock() when RynthAi asked.
---@field deadline number clock() after which RynthAi casts its own choice.
---@field monsters RynthLua.CombatMonster[] RynthAi's targets in range (attackable, in sight), nearest first.
---@field last RynthLua.CombatLast The last answer of this kind RynthAi used.
---@class RynthLua.CombatMonster
---@field id integer
---@field distance number Metres.
---@class RynthLua.CombatLast
---@field seq integer 0 before the first.
---@field spell integer The spell cast; 0 = declined or rejected.
---@field target integer
---@field at number clock() when it was used.
---ai.CombatHook
---@class RynthLua.CombatHookInfo
---@field Supported boolean RynthAi serves the combat hook now.
---@field AttackOwner string? The script holding the attack kind.
---@field HealOwner string? The script holding the heal kind.
---@field Claimed boolean RynthAi granted RynthLua's last claim (false while another owner holds it).
---require("rynthlua")
---@class RynthLua.InfoModule

View file

@ -585,10 +585,21 @@ internal static class ActionPacer
MoveAudit.FlushPendingStops(host, "before a cast", force: true);
int seq = UseDoneSeqNow(host);
bool ok = host.CastSpell(targetId, spellId);
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
if (ok)
{
CastsSent++;
Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
}
return ok;
}
/// <summary>
/// Casts sent through <see cref="CastSpellFor"/> in this plugin (every caller: combat, buffs,
/// nav, commands, meta): a caller that remembers the count at its own cast can tell whether
/// another cast went out since (a refusal then may be that one's).
/// </summary>
public static long CastsSent { get; private set; }
/// <summary>
/// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that
/// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change

View file

@ -0,0 +1,160 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthAiCombatApi.cs
// The "RynthAi.Combat" interface: lets a script plugin (RynthLua) choose the
// spell for RynthAi's next attack cast or vitals heal, while RynthAi keeps
// targeting, pacing, stance and the cast itself. Compiled into both plugins
// (linked source), so the layout and the constants can't drift between them.
//
// The exchange is polled, never a callback:
// 1. The script side calls Claim every tick for the kinds it handles (a
// lease: when it stops renewing, RynthAi goes native on its own).
// 2. When RynthAi reaches a cast choice it opens a request (a new Seq) and
// waits, holding that one cast, up to the request's deadline.
// 3. The script side sees it through Poll, decides, and answers with Decide.
// 4. RynthAi validates the answer and casts it, or (spell 0, an invalid
// answer, or no answer by the deadline) makes its own choice that tick.
//
// Rules (as RynthAi.Script, Shared/RynthAiScriptApi.cs):
// - Its own interface, so RynthAi.Script v1 (exact-version checked) and
// RynthAi.Status stay as they are.
// - Append-only: new functions and request fields go at the end, and Version
// goes up. CombatRequestV1.StructSize is set by the caller before Poll;
// RynthAi never writes past it.
// - Strings are UTF-8, NUL-terminated.
// - Call only from the plugin pump thread (OnTick), never from AC's thread or Render.
// - Every function returns safely (no exception crosses the boundary).
// - Times are Environment.TickCount64 milliseconds (one clock per process).
// ============================================================================
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
/// <summary>Constants of the "RynthAi.Combat" exchange: kinds, decision flags, lease and timeout bounds.</summary>
public static class RynthAiCombat
{
/// <summary>Kind bit: the spell of RynthAi's next attack cast (Magic mode, after its debuffs).</summary>
public const uint KindAttack = 1;
/// <summary>Kind bit: the spell of the next vitals heal (health under Heal At / Top Off HP), asked before kits.</summary>
public const uint KindHeal = 2;
/// <summary>Every kind this version knows.</summary>
public const uint KindsAll = KindAttack | KindHeal;
/// <summary>Decision flag: an area cast (ring, wall, chain): no blacklist or pending-offensive judgement on it.</summary>
public const uint FlagArea = 1;
/// <summary>
/// Decision flag: a single-target cast that is not meant to damage (a debuff, a drain, a
/// utility spell): no no-damage blacklist judgement on it. Flags are append-only; RynthAi
/// ignores bits it does not know.
/// </summary>
public const uint FlagNoJudge = 2;
/// <summary>Lease length when Claim passes 0, and its bounds (clamped).</summary>
public const uint DefaultLeaseMs = 1500;
public const uint MinLeaseMs = 500;
public const uint MaxLeaseMs = 3000;
/// <summary>How long RynthAi waits for an answer before casting its own choice (0 = default), and the bounds.</summary>
public const uint DefaultAttackTimeoutMs = 1000;
public const uint DefaultHealTimeoutMs = 750;
public const uint MinTimeoutMs = 100;
public const uint MaxTimeoutMs = 3000;
/// <summary>Longest owner name RynthAi keeps (characters).</summary>
public const int MaxOwnerLength = 64;
/// <summary>"attack", "heal", "attack+heal" or "none".</summary>
public static string KindNames(uint kinds)
{
kinds &= KindsAll;
if (kinds == 0) return "none";
if (kinds == KindsAll) return "attack+heal";
return kinds == KindAttack ? "attack" : "heal";
}
/// <summary>A lease length within the bounds (0 = the default).</summary>
public static uint ClampLease(uint ms) => ms == 0 ? DefaultLeaseMs : ms < MinLeaseMs ? MinLeaseMs : ms > MaxLeaseMs ? MaxLeaseMs : ms;
/// <summary>A request timeout within the bounds (0 = <paramref name="fallback"/>).</summary>
public static uint ClampTimeout(uint ms, uint fallback) => ms == 0 ? fallback : ms < MinTimeoutMs ? MinTimeoutMs : ms > MaxTimeoutMs ? MaxTimeoutMs : ms;
}
/// <summary>
/// An open request, as Poll hands it out. Blittable; the caller sets StructSize to
/// sizeof(CombatRequestV1) before Poll and RynthAi fills at most that many bytes.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CombatRequestV1
{
/// <summary>Set by the caller before Poll: the size of the struct it passes.</summary>
public uint StructSize;
/// <summary>The request's id; Decide must quote it. Never 0.</summary>
public uint Seq;
/// <summary>RynthAiCombat.KindAttack or KindHeal.</summary>
public uint Kind;
/// <summary>
/// Attack: RynthAi's locked target. Heal: RynthAi's current fight target, informational (0 when
/// none); a heal decision's target 0 still means the player.
/// </summary>
public uint TargetId;
/// <summary>That target's health, 0..1; -1 unknown or no target.</summary>
public float TargetHealth;
/// <summary>The player's vitals in percent; -1 unknown.</summary>
public int HealthPct;
public int StaminaPct;
public int ManaPct;
/// <summary>Heal: the health line it is under (Heal At in combat, Top Off HP idle). Attack: 0.</summary>
public int HealLine;
/// <summary>1 when a monster is engaged or within Monster Range.</summary>
public int InCombat;
/// <summary>AC's combat mode (1 NonCombat, 2 Melee, 4 Missile, 8 Magic).</summary>
public int CombatMode;
/// <summary>When the request was opened, and when RynthAi stops waiting for it.</summary>
public long IssuedAtMs;
public long DeadlineMs;
/// <summary>The last decision of this kind RynthAi consumed: its Seq, the spell cast (0 = declined or rejected), the target and when.</summary>
public uint LastSeq;
public uint LastSpell;
public uint LastTarget;
public long LastAtMs;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthAiCombatApiV1
{
public const string InterfaceName = "RynthAi.Combat";
public const uint InterfaceVersion = 1;
public uint Version; // InterfaceVersion of the table RynthAi filled
public uint StructSize; // sizeof(RynthAiCombatApiV1) as RynthAi built it
/// <summary>
/// Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, owner): take or renew the hook for
/// <c>kinds</c> (RynthAiCombat.Kind* bits) until now + leaseMs (clamped; 0 = default). Renew it
/// every tick. The kinds passed replace the ones held. Returns the kinds granted: 0 while another
/// owner's lease is live (the names compare case-sensitively).
/// </summary>
public delegate* unmanaged[Cdecl]<uint, uint, uint, uint, byte*, int> Claim;
/// <summary>Release(kinds): drop those kinds now (an open request of them is cancelled: native that tick).</summary>
public delegate* unmanaged[Cdecl]<uint, void> Release;
/// <summary>Poll(kind, request): 1 when a request of that kind is open and unanswered (filled in), else 0.</summary>
public delegate* unmanaged[Cdecl]<uint, CombatRequestV1*, int> Poll;
/// <summary>
/// Decide(seq, kind, spellId, targetId, flags): the answer to request <c>seq</c>. spellId 0 =
/// decline (RynthAi chooses); targetId 0 = the request's target (the player for a heal);
/// flags RynthAiCombat.Flag*. 1 = taken; 0 = stale (another seq, already answered, past its
/// deadline, or the kind isn't held). Taken is not cast: RynthAi still validates it.
/// </summary>
public delegate* unmanaged[Cdecl]<uint, uint, uint, uint, uint, int> Decide;
/// <summary>
/// GetScanned(ids, distances, capacity): RynthAi's current target candidates (in range,
/// attackable, line of sight), nearest first. Writes up to capacity and returns how many
/// there are in all (ids null: just the count).
/// </summary>
public delegate* unmanaged[Cdecl]<uint*, float*, int, int> GetScanned;
}