Merge rynth/main (2026.10.8.1) into sk/features-on-rynth-main

Resolves the conflicts that kept PR #2 from merging. Where rynth/main
already ships the same feature, its version wins: the shared read-only
RynthInstallPaths, /ra iteminfo (PR #2's Mag-Tools item info window is
dropped), pet essence refill trust, object filing, spell metadata and the
Monster Editor's Category / MatchExpression.

See Changelog/2026-10-08-merge-rynth-main-into-pr2.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-08 22:23:49 -04:00
commit 2e54796b15
160 changed files with 15447 additions and 2566 deletions

View file

@ -39,6 +39,8 @@ public enum LongValueKey
public enum StringValueKey
{
Name = 1,
// ACECustom puts the T11 "Modifiers:" block of armor, clothing and jewelry here.
Use = 14,
ShortDesc = 15,
LongDesc = 16,
PluralName = 20,
@ -47,7 +49,9 @@ public enum StringValueKey
/// <summary>
/// STypeFloat keys used with TryGetObjectDoubleProperty / WorldObjectCache.GetDoubleProperty.
/// Values match Chorizite's STypeFloat sequential enum.
/// Values match ACE's PropertyFloat and Chorizite's STypeFloat (UNDEF = 0). WeaponOffense and
/// DamageMod were 61/62 until 2026-10-05 (61 is EconRecoveryInterval), so a native "damage
/// percent" loot rule read the weapon's attack mod; PowerLevel/AccuracyLevel were 86/87.
/// </summary>
public enum DoubleValueKey
{
@ -57,10 +61,10 @@ public enum DoubleValueKey
MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised
WeaponDefense = 29,
UseRadius = 54,
WeaponOffense = 61,
DamageMod = 62,
PowerLevel = 86,
AccuracyLevel = 87,
WeaponOffense = 62,
DamageMod = 63,
PowerLevel = 92,
AccuracyLevel = 93,
}
// ── Combat mode int constants (matches acclient.exe CM_Combat enum) ────────
@ -117,13 +121,34 @@ public class WorldObject
public int Values(int key, int defaultValue)
{
// T11 virtual keys are computed from the item's text, never stored on the object.
if (RynthCore.Loot.T11.T11Keys.IsVirtual(key))
return Loot.T11ItemSupport.VirtualValue(this, key, defaultValue);
// Decal's synthetic keys that are a plain int property (MaxDamage = Damage 44, Coverage =
// ClothingPriority 4, ...) read as that property, from the overlay or live. The icon and
// spell ones are data ids: WorldObjectCache.GetIntProperty answers them.
uint decalStype = WorldObjectCache.DecalIntStype(unchecked((uint)key));
if (decalStype != 0)
return Values(unchecked((int)decalStype), defaultValue);
var o = Overlay;
if (o != null)
{
if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v;
if (!o.LiveFallback) return defaultValue;
if (!o.LiveFallback) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue);
}
return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
if (Cache == null) return Loot.T11ItemSupport.StrippedValue(this, key, defaultValue);
// T11 appraisals omit the item-aug wield gate (158-160) and modifier-carried ratings
// (370-379); an absent or zero value there falls back to what the item's text says.
if (RynthCore.Loot.T11.T11Keys.IsStrippedKey(key))
{
int live = Cache.GetIntProperty(Id, (uint)key, int.MinValue);
if (live != int.MinValue && live != 0) return live;
return Loot.T11ItemSupport.StrippedValue(this, key, live == int.MinValue ? defaultValue : 0);
}
return Cache.GetIntProperty(Id, (uint)key, defaultValue);
}
public string Values(StringValueKey key, string defaultValue)

View file

@ -158,6 +158,15 @@ public class BuffManager : IDisposable
private readonly Dictionary<int, DateTime> _buffFailCooldownUntil = new();
private const double BuffFailCooldownSec = 120.0;
// A vital spell LEVEL the server refused for missing components (Revitalize, Heal, Stamina
// to Mana...): that level is passed over for NoComponentsLevelSec and the next lower level
// with components is cast instead. It used to park the whole family, then retry the same
// top level the character had no components for (2026-10-08).
private readonly Dictionary<int, DateTime> _noComponentsUntil = new();
private const double NoComponentsLevelSec = 600.0;
private bool LevelLacksComponents(int spellId)
=> _noComponentsUntil.TryGetValue(spellId, out DateTime until) && DateTime.Now < until;
// Per-family SILENT no-show counter. Distinct from _buffFailCooldownUntil
// (which catches chat-explicit hard rejects). This catches the /god case:
// skill is Trained → IsSkillUsable says yes → BuildDynamicBuffList includes
@ -328,6 +337,16 @@ public class BuffManager : IDisposable
// stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield
// the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never
// loop forever; on exhaustion the buff family is parked and the bot fights unbuffed.
// Switch like a player (2026-10-06): a use of the wand goes through ClientUISystem::UseObject,
// the client's double-click, which puts the weapon in hand away by itself (ACE's
// DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items
// automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it,
// then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't
// got the wand into the hand in WieldResolveTimeoutMs, this session moves the weapon first.
private bool _directWandSwapFailed;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
private int _bowDequipPendingId;
private DateTime _bowDequipAt = DateTime.MinValue;
private int _bowDequipAttempts;
@ -466,6 +485,27 @@ public class BuffManager : IDisposable
{ AcSkillType.Summoning, "Summoning Mastery" },
};
/// <summary>
/// The prots and banes the Buffing settings let the player untick (LegacyUiSettings.DisabledBuffs),
/// paired by element for the two-column grid: (buff base name, label). Armor Self and
/// Impenetrability head the columns. The cast order stays BuildDynamicBuffList's.
/// </summary>
internal static readonly (string Buff, string Label)[] ToggleProtections =
{
("Armor Self", "Armor"), ("Fire Protection Self", "Fire"), ("Cold Protection Self", "Cold"),
("Acid Protection Self", "Acid"), ("Lightning Protection Self", "Lightning"),
("Blade Protection Self", "Blade"), ("Piercing Protection Self", "Piercing"),
("Bludgeoning Protection Self", "Bludgeoning"),
};
internal static readonly (string Buff, string Label)[] ToggleBanes =
{
("Impenetrability", "Impenetrability"), ("Flame Bane", "Flame"), ("Frost Bane", "Frost"),
("Acid Bane", "Acid"), ("Lightning Bane", "Lightning"),
("Blade Bane", "Blade"), ("Piercing Bane", "Piercing"),
("Bludgeoning Bane", "Bludgeoning"),
};
public BuffManager(RynthCoreHost host, LegacyUiSettings settings, SpellManager spellManager, PlayerVitalsCache vitals)
{
_host = host;
@ -1117,6 +1157,18 @@ public class BuffManager : IDisposable
return;
}
// One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no kit, potion,
// wand, stance change or cast while the server hasn't answered the last one (its UseDone;
// a buff's enchantment lands before that). Heals keep their priority (ActionPacer's heal
// rules). And not while RynthAi still has the character running: the arbiter's stop goes
// out this tick, the cast the next one (a stop mid-windup disturbs the cast).
if (!PacerAllows(out string paceWhy))
{
LastBuffSkipReason = "server answering the last action: " + paceWhy;
Hold("server answering the last action", paceWhy);
return;
}
// Don't issue a cast while the previous cast GESTURE is still animating.
// CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast
// gate). AC refuses a cast issued mid-gesture with a server-driven
@ -1135,6 +1187,7 @@ public class BuffManager : IDisposable
// everything else still waits for the count to drop.
bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
bool busyHolds = BusyCount > 0
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
if (!gateOpen || busyHolds)
{
@ -1157,6 +1210,14 @@ public class BuffManager : IDisposable
return;
}
// Health floor: no buff while health is under a heal line that nothing could heal
// (Drakkon, 2026-10-06 04:51: recasting Swift Killer at 19% health, dead 10 s later).
if (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct))
{
Hold("health under a heal line");
return;
}
// Mana floor: no buff while mana is under Get Mana At. CheckVitals above already tried
// Stamina to Mana and a mana potion; when neither could run (stamina too low, none
// carried) buffing used to carry on and run mana to 0. Wait for it instead.
@ -1392,7 +1453,7 @@ public class BuffManager : IDisposable
bool inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
int stamThreshold = inCombat ? _settings.RestamAt : _settings.TopOffStam;
int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
// A flag is set only when something was actually done about the vital.
// WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so
@ -1409,6 +1470,16 @@ public class BuffManager : IDisposable
if (!healed) { _vitalWhy = ""; healed = AttemptVitalCast("Heal Self"); }
string spellWhy = _vitalWhy;
if (!healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); }
// Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all
// (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later).
if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal))
{
string potionWhy = _vitalWhy;
_vitalWhy = "";
healed = AttemptHealthKitUse(ignoreMinSuccess: true);
if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %.");
else _vitalWhy = potionWhy;
}
if (healed)
{
_isHealingSelf = true;
@ -1438,16 +1509,54 @@ public class BuffManager : IDisposable
}
// Stamina kits first, like healing kits for health: Lucy carried Greater Stamina Kits
// and cast Revitalize/Robustification instead, because stamina never looked for a kit.
if (curStamPct < stamThreshold && (AttemptStaminaKitUse() || AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina")))
// Melee first (Tom, 2026-10-06): out of Magic stance, Revitalize means switching the weapon
// for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina
// potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize
// on top of it. In Magic stance (a caster) Revitalize stays first.
bool potionFirst = CurrentCombatMode != CombatMode.Magic;
if (curStamPct < stamThreshold)
{
_isRechargingStamina = true;
return true;
bool potionJustDrunk = potionFirst && _settings.UsePotions
&& (DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500
&& HasListedPotion("StaminaPotion", "Stamina");
if (!potionJustDrunk
&& (AttemptStaminaKitUse()
|| (potionFirst && AttemptPotion(true, "StaminaPotion", "Stamina"))
|| AttemptVitalCast("Revitalize Self")
|| AttemptPotion("StaminaPotion", "Stamina")))
{
_isRechargingStamina = true;
if (_restamRun) _restamRunCasts++;
return true;
}
}
return false;
}
// Re-stam To (2026-10-06): a recharge started under Re-stam At carries on until stamina
// reaches Re-stam To; one Revitalize often doesn't get far. Capped so a recharge that
// never gains can't loop: it ends after RestamRunMaxCasts.
private bool _restamRun;
private int _restamRunCasts;
internal const int RestamRunMaxCasts = 4;
/// <summary>The stamina % to recharge under now (see the fields above).</summary>
internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts)
{
if (!inCombat) { run = false; return s.TopOffStam; }
if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; }
if (stamPct < s.RestamAt)
{
if (!run) { run = true; casts = 0; }
}
else if (stamPct >= s.RestamTo || casts >= RestamRunMaxCasts)
{
run = false;
}
return run ? s.RestamTo : s.RestamAt;
}
/// <summary>True when Stamina To Health At / Min Stamina allow Stamina to Health Self now.</summary>
internal static bool StaminaToHealthAllowed(LegacyUiSettings s, int healthPct, int staminaPct)
=> s.StaminaToHealthAt > 0 && healthPct <= s.StaminaToHealthAt && staminaPct > s.StaminaToHealthMinStamina;
@ -1485,6 +1594,7 @@ public class BuffManager : IDisposable
if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return;
if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return;
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return;
if (!ActionPacer.MayStart(_host, "Buff", HealNeed.Emergency, out _)) return;
if (AttemptHealthKitUse() || AttemptPotion("HealthPotion"))
{
_lastPendingEmergencyHealAt = DateTime.Now;
@ -1540,7 +1650,19 @@ public class BuffManager : IDisposable
_healWaitKind = "server finishing the last cast";
return true;
}
int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic);
int spellId = _spellManager.GetDynamicSelfBuffId(baseName, AcSkillType.LifeMagic, LevelLacksComponents);
// A heal with nothing known at the allowed tiers: the lowest known tier above them.
// Vitae can drop Life Magic under a tier line while only higher tiers are known.
if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self")
{
spellId = _spellManager.GetSelfSpellIdAboveAllowedTier(baseName, AcSkillType.LifeMagic);
if (spellId != 0 && (DateTime.Now - _lastAboveTierLog).TotalSeconds >= 30)
{
_lastAboveTierLog = DateTime.Now;
_host.Log($"[RynthAi] Vitals: no '{baseName}' at the tiers Life Magic allows now; " +
$"trying {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} (may fizzle).");
}
}
if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers");
// Parked after a hard server refusal (see OnChatWindowText) — the same
// per-family cooldown the buff selectors honour.
@ -1566,7 +1688,8 @@ public class BuffManager : IDisposable
_pendingSpellId = spellId;
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
_pendingVitalLabel = VitalLabel(baseName);
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff",
SpellTableStub.GetById(spellId)?.Name ?? baseName);
_lastCastAttempt = DateTime.Now;
if (!castOk)
{
@ -1589,7 +1712,21 @@ public class BuffManager : IDisposable
/// Drinks the first potion of <paramref name="types"/> from the Items panel.
/// "Stamina" is the older name for stamina potions. Off with UsePotions.
/// </summary>
private bool AttemptPotion(params string[] types)
private bool AttemptPotion(params string[] types) => AttemptPotion(false, types);
/// <summary>A potion of one of <paramref name="types"/> listed in Consumables and in the pack.</summary>
private bool HasListedPotion(params string[] types)
{
if (_worldObjectCache == null) return false;
foreach (var rule in _settings.ConsumableRules)
if (Array.FindIndex(types, t => t.Equals(rule.Type, StringComparison.OrdinalIgnoreCase)) >= 0
&& _worldObjectCache[rule.Id] != null)
return true;
return false;
}
/// <summary><paramref name="listedOnly"/>: only the Consumables list, not any potion in the pack.</summary>
private bool AttemptPotion(bool listedOnly, params string[] types)
{
if (!_settings.UsePotions || _worldObjectCache == null) return VitalNo("Use Potions is off");
if ((DateTime.Now - _lastPotionAt).TotalMilliseconds < 2500) return VitalNo("one drunk under 2.5 s ago");
@ -1605,6 +1742,7 @@ public class BuffManager : IDisposable
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
return true;
}
if (listedOnly) return VitalNo("none listed in Consumables");
// Nothing on the Items panel: anything in the pack of that kind (Field Rations
// weren't used unless someone added them by hand, 2026-09-29).
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: false))
@ -1726,7 +1864,9 @@ public class BuffManager : IDisposable
}
private DateTime _lastPotionAt = DateTime.MinValue;
private bool AttemptHealthKitUse()
private DateTime _lastAboveTierLog = DateTime.MinValue;
private bool AttemptHealthKitUse(bool ignoreMinSuccess = false)
{
if (_worldObjectCache == null) return false;
// VTank's kit options: skip kits in magic mode unless allowed; optionally
@ -1745,10 +1885,10 @@ public class BuffManager : IDisposable
if (KitRetryWait(out string kitWait)) return VitalNo(kitWait);
// Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it.
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
{
_host.ChangeCombatMode(CombatMode.NonCombat);
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit");
_lastCastAttempt = DateTime.Now;
_healWaitKind = "peace mode for the kit";
return true; // use the kit next tick, once in peace mode
@ -1781,7 +1921,7 @@ public class BuffManager : IDisposable
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false;
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
{
_host.ChangeCombatMode(CombatMode.NonCombat);
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit");
_lastCastAttempt = DateTime.Now;
return true; // use the kit next tick, once in peace mode
}
@ -2102,7 +2242,7 @@ public class BuffManager : IDisposable
// buffed when it wasn't and never retried the known tier.
if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)");
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName);
_lastCastAttempt = DateTime.Now;
if (castOk) NoteCastIssued(spellId);
if (castOk && buffFamily != 0 && spellInfo != null)
@ -2997,6 +3137,12 @@ public class BuffManager : IDisposable
final.AddRange(step5_LifeAndItem);
final.AddRange(step6_WeaponAuras);
final.AddRange(step7_ArmorBanes);
// Buffs the player unticked (Buffing settings: prots and banes) leave the list here, so
// the cast loop never casts them and NeedsAnyBuff never waits on them: a skipped buff
// can't hold the bot in Buffing.
if (_settings.DisabledBuffs.Count > 0)
final.RemoveAll(_settings.IsBuffDisabled);
return final;
}
@ -3206,7 +3352,15 @@ public class BuffManager : IDisposable
if (_pendingSpellId != 0)
{
var pendingSpell = SpellTableStub.GetById(_pendingSpellId);
if (pendingSpell != null)
bool noCompsVital = _pendingSpellId == _pendingVitalSpellId
&& (lower.Contains("components") || lower.Contains("missing some required"));
if (pendingSpell != null && noCompsVital)
{
// A vital spell: pass over this level only; the next lower one goes next.
_noComponentsUntil[_pendingSpellId] = DateTime.Now.AddSeconds(NoComponentsLevelSec);
_host.WriteToChat($"[RynthAi] No components for {pendingSpell.Name}: using a lower level for {NoComponentsLevelSec / 60:0} min.", 2);
}
else if (pendingSpell != null)
{
if (IsItemEnchantment(pendingSpell.Name))
{
@ -3364,6 +3518,50 @@ public class BuffManager : IDisposable
_onCastResolved?.Invoke($"cast '{spellName}'");
}
/// <summary>What a heal needs from the pacing now: none, a heal line, or Emergency Heal At.</summary>
internal HealNeed HealNeedNow()
{
if (_vitals.MaxHealth <= 0) return HealNeed.None;
int hp = _vitals.HealthPct;
int emergencyAt = _settings.EmergencyHealAt;
if (emergencyAt > 0 && hp <= emergencyAt) return HealNeed.Emergency;
return HealthUnderAnyLine(hp, _vitals.StaminaPct) ? HealNeed.Heal : HealNeed.None;
}
/// <summary>Times the vitals/buff step waited for the server's answer (tests, status).</summary>
internal int PacerHolds { get; private set; }
/// <summary>
/// The pacing gate of the vitals/buff step (see HeartbeatCore): false while the server is still
/// answering the last action (ActionPacer.MayStart, with the heal rules) or while RynthAi still
/// has the character running (the arbiter's stop goes out first).
/// </summary>
private bool _pacerLetHealAhead;
private bool PacerAllows(out string why)
{
why = "";
_pacerLetHealAhead = false;
if (!ActionPacer.Enabled) return true;
if (MoveAudit.OwnMovementActive)
{
why = "the character is still moving (the stop goes out first)";
PacerHolds++;
return false;
}
HealNeed need = HealNeedNow();
bool outstanding = ActionPacer.Current(_host) != null;
if (ActionPacer.MayStart(_host, "Buff", need, out why))
{
// A heal let ahead of an unanswered action: the busy count still counts that action,
// so the busy gate below must not hold the heal again.
_pacerLetHealAhead = outstanding && need != HealNeed.None;
return true;
}
PacerHolds++;
return false;
}
/// <summary>Record that a cast just went out, so the next one waits for the
/// server to report the action finished rather than a blind interval.</summary>
private void NoteCastIssued(int spellId)
@ -3491,6 +3689,7 @@ public class BuffManager : IDisposable
var held = _cast.Open;
string name = held?.Name ?? "?";
double secs = _cast.HeldSeconds;
FlightRecorderSignal.Dump(_host, $"held cast nudge: '{name}' {secs:0.0} s");
if (!_host.HasSetAutoRun)
{
_host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation, but this engine has no SetAutoRun: no nudge.");
@ -3740,9 +3939,9 @@ public class BuffManager : IDisposable
// _lastBuffStanceAttempt), while buffing held the bot.
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs)
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
{
_host.ChangeCombatMode(CombatMode.Magic);
NoteStanceRequest();
_lastBuffStanceAttempt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
@ -3801,6 +4000,20 @@ public class BuffManager : IDisposable
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
return false;
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
{
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
int stillInHand = _directWandSwapFailed ? 0 : FindWieldedNonWandWeapon(wandId);
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
_directWandSwapFailed = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
"from now on the weapon goes into a pack first");
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
_pendingWieldId = 0;
@ -3838,7 +4051,7 @@ public class BuffManager : IDisposable
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
if (bowId != 0)
if (bowId != 0 && (_directWandSwapFailed || !IsWieldedLive(bowId))) // else the use swaps (see _directWandSwapFailed)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
@ -3861,6 +4074,7 @@ public class BuffManager : IDisposable
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
_bowDequipAt = now;
_lastCastAttempt = now;
@ -3870,8 +4084,9 @@ public class BuffManager : IDisposable
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_host.UseFor((uint)wandId, "Buff", "buffing: wield the wand");
_host.UseFor((uint)wandId, "Buff", bowId != 0 && !_directWandSwapFailed ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
_pendingWieldAt = now;
_lastCastAttempt = now;
@ -3924,9 +4139,9 @@ public class BuffManager : IDisposable
if (shift > 5) shift = 5;
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
if (gateMs > 30000) gateMs = 30000; // cap at 30s
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs)
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
{
_host.ChangeCombatMode(CombatMode.Magic);
NoteStanceRequest();
_lastBuffStanceAttempt = DateTime.Now;
_lastCastAttempt = DateTime.Now;

View file

@ -156,6 +156,8 @@ internal sealed class CastTracker
private void Close(Cast c, string kind)
{
c.Done = true;
// The server is in the cast's recoil now: one heal may be queued behind it (ActionPacer).
RynthCore.Plugin.Shared.ActionPacer.NoteCastResult();
DateTime now = Now;
string nudged = c.Nudged ? " (after the movement nudge)" : "";
if (c.HasIncantation)

View file

@ -220,6 +220,7 @@ public partial class CombatManager
var wo = _worldFilter[wielded.Id];
int amount = Math.Max(1, wo?.Values(LongValueKey.StackCount, 1) ?? 1); // the whole stack, not one arrow
_host.MoveItemInternal(unchecked((uint)wielded.Id), unchecked((uint)packId), 0, amount);
_weaponSwapGate?.NoteMove(wielded.Id, wieldedNow: true);
_ammoDequipPendingId = wielded.Id;
_ammoDequipAt = now;
_ammoDequipTries++;

View file

@ -285,6 +285,7 @@ public partial class CombatManager
if (!gateHeld && _weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-offhand-dequip")) return OffPrep.Busy;
_host.MoveItemInternal(unchecked((uint)offId), unchecked((uint)packId), 0, 1);
_weaponSwapGate?.NoteMove(offId, wieldedNow: true);
_offDequipPendingId = offId;
_offDequipAt = now;
_offDequipTries++;
@ -379,6 +380,7 @@ public partial class CombatManager
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(plan.Id, _offSwapFrom, now);
_weaponSwapGate?.NoteMove(plan.Id, wieldedNow: false);
_offSwapFrom = 0;
_lastEquipTime = now;
if (plan.Id != _stowedOffhandId) _stowedOffhandId = 0; // a listed one replaces what was taken off

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,126 @@
using System;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The one "time since our last kill" clock (2026-10-06). Read by the meta expression
/// secondssincelastkill[], the "No Kills Within Minutes" meta condition and the status feed's
/// secsSinceLastKill.
///
/// A kill is ACE's KillerNotification (GameEvent 0x01AD), which the server sends only to the
/// killer: RynthAiPlugin.OnKillNotification is the only caller of <see cref="RecordKill"/>.
/// Death messages in chat ("X died", a fellow's kill) never count.
///
/// Before the first kill this session the clock counts from the last macro start, or, if the
/// macro hasn't been started since login, from login (a plugin load or hot reload counts as a
/// login), so a meta can still act on "no kills at all". After that it counts from the later of
/// the last kill and the last macro start: restarting the macro starts the count again.
///
/// Monotonic (Environment.TickCount64, not the wall clock). Writers are the plugin pump thread;
/// the status feed reads from its poll thread, so every field is read and written with Interlocked.
/// </summary>
internal sealed class KillClock
{
private const long None = long.MinValue;
private readonly Func<long> _nowMs;
private long _sessionStartMs;
private long _macroStartMs = None;
private long _lastKillMs = None;
private int _macroWasRunning;
/// <param name="nowMs">Monotonic milliseconds; tests pass a fake clock.</param>
public KillClock(Func<long>? nowMs = null)
{
_nowMs = nowMs ?? (static () => Environment.TickCount64);
_sessionStartMs = _nowMs();
}
/// <summary>Asked on every read, so a macro start is seen before the first condition after it.
/// The plugin also calls <see cref="ObserveMacro"/> every tick.</summary>
public Func<bool>? MacroRunning { get; set; }
/// <summary>Login (and plugin load): no kill yet, the clock counts from now. A macro that is
/// already on (start macro on login) counts as started now.</summary>
public void SessionStarted()
{
Interlocked.Exchange(ref _sessionStartMs, _nowMs());
Interlocked.Exchange(ref _macroStartMs, None);
Interlocked.Exchange(ref _lastKillMs, None);
Interlocked.Exchange(ref _macroWasRunning, 0);
Observe();
}
/// <summary>Notes a macro start (off to on). Safe to call any number of times.</summary>
public void ObserveMacro(bool running)
{
int prev = Interlocked.Exchange(ref _macroWasRunning, running ? 1 : 0);
if (running && prev == 0)
Interlocked.Exchange(ref _macroStartMs, _nowMs());
}
/// <summary>We killed something (KillerNotification only).</summary>
public void RecordKill() => Interlocked.Exchange(ref _lastKillMs, _nowMs());
/// <summary>True once we have a kill this session.</summary>
public bool HasKill => Interlocked.Read(ref _lastKillMs) != None;
/// <summary>What the clock counts from: "kill", "macro start" or "login".</summary>
public string Since
{
get
{
Observe();
long kill = Interlocked.Read(ref _lastKillMs), macro = Interlocked.Read(ref _macroStartMs);
if (kill != None && kill >= macro) return "kill";
return macro != None ? "macro start" : "login";
}
}
/// <summary>Milliseconds since our last kill (before the first: since the macro start, or login). Never negative.</summary>
public long ElapsedMs()
{
Observe();
// The later of the last kill and the last macro start: a restart after a long pause
// starts the count again (Tom, 2026-10-06), so "no kills in 10 min" doesn't fire at once.
long from = Math.Max(Interlocked.Read(ref _lastKillMs), Interlocked.Read(ref _macroStartMs));
if (from == None) from = Interlocked.Read(ref _sessionStartMs);
return Math.Max(0, _nowMs() - from);
}
/// <summary>Whole seconds for secondssincelastkill[].</summary>
public long SecondsSinceLastKill() => ElapsedMs() / 1000;
/// <summary>Whole seconds since an actual kill, or -1 before the first (the status feed's value).</summary>
public int SecondsSinceKillOnly()
{
long kill = Interlocked.Read(ref _lastKillMs);
if (kill == None) return -1;
return (int)Math.Clamp((_nowMs() - kill) / 1000, 0, int.MaxValue);
}
/// <summary>"No Kills Within Minutes": true when nothing was killed for at least
/// <paramref name="minutes"/> minutes (decimals allowed: 0.5 = 30 s).</summary>
public bool NoKillsFor(double minutes) => ElapsedMs() >= minutes * 60_000.0;
/// <summary>The condition's value as typed in the editor or the .af file: minutes, decimals
/// allowed ("5", "2.5"; a comma decimal is accepted too). False for empty, negative or not a number.</summary>
public static bool TryParseMinutes(string? text, out double minutes)
{
minutes = 0;
if (string.IsNullOrWhiteSpace(text)) return false;
string t = text.Trim().Replace(',', '.');
if (!double.TryParse(t, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out double m)) return false;
if (double.IsNaN(m) || double.IsInfinity(m) || m < 0) return false;
minutes = m;
return true;
}
private void Observe()
{
Func<bool>? probe = MacroRunning;
if (probe != null) ObserveMacro(probe());
}
}

View file

@ -223,7 +223,7 @@ public class MissileCraftingManager
_combinesCompleted = 0;
_allCombinesDone = false;
try { _host.ChangeCombatMode(CombatMode.NonCombat); } catch { }
try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { }
var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList();
var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList();

View file

@ -60,13 +60,15 @@ internal sealed class PetManager
// get parked so we advance to the next configured essence instead of looping.
private readonly Dictionary<int, long> _deviceCooldownUntil = new();
// Essences the server just confirmed full ("You add the spirit…" / "…already full"). Until a
// summon reports "not enough charges", their Structure read is not trusted: the cached value
// can still be the empty 0 from the last appraisal, which re-issued the refill in a loop
// (spirit use → peace mode → clap) on 2026-10-04.
private readonly Dictionary<int, long> _confirmedFullUntil = new();
// Refills issued per essence inside RefillLoopWindowMs; a third one parks the essence.
private readonly Dictionary<int, (int Count, long WindowStart)> _refillAttempts = new();
// The server's word over a stale Structure read (2026-10-05). A read
// can say 0 while the server holds a full essence; the server then answers a refill with
// "already full" (or refills it and the read still lags), and deciding from the read alone
// re-issued the refill every think tick: peace mode and a clap each time, a spirit each time
// the refill was real. Essence -> until when its read of 0 is not believed; cleared when a
// summon reports "not enough charges".
private readonly Dictionary<int, long> _serverSaidFullUntil = new();
// Refills issued per essence: how many since the window opened, and when it opened.
private readonly Dictionary<int, (int Count, long Since)> _refills = new();
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
// by name; it is never itself a summon device.
@ -77,15 +79,17 @@ internal sealed class PetManager
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
private const long DeviceNoSpiritCooldownMs = 15_000;
private const long ConfirmedFullTrustMs = 30 * 60_000;
private const long RefillLoopWindowMs = 120_000;
private const int RefillLoopMaxAttempts = 2;
private const long RefillLoopParkMs = 300_000;
private const long ServerSaidFullTrustMs = 30 * 60_000;
private const long RefillWindowMs = 120_000; // two refills inside this and the
private const int RefillsPerWindow = 2; // essence still reads empty:
private const long RefillLoopParkMs = 300_000; // park it this long
private string _playerName = string.Empty;
private long _playerNameAt;
private static long NowMs => Environment.TickCount64;
/// <summary>Clock (ms); tests replace it.</summary>
internal static Func<long> Clock { get; set; } = static () => Environment.TickCount64;
private static long NowMs => Clock();
/// <summary>
/// Optional ILT Hub hook: when it returns true an EMPTY essence is used anyway, because
@ -190,8 +194,8 @@ internal sealed class PetManager
// Drop to Idle; the next think tick reads Structure==0 and refills it.
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
{
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
_confirmedFullUntil.Remove(_activeDeviceId); // really empty now — a refill is due
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
_serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again
// The server-side pyreal refill didn't happen (charm off / no pyreals):
// park the essence so the empty-summon path can't spin on it.
if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0)
@ -205,21 +209,13 @@ internal sealed class PetManager
if (_state == PetState.Refilling)
{
// "You add the spirit to the essence." (success) / "This essence is
// already full." (our Structure read was stale — also done).
// already full." (our Structure read was stale — also done). Either way the
// essence is full now, whatever its read says until the next update.
bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase);
bool full = text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
bool full = !added && text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
if (added || full)
{
int device = _activeDeviceId;
if (device != 0)
{
_confirmedFullUntil[device] = NowMs + ConfirmedFullTrustMs;
// Refresh the cached Structure so the roster / HUD and later reads agree.
if (_host.HasRequestId) _host.RequestId(unchecked((uint)device));
}
RynthLog.Write(LogCat.Pets, added
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)device:X8}, server confirmed)."
: $"[RynthAi] Pet: essence 0x{(uint)device:X8} is already full; charge read was stale.");
OnServerSaidFull(_activeDeviceId, added);
GoIdle();
}
}
@ -258,12 +254,11 @@ internal sealed class PetManager
int charges = ReadCharges(deviceId); // -1 = unreadable
// The server said this essence is full since the read went stale — summon from it.
if (charges == 0 && _confirmedFullUntil.TryGetValue(deviceId, out long trustUntil))
{
if (now < trustUntil) charges = -1;
else _confirmedFullUntil.Remove(deviceId);
}
// The server called this essence full after the read last changed: the 0 is stale.
// Summon as for an unreadable one (an empty essence is refused harmlessly, and that
// "not enough charges" ends the trust).
if (charges == 0 && ServerSaidFull(deviceId, now))
charges = -1;
if (charges != 0)
{
@ -285,13 +280,13 @@ internal sealed class PetManager
if (_settings.PetAutoRefill)
{
int spiritId = FindEncapsulatedSpirit();
if (spiritId != 0)
if (spiritId != 0 && !RefillLooping(deviceId, now))
{
if (RefillLoopDetected(deviceId, now))
continue;
IssueRefill(deviceId, spiritId);
return;
}
if (spiritId != 0)
continue; // parked by RefillLooping; try the next essence
}
// Out of charges and no spirit (or refill off): park this essence
@ -323,34 +318,54 @@ internal sealed class PetManager
_activeDeviceId = deviceId;
_activeSpiritId = spiritId;
_actionIssuedAt = NowMs;
RecordRefillAttempt(deviceId, _actionIssuedAt);
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
CountRefill(deviceId, _actionIssuedAt);
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
}
/// <summary>Counts refills per essence inside <see cref="RefillLoopWindowMs"/>.</summary>
private void RecordRefillAttempt(int deviceId, long now)
/// <summary>
/// The server said the essence is full ("You add the spirit..." / "...already full"): its
/// read of 0 is not believed for a while, and it is re-identified so the read catches up.
/// </summary>
private void OnServerSaidFull(int deviceId, bool refilled)
{
if (_refillAttempts.TryGetValue(deviceId, out var a) && now - a.WindowStart < RefillLoopWindowMs)
_refillAttempts[deviceId] = (a.Count + 1, a.WindowStart);
if (deviceId == 0) return;
_serverSaidFullUntil[deviceId] = NowMs + ServerSaidFullTrustMs;
if (_host.HasRequestId) _host.RequestId(unchecked((uint)deviceId));
_host.Log(refilled
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)deviceId:X8}, server confirmed)."
: $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} is already full (its charge read was stale); summoning from it.");
}
private bool ServerSaidFull(int deviceId, long now)
{
if (!_serverSaidFullUntil.TryGetValue(deviceId, out long until)) return false;
if (now < until) return true;
_serverSaidFullUntil.Remove(deviceId);
return false;
}
private void CountRefill(int deviceId, long now)
{
if (_refills.TryGetValue(deviceId, out var r) && now - r.Since < RefillWindowMs)
_refills[deviceId] = (r.Count + 1, r.Since);
else
_refillAttempts[deviceId] = (1, now);
_refills[deviceId] = (1, now);
}
/// <summary>
/// True (and the essence parked) when it was already refilled <see cref="RefillLoopMaxAttempts"/>
/// times in the window without becoming usable — the charge read is stale or the refill is
/// failing, and repeating it only burns spirits and forces peace mode.
/// True, and the essence parked, when it was refilled <see cref="RefillsPerWindow"/> times
/// inside <see cref="RefillWindowMs"/> and still reads empty: another refill would only cost
/// a spirit and force peace mode again. An essence holds dozens of summons, so two real
/// refills that close together don't happen.
/// </summary>
private bool RefillLoopDetected(int deviceId, long now)
private bool RefillLooping(int deviceId, long now)
{
if (!_refillAttempts.TryGetValue(deviceId, out var a) || now - a.WindowStart >= RefillLoopWindowMs)
return false;
if (a.Count < RefillLoopMaxAttempts)
if (!_refills.TryGetValue(deviceId, out var r) || now - r.Since >= RefillWindowMs || r.Count < RefillsPerWindow)
return false;
_refills.Remove(deviceId);
_deviceCooldownUntil[deviceId] = now + RefillLoopParkMs;
_refillAttempts.Remove(deviceId);
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} refilled {a.Count}x in {(now - a.WindowStart) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
_host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} was refilled {r.Count}x in {(now - r.Since) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
return true;
}

View file

@ -8,9 +8,11 @@ namespace RynthCore.Plugin.RynthAi;
public static class SpellDatabase
{
private static readonly Dictionary<int, string> _spellNames = new();
// Family + difficulty (power) per spell id, from SpellData.txt columns 3 and 7.
// Used by the Mag-style item info spell filter (cantrip / aura tiers).
private static readonly Dictionary<int, (int Family, int Difficulty)> _spellMeta = new();
// The data's category (ACE SpellCategory, column 3) and power (difficulty, column 7) per id,
// and the ids of each category. Read for wall spells (2026-10-08): they have no tier in their
// names ("Slithering Flames"), so a wall is found by its category and ranked by its power.
private static readonly Dictionary<int, (int Category, int Power)> _spellMeta = new();
private static readonly Dictionary<int, List<int>> _idsByCategory = new();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
@ -42,6 +44,7 @@ public static class SpellDatabase
{
_spellNames.Clear();
_spellMeta.Clear();
_idsByCategory.Clear();
_loaded = false;
try
@ -65,10 +68,14 @@ public static class SpellDatabase
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
{
_spellNames[spellId] = columns[1].Trim();
if (columns.Length >= 7
&& int.TryParse(columns[2].Trim(), out int family)
&& int.TryParse(columns[6].Trim(), out int difficulty))
_spellMeta[spellId] = (family, difficulty);
if (columns.Length >= 7 && int.TryParse(columns[2].Trim(), out int category)
&& int.TryParse(columns[6].Trim(), out int power))
{
_spellMeta[spellId] = (category, power);
if (!_idsByCategory.TryGetValue(category, out List<int>? ids))
_idsByCategory[category] = ids = new List<int>();
ids.Add(spellId);
}
}
}
@ -87,20 +94,6 @@ public static class SpellDatabase
return $"Unknown Spell ({spellId})";
}
/// <summary>Spell family and difficulty (power). False when the spell isn't in SpellData.txt.</summary>
public static bool TryGetSpellMeta(int spellId, out int family, out int difficulty)
{
if (_spellMeta.TryGetValue(spellId, out var meta))
{
family = meta.Family;
difficulty = meta.Difficulty;
return true;
}
family = 0;
difficulty = 0;
return false;
}
/// <summary>True when the spell id is in the embedded table or the built-in recall list.</summary>
public static bool HasSpell(int spellId) =>
_spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
@ -121,6 +114,30 @@ public static class SpellDatabase
return _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
}
/// <summary>The spell's category (ACE SpellCategory) and power from the data; false when the
/// spell isn't in it.</summary>
public static bool TryGetCategoryAndPower(int spellId, out int category, out int power)
{
if (_spellMeta.TryGetValue(spellId, out var m)) { category = m.Category; power = m.Power; return true; }
category = 0; power = 0;
return false;
}
/// <summary>Every spell id of a category (ACE SpellCategory), in data order.</summary>
public static IReadOnlyList<int> IdsInCategory(int category)
=> _idsByCategory.TryGetValue(category, out List<int>? ids) ? ids : Array.Empty<int>();
/// <summary>
/// A spell's level by ACE's server formula (Spell.Level): the highest level whose minimum power
/// it reaches, 1/50/100/150/200/250/300/400 for levels 1-8 (SpellFormula.MinPower). The tiered
/// war lines have exactly those powers (Flame Bolt V 200, the tier-7 lore 300, Incantations
/// 400; blasts +25), so it is the same tier limit the other shapes use. 0 = no power.
/// </summary>
public static int LevelFromPower(int power) => power switch
{
>= 400 => 8, >= 300 => 7, >= 250 => 6, >= 200 => 5, >= 150 => 4, >= 100 => 3, >= 50 => 2, >= 1 => 1, _ => 0,
};
/// <summary>Builds a name→id reverse map for SpellManager initialisation.</summary>
public static Dictionary<string, int> BuildNameToIdMap()
{

View file

@ -174,7 +174,29 @@ public class SpellManager
_ => "I"
};
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill)
/// <summary>
/// The LOWEST known tier of <paramref name="baseSpellName"/> above the buff tier the skill
/// allows, 0 when none. For heals when nothing at or under the allowed tier is known: vitae
/// can drop Life Magic under a tier line while the character only knows higher tiers, and a
/// heal that may fizzle beats none (Drakkon died twice, 2026-10-06).
/// </summary>
public int GetSelfSpellIdAboveAllowedTier(string baseSpellName, AcSkillType magicSkill)
{
RefreshKnownSpells();
int maxTier = GetHighestBuffSpellTier(magicSkill);
string cleanBase = baseSpellName.Replace(" Self", "").Trim();
BaseNameAliases.TryGetValue(cleanBase, out string? alias);
for (int tier = maxTier + 1; tier <= 8; tier++)
{
if (TryGetTierId(cleanBase, tier, out int id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
}
return 0;
}
/// <param name="skip">Levels to pass over (a level the server refused for missing components):
/// the next lower known level is returned instead.</param>
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill, Func<int, bool>? skip = null)
{
RefreshKnownSpells(); // keep the authoritative inventory current (throttled)
@ -187,8 +209,8 @@ public class SpellManager
for (int tier = maxTier; tier >= 1; tier--)
{
if (TryGetTierId(cleanBase, tier, out int id)) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
if (TryGetTierId(cleanBase, tier, out int id) && (skip == null || !skip(id))) return id;
if (alias != null && TryGetTierId(alias, tier, out int idAlias) && (skip == null || !skip(idAlias))) return idAlias;
}
return 0;
}

View file

@ -15,8 +15,8 @@ namespace RynthCore.Plugin.RynthAi;
/// they didn't know about each other, so cross-subsystem swaps still raced.
///
/// This gate is a single shared instance both managers consult: a swap is only
/// allowed if no other swap has been issued within MinIntervalMs. The loser
/// yields and retries on a later tick. Spell casts and non-weapon item actions
/// allowed once the last one is done on the server (or MinIntervalMs has passed).
/// The loser yields and retries on a later tick. Spell casts and non-weapon item actions
/// (loot moves, corpse opens) do NOT go through here.
/// </summary>
public sealed class WeaponSwapGate
@ -24,37 +24,84 @@ public sealed class WeaponSwapGate
private readonly object _lock = new();
private long _lastSwapTickMs = long.MinValue / 4;
private string _lastSwapBy = "";
private int _movingId;
private long _claims;
/// <summary>Swaps claimed so far: a caller can tell whether another swap went out after its own.</summary>
public long Claims { get { lock (_lock) { return _claims; } } }
/// <summary>
/// Minimum milliseconds between two weapon swaps. ~3s comfortably covers
/// AC's equip + stance-change settle (matches the existing 3000ms cast
/// equip-gate in CombatManager) so a swap fully resolves before the next.
/// The longest one swap holds the next: a swap the server's answer can't be seen for (or
/// with no <see cref="ServerIdle"/>) waits this long, as before 2026-10-06.
/// </summary>
public int MinIntervalMs { get; set; } = 3000;
/// <summary>
/// Atomically claim the swap slot. Returns true (recording the swap) when
/// no swap has occurred within MinIntervalMs; false when the caller must
/// wait. Only mutates state when it returns true, so a denied caller never
/// Swap speed (2026-10-06): the next swap may go once the last one is done on the server,
/// after at least this long. A weapon change takes up to three steps (a shield or arrows
/// into the pack, the weapon, the off hand); at a flat 3 s per step it took 6-9 s.
/// </summary>
public int FloorMs { get; set; } = 400;
/// <summary>True when no use or cast is waiting for the server's answer (ActionPacer).</summary>
public Func<bool>? ServerIdle { get; set; }
/// <summary>Reads whether the character wields an item (for a noted move, <see cref="NoteMove"/>).</summary>
public Func<int, bool>? IsWielded { get; set; }
public Func<long> NowMs { get; set; } = () => Environment.TickCount64;
/// <summary>
/// Atomically claim the swap slot. Returns true (recording the swap) when the last swap is
/// done on the server (see <see cref="FloorMs"/>) or MinIntervalMs has passed; false when
/// the caller must wait. Only mutates state when it returns true, so a denied caller never
/// "wastes" the slot.
/// </summary>
public bool TryBeginSwap(string requestedBy)
{
long now = Environment.TickCount64;
long now = NowMs();
lock (_lock)
{
if (now - _lastSwapTickMs < MinIntervalMs)
long since = now - _lastSwapTickMs;
if (since < MinIntervalMs && !LastSwapDone(since))
return false;
_lastSwapTickMs = now;
_lastSwapBy = requestedBy ?? "";
_movingId = 0;
_claims++;
return true;
}
}
/// <summary>
/// The claimed swap moved <paramref name="itemId"/> into or out of a hand without a use (a
/// pack move or a slot wield): the next swap waits the full MinIntervalMs, as before.
/// Drakkon 2026-10-06 13:58: the wand went out 1.3 s after the axe's pack move (the axe read
/// out of hand) and the server then held the first cast open until a relog. The server's
/// unwield motion outlasts the item move, and nothing tells us when it ends.
/// </summary>
public void NoteMove(int itemId, bool wieldedNow)
{
lock (_lock) _movingId = itemId;
}
private bool LastSwapDone(long since)
{
if (since < FloorMs || ServerIdle == null || IsWielded == null) return false;
try
{
return _movingId == 0 && ServerIdle();
}
catch
{
return false;
}
}
/// <summary>Milliseconds since the last successful swap (diagnostics).</summary>
public long MsSinceLastSwap
{
get { lock (_lock) { return Environment.TickCount64 - _lastSwapTickMs; } }
get { lock (_lock) { return NowMs() - _lastSwapTickMs; } }
}
/// <summary>Who last claimed a swap (diagnostics).</summary>

View file

@ -43,6 +43,12 @@ public class WorldObjectCache
private readonly HashSet<int> _landscape = new(); // has physics position
private readonly HashSet<int> _inventory = new(); // no physics position
private readonly Dictionary<int, float> _healthRatios = new(); // last known health ratio per object (0-1)
// Ids whose ratio is an estimate from our own damage lines (a ring, wall or chain spell's other
// targets: the server sends health only for the selected target). A real health update replaces
// the estimate and takes the id out of this set.
private readonly HashSet<int> _estimatedHealth = new();
/// <summary>The lowest an estimate goes: 0 means dead to every reader, and only the server says that.</summary>
internal const float EstimatedHealthFloor = 0.01f;
// OnCreateObject IDs pending classification
private readonly Queue<uint> _pending = new();
@ -199,6 +205,7 @@ public class WorldObjectCache
_creatures.Remove(sid);
_landscape.Remove(sid);
_healthRatios.Remove(sid);
_estimatedHealth.Remove(sid);
_classifyRetry.Remove(id);
_slowRetry.Remove(id);
_reclassifySkipState.Remove(id);
@ -234,6 +241,37 @@ public class WorldObjectCache
return _healthRatios.TryGetValue(id, out float v) ? v : -1f;
}
/// <summary>
/// Lowers a creature's health by our own hit when the server sends it no health of its own: the
/// other targets of a ring, wall or chain spell (ACE pushes health only for the selected target).
/// <paramref name="fraction"/> is damage / max health, or 0 when the max is unknown, which only
/// marks the creature as hurt (0.99). Never goes to 0 (dead is the server's call: the kill
/// notice, a health update or the corpse) and never raises a known value. A real health update
/// overwrites the estimate.
/// </summary>
public void ApplyDamageEstimate(int id, double fraction)
{
lock (_gate)
{
if (_playerId != 0 && unchecked((uint)id) == _playerId) return;
float cur = _healthRatios.TryGetValue(id, out float v) ? v : 1f;
if (cur <= 0f) return;
float next = fraction > 0
? (float)Math.Max(EstimatedHealthFloor, cur - fraction)
: Math.Min(cur, 0.99f);
if (next >= cur && _healthRatios.ContainsKey(id)) return;
_healthRatios[id] = next;
_estimatedHealth.Add(id);
}
}
/// <summary>True when <paramref name="id"/>'s health ratio is our estimate rather than the server's.</summary>
public bool IsHealthEstimated(int id)
{
lock (_gate)
return _estimatedHealth.Contains(id);
}
public void OnUpdateHealth(uint id, float healthRatio)
{
lock (_gate)
@ -243,6 +281,7 @@ public class WorldObjectCache
int sid = (int)id;
_healthRatios[sid] = Math.Clamp(healthRatio, 0f, 1f);
_estimatedHealth.Remove(sid); // the server's number replaces any estimate
if (!_creatures.Add(sid))
return; // creature already known — ratio updated above, nothing more to do
@ -601,13 +640,16 @@ public class WorldObjectCache
return;
}
// Non-creature with a known type: classify it by its ItemType flags and place it
// by ownership. Only weapons/armor/casters/containers were accepted here before,
// so keys, gems, spell components, food and misc fell through to Unknown
// landscape (never inventory) and ReclassifyUnknownDynamics re-probed them
// every 2 s forever.
// Non-creature with a position and a known item type: equipped gear, a ground
// drop, a chest. It gets the class its type gives and is filed by who has it
// (FileTypedObject). Only weapons, armor, casters and containers were taken
// here before, all into the inventory: keys, gems, comps, food and the like
// stayed Unknown landscape and were re-probed every 2 s for good, and other
// players' wielded gear and ground-dropped weapons counted as ours
// (2026-10-05). A static object that isn't a chest or a lifestone returns
// false and stays Unknown scenery below, hazard check included.
AcObjectClass typedCls = ClassifyItem(uid, typeFlags);
if (typedCls != AcObjectClass.Unknown && PlaceTypedObject(uid, id, name, typedCls, typeFlags))
if (typedCls != AcObjectClass.Unknown && FileTypedObject(uid, id, name, typedCls, typeFlags))
return;
}
else if (uid >= 0x80000000u)
@ -657,83 +699,77 @@ public class WorldObjectCache
}
}
/// <summary>
/// Places a positioned, non-creature object whose ItemType resolved to a real class.
/// Must be called under <see cref="_gate"/>.
/// <list type="bullet">
/// <item>Portals / lifestones → landscape with their real class.</item>
/// <item>Dynamic objects owned by the player (wielded, in the main pack, or in a side pack) → inventory.</item>
/// <item>Other dynamic objects (ground drops, corpse / chest contents) → landscape with the item class.</item>
/// <item>Ownership unreadable → gear-like types go to inventory, the rest to landscape.</item>
/// <item>Static non-fixture, non-container objects (doors, signs) → returns false; the caller keeps them Unknown scenery.</item>
/// </list>
/// Returns true when the object was placed and recorded in <see cref="_byId"/>.
/// </summary>
private bool PlaceTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
{
bool isFixture = cls is AcObjectClass.Portal or AcObjectClass.Lifestone;
bool isDynamic = uid >= 0x80000000u;
private const uint ItemTypeGear = ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer;
bool toInventory;
if (isFixture)
private enum Holder { Unknown, Player, OtherWielder, OtherContainer, Nobody }
/// <summary>
/// Who has the object: the player (wielded, in the main pack, or in a side pack), another
/// wielder (other players' and NPCs' gear), another container (a corpse, a chest), or
/// nobody (it lies on the ground). Unknown when the player isn't known yet or the engine
/// can't read the object's ownership. Caller holds _gate.
/// </summary>
private Holder WhoHas(int id)
{
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
return Holder.Unknown;
uint container = unchecked((uint)containerId), wielder = unchecked((uint)wielderId);
if (wielder == _playerId || container == _playerId) return Holder.Player;
if (wielder != 0) return Holder.OtherWielder;
if (container == 0) return Holder.Nobody;
// Side packs sit in the main pack (AC has no deeper nesting).
return TryGetOwnership(containerId, out int outer, out _, out _) && unchecked((uint)outer) == _playerId
? Holder.Player : Holder.OtherContainer;
}
/// <summary>
/// Files a positioned non-creature whose item type gave it a real class. Caller holds _gate.
/// <list type="bullet">
/// <item>A lifestone: landscape.</item>
/// <item>Another static object: a chest goes on the landscape; anything else returns false
/// and the caller keeps it Unknown scenery (doors, signs, static hotspots).</item>
/// <item>A dynamic object the player has: inventory. One another player or an NPC wields:
/// neither list (known by id only), so it is not ours, not a ground item on the radar and
/// not something a meta can pick up. In another container or loose on the ground: landscape.</item>
/// <item>Ownership unreadable: gear goes to the inventory as before, the rest to the landscape.</item>
/// </list>
/// A non-gear object that lands on the landscape gets the hazard check it had as Unknown
/// (a hotspot spawned with a dynamic id and a Misc type is still a hazard).
/// </summary>
private bool FileTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
{
bool gear = (typeFlags & ItemTypeGear) != 0;
bool toInventory, toLandscape;
if (cls == AcObjectClass.Lifestone)
{
toInventory = false;
toLandscape = true;
}
else if (!isDynamic)
else if (uid < 0x80000000u)
{
// Chests are static containers; other static objects stay Unknown scenery.
if ((typeFlags & ItemTypeContainer) == 0)
return false;
if ((typeFlags & ItemTypeContainer) == 0) return false;
toInventory = false;
toLandscape = true;
}
else
{
bool owned = IsOwnedByPlayer(id, out bool ownershipKnown);
toInventory = ownershipKnown
? owned
: (typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0;
Holder holder = WhoHas(id);
toInventory = holder == Holder.Player || (holder == Holder.Unknown && gear);
toLandscape = !toInventory && holder != Holder.OtherWielder;
}
_classifyRetry.Remove(uid);
_reclassifySkipState.Remove(uid);
if (toInventory)
{
if (_inventory.Add(id)) _inventoryDirty = true;
_landscape.Remove(id);
}
else
{
if (_inventory.Remove(id)) _inventoryDirty = true;
_landscape.Add(id);
}
if (toInventory) { if (_inventory.Add(id)) _inventoryDirty = true; }
else if (_inventory.Remove(id)) _inventoryDirty = true;
if (toLandscape) _landscape.Add(id);
else _landscape.Remove(id);
_byId[id] = Make(id, name, cls);
TraceClassify(uid, name.Length > 0, true, true, typeFlags, toInventory ? $"typed->{cls}(inv)" : $"typed->{cls}(land)");
if (toLandscape && !gear)
MaybeRegisterHazard(uid, name);
return true;
}
/// <summary>
/// True when the object is wielded by the player, sits in the player's main pack, or sits in
/// a side pack whose container is the player. <paramref name="known"/> is false when the
/// player id isn't set yet or the ownership read failed.
/// </summary>
private bool IsOwnedByPlayer(int id, out bool known)
{
known = false;
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
return false;
known = true;
uint container = unchecked((uint)containerId);
uint wielder = unchecked((uint)wielderId);
if (wielder == _playerId || container == _playerId)
return true;
// One level of nesting covers side packs (AC doesn't allow packs inside packs).
return container != 0
&& TryGetOwnership(containerId, out int outer, out _, out _)
&& unchecked((uint)outer) == _playerId;
}
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
private const uint BfCorpse = 0x2000;
@ -799,7 +835,7 @@ public class WorldObjectCache
List<int>? toPromote = null;
List<int>? toCorpse = null;
List<(int id, string name, AcObjectClass cls)>? statics = null;
List<(int Id, uint Flags)>? toType = null; // Unknowns whose ItemType is now a real item class
List<(int Id, uint Flags)>? typed = null; // Unknowns whose item type now gives a class
foreach (int id in _landscape)
{
uint uid = unchecked((uint)id);
@ -829,7 +865,11 @@ public class WorldObjectCache
// Bounded to Monster/Unknown so we don't name-query every ground
// item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X")
// so a live mob cannot be misread as a corpse.
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown)
// Container too: a corpse typed before its name or flag was readable is filed as a
// landscape Container by FileTypedObject (it used to go to the inventory, which the
// inventory pass below re-checks).
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown
|| wo.ObjectClass == AcObjectClass.Container)
&& ((_host.TryGetObjectName(uid, out string maybeCorpse) && IsCorpseName(maybeCorpse))
|| HasCorpseFlag(uid)))
{
@ -854,11 +894,11 @@ public class WorldObjectCache
isCreature = true;
if (!isCreature)
{
// Type known now (or arrived late): place it as a real item instead of
// re-probing it every pass. Applied after the loop: placing mutates _landscape.
// Its type arrived after it was classified: file it as the item it is instead
// of probing it again every pass. Done after the loop (filing edits _landscape).
if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown)
{
(toType ??= new()).Add((id, typeFlags));
(typed ??= new()).Add((id, typeFlags));
continue;
}
DiagLogReclassifySkip(uid, wo.Name);
@ -914,27 +954,27 @@ public class WorldObjectCache
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse");
}
if (toType != null)
if (typed != null)
{
int placed = 0, toInv = 0;
foreach (var (id, flags) in toType)
int filed = 0, intoInventory = 0;
foreach (var (id, flags) in typed)
{
if (!_byId.TryGetValue(id, out var wo)) continue;
uint uid = unchecked((uint)id);
// An Unknown result would be re-queued every pass, so leave it to the skip diag.
AcObjectClass cls = ClassifyItem(uid, flags);
if (cls == AcObjectClass.Unknown || !PlaceTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
placed++;
if (_inventory.Contains(id)) toInv++;
if (cls == AcObjectClass.Unknown || !FileTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
filed++;
if (_inventory.Contains(id)) intoInventory++;
}
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {placed} Unknown object(s) as items ({toInv} into inventory)");
if (filed > 0)
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {filed} Unknown object(s) as items ({intoInventory} into the inventory)");
}
// DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted
// this pass. Confirms ReclassifyUnknownDynamics is running and engine signals
// keep failing for the stuck uids (vs. them never reaching _landscape at all).
if (toPromote == null
&& toType == null
&& typed == null
&& _reclassifySkipState.Count > 0
&& _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries)
{
@ -1096,10 +1136,64 @@ public class WorldObjectCache
uint uid = unchecked((uint)id);
if (stype == DecalTypeKey)
return _host.HasGetObjectWcid && _host.TryGetObjectWcid(uid, out uint wcid) ? unchecked((int)wcid) : defaultValue;
if ((stype & 0xFFFFFF00u) == DecalTypeKey)
return GetDecalLongKey(uid, stype, defaultValue);
if (!_host.HasGetObjectIntProperty) return defaultValue;
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
}
/// <summary>
/// Decal's other synthetic LongValueKeys (0x0D000001-0x0D00002A, Decal.Adapter's numbering),
/// read as the game property each one is. VTank profiles use them: LootSnobV4 has 336 rules on
/// MaxDamage and 109 on Coverage. They were read as STypeInt ids, which no object has, so
/// they were always 0 and those rules never matched (until 2026-10-07). Icons are the
/// portal.dat index without its 0x06000000 base, as Decal gives them. Keys with no property
/// here (landblock, monarch, physics flags, spell counts) answer the default.
/// </summary>
private int GetDecalLongKey(uint uid, uint key, int defaultValue)
{
switch (key)
{
case 0x0D000001: return DecalIcon(uid, 8, defaultValue); // Icon
case 0x0D000008: { uint s = GetDataIdProperty(unchecked((int)uid), 28); return s != 0 ? unchecked((int)s) : defaultValue; } // AssociatedSpell
case 0x0D000029: return DecalIcon(uid, 50, defaultValue); // IconOverlay
case 0x0D00002A: return DecalIcon(uid, 52, defaultValue); // IconUnderlay
}
uint stype = DecalIntStype(key);
if (stype == 0 || !_host.HasGetObjectIntProperty) return defaultValue;
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
}
/// <summary>The STypeInt a Decal synthetic long key is, or 0 (not an int property).</summary>
public static uint DecalIntStype(uint key) => key switch
{
0x0D000004 => 6, // ItemSlots -> ItemsCapacity
0x0D000005 => 7, // PackSlots -> ContainersCapacity
0x0D000006 => 12, // StackCount -> StackSize
0x0D000007 => 11, // StackMax -> MaxStackSize
0x0D00000B => 10, // WieldingSlot -> CurrentWieldedLocation
0x0D00000D => 4, // Coverage -> ClothingPriority
0x0D00000E => 9, // EquipableSlots -> ValidLocations
0x0D00000F => 51, // EquipType -> CombatUse
0x0D000010 => 18, // IconOutline -> UiEffects
0x0D000011 => 50, // MissileType -> AmmoType
0x0D000012 => 16, // UsageMask -> ItemUseable
0x0D000014 => 152, // HookMask -> HookItemType
0x0D000015 => 151, // HookType
0x0D00001A => 1, // Category -> ItemType
0x0D00001F => 49, // WeapSpeed -> WeaponTime
0x0D000020 => 48, // EquipSkill -> WeaponSkill
0x0D000021 => 45, // DamageType
0x0D000022 => 44, // MaxDamage -> Damage (the appraisal's weapon profile)
_ => 0,
};
private int DecalIcon(uint uid, uint did, int defaultValue)
{
uint v = GetDataIdProperty(unchecked((int)uid), did);
return v != 0 ? unchecked((int)(v & 0x00FFFFFFu)) : defaultValue;
}
/// <summary>
/// Read an STypeDID property (e.g. a scroll's Spell 28 from its CreateObject header).
/// 0 if the API is unavailable or the property is not set.
@ -1753,6 +1847,24 @@ public class WorldObjectCache
get { lock (_gate) return _hazardVersion; }
}
/// <summary>
/// A dungeon cell the character took hotspot damage in ("You suffer 32 damage from acid!"):
/// registered and persisted like a sighted hazard, so the patrol reroutes around it now and
/// on every later visit. Outdoor cells (a 24 m land cell) are never registered. True when new.
/// </summary>
public bool RegisterDamageHazardCell(uint cellId, string source)
{
if (cellId == 0 || (cellId & 0xFFFF) < 0x0100) return false;
lock (_gate)
{
if (!_hazardCells.Add(cellId)) return false;
_hazardVersion++;
}
DungeonHazardStore.Append(cellId >> 16, cellId);
_host.Log($"[Hazard] took {source} damage in cell 0x{cellId:X8} (persisted)");
return true;
}
public bool IsHazardCell(uint cellId)
{
lock (_gate)

View file

@ -97,6 +97,10 @@ public sealed partial class RynthAiPlugin
private bool _currentLootItemMovePending;
private bool _corpseAutorunActive;
private int _currentLootItemMoveAttempts;
private long _currentLootItemStillSince;
private long _currentLootItemLeftAt;
private bool _currentLootItemSawAnim;
private long _pickupAnimSince;
private string _currentLootItemActionLabel = string.Empty;
private string _currentLootItemName = string.Empty;
private bool _currentLootItemIsSalvage;
@ -104,7 +108,9 @@ public sealed partial class RynthAiPlugin
private long _corpseIdsRequestedAt;
private bool _corpseApproachTurnsActive;
private static long CorpseNowMs => Environment.TickCount64;
/// <summary>The loot clock (ms); the host tests replace it to run minutes of looting at once.</summary>
internal static Func<long> CorpseClock = static () => Environment.TickCount64;
private static long CorpseNowMs => CorpseClock();
private void LootDiag(string message)
{
Log(message);
@ -142,8 +148,49 @@ public sealed partial class RynthAiPlugin
// busy-zero churn) paced the whole loot grind, and the 2026-06-12 09:33
// storm of them latched the variant-2 stance/item deadlock.
private const long BUSY_TIMEOUT_COMBAT_URGENT_MS = 5_000;
// The engine's count is the one owner (2026-10-06; analysis by Silentkelpie, re-implemented
// here): this mirror is fed by the engine's busy events, and the engine now sends one for
// every UseDone and every reset it does, so the two agree except for events still on their
// way. A disagreement that lasts BusyMirrorFollowMs is settled the engine's way; the old
// 5/10 s mirror reset below is only for an engine without GetBusyState.
private const long BusyMirrorFollowMs = 1_500;
private long _busyMismatchSince;
private long _lastBusyFollowLogAt;
private int _busyFollowsSinceLog;
private bool FollowEngineBusyCount()
{
if (!Host.HasGetBusyState) return false;
int engine;
try { engine = Host.GetBusyState(); } catch { return false; }
long now = CorpseNowMs;
if (engine == _busyCount) { _busyMismatchSince = 0; return true; }
if (_busyMismatchSince == 0) { _busyMismatchSince = now; return true; }
if (now - _busyMismatchSince < BusyMirrorFollowMs) return true;
int was = _busyCount;
_busyMismatchSince = 0;
_busyCount = Math.Max(0, engine);
_busyCountLastIncrementAt = 0;
_busyCountBecamePositiveAt = _busyCount > 0 ? now : 0;
if (_combatManager != null) _combatManager.BusyCount = _busyCount;
if (_buffManager != null) _buffManager.BusyCount = _busyCount;
_busyFollowsSinceLog++;
if (now - _lastBusyFollowLogAt >= 10_000)
{
Log($"[RynthAi] Busy mirror {was} -> {_busyCount}: following the engine's count ({_busyFollowsSinceLog} in the last {(now - _lastBusyFollowLogAt) / 1000.0:0} s; the client's count is never cleared by RynthAi).");
_lastBusyFollowLogAt = now;
_busyFollowsSinceLog = 0;
}
return true;
}
private void CheckBusyTimeout()
{
if (FollowEngineBusyCount())
{
PruneCorpseCollections();
return;
}
if (_busyCount > 0 && _busyCountBecamePositiveAt != 0)
{
long elapsed = CorpseNowMs - _busyCountBecamePositiveAt;
@ -176,10 +223,17 @@ public sealed partial class RynthAiPlugin
if (elapsed > threshold)
{
Log($"[RynthAi] Busy count stuck at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}) — force-clearing.");
// Reset pending loot item BEFORE zeroing AC's m_cBusy. If we have an
// in-flight UseObject, ForceResetBusyCount zeros m_cBusy under it; the
// retry in TickPendingCorpsePickup would then hit a freed AC object and crash.
// Our mirror only (2026-10-06). AC's m_cBusy is +1 per action the client sends and
// -1 per server UseDone (ClientUISystem::Handle_Item::UseDone, inline - which is why
// this mirror, fed by the Increment/Decrement hooks, never saw the decrement and
// looked "stuck"). Force-clearing AC's count here zeroed the count of actions the
// server had not answered yet (each later UseDone then drove it negative: ~190
// repairs an hour in the 10-05/10-06 logs) and let the next action out on top of
// them. The pacing waits on the server's answers now (ActionPacer); the client's
// own count is left to the client and the engine.
bool serverWaiting = RynthCore.Plugin.Shared.ActionPacer.Current(Host) != null;
Log($"[RynthAi] Busy mirror at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}" +
$"{(serverWaiting ? ", a server action is still unanswered" : "")}) — resetting the mirror only (the client's count is left alone).");
ResetCurrentLootItem();
_corpseIdsRequested = false;
_lastLootActionAt = CorpseNowMs;
@ -188,7 +242,6 @@ public sealed partial class RynthAiPlugin
_busyCountBecamePositiveAt = 0;
if (_combatManager != null) _combatManager.BusyCount = 0;
if (_buffManager != null) _buffManager.BusyCount = 0;
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
}
}
@ -350,6 +403,13 @@ public sealed partial class RynthAiPlugin
}
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
_lootWedgeAnnounced = false;
if (_useCheckJumpAt != 0)
{
Log($"[RynthAi] Use check: 0x{objectId:X8} opened {CorpseNowMs - _useCheckJumpAt} ms after the use check's jump - the jump cleared the server's stuck turn.");
_useCheckJumpAt = 0;
}
ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs);
if (switchedTarget)
LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}.");
@ -476,7 +536,12 @@ public sealed partial class RynthAiPlugin
// timeouts). Stop firing opens into a dead client until the halt window
// elapses — hammering it can't recover a server-side lock, only a relog
// can. Navigation/combat (non-item-action) still run elsewhere.
if (CorpseNowMs < _lootHaltUntil)
// The use-refusal watch first: it reads the server's answers to our opens, and while it
// has decided the server refuses every use (Stuck) no corpse is claimed or opened until
// its back-off ends.
long haltNow = CorpseNowMs;
TickUseRefusalWatch(haltNow);
if (haltNow < _lootHaltUntil || _useRefusals.HoldsOpens(haltNow))
return;
// ── Buffing: halt loot work but retain target so looting resumes immediately ──
@ -622,6 +687,29 @@ public sealed partial class RynthAiPlugin
return;
}
// An open goes out only once the arbiter has given Looting the tick. A corpse claimed on
// the tick a fight ended (Combat still owned it) used to be opened at once, and the
// arbiter's nav stop (StopCompletely) and Combat's idle peace-mode swap followed 3-30 ms
// later. On ACE both cancel the server's walk/turn to the corpse - a mode change runs
// HandleActionCancelAttack -> cancel_moveto - so that open could only fail (2026-10-06
// 06:18:44, the first failed open of the day's stall). One tick later the stop goes
// out first (PauseNavigationForCorpse) and the open after it.
if (_activity != BotActivity.Looting)
return;
// One server action at a time (2026-10-06, ActionPacer): no open while the server is still
// answering another action - a kit, a cast, a stance change, or the last open itself (a
// re-sent open restarts the server's walk and fails the first one's callback). The claim's
// 12 s timeout keeps running (the longest wait here is the 5 s limit on an open).
if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out _))
return;
// The last corpse's close is not answered yet (CloseGroundContainer, ~40 ms): a use now makes
// the client send its own NoLongerViewingContents for that corpse too (flight recorder
// 2026-10-06 07:57:09.801: the engine's close, then the client's, beside the next use).
if (_closeSentFor != 0 && _closeSentFor != _targetCorpseId && now - _closeSentAt < CloseAnswerWaitMs
&& Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == _closeSentFor)
return;
// Farther than reach: just use the corpse. The server walks the character to it and turns
// it (as a player's double-click does); steering there ourselves looked awkward and
// turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that
@ -634,8 +722,8 @@ public sealed partial class RynthAiPlugin
if (_lastCorpseOpenAttemptAt == 0 || now - _lastCorpseOpenAttemptAt >= walkMs)
{
if (_busyCount > 0 && now - _lastCorpseOpenAttemptAt < OpenBusyWaitMaxMs) return;
AttemptOpenCorpse(_targetCorpseId);
_lastCorpseOpenAttemptAt = now;
if (AttemptOpenCorpse(_targetCorpseId))
_lastCorpseOpenAttemptAt = now;
}
return;
}
@ -660,8 +748,8 @@ public sealed partial class RynthAiPlugin
return; // busy — hold the open briefly
}
_corpseOpenBusyWaitSince = 0;
AttemptOpenCorpse(_targetCorpseId);
_lastCorpseOpenAttemptAt = now;
if (AttemptOpenCorpse(_targetCorpseId))
_lastCorpseOpenAttemptAt = now;
}
}
@ -1208,7 +1296,9 @@ public sealed partial class RynthAiPlugin
pendingDataCount++;
continue;
}
// Still nameless well past the window — skip this item.
// Still nameless well past the window — skip this item (and say so: it used to
// leave nothing in the log, so a missed item couldn't be traced).
LootDiag($"[LootEval] 0x{(uint)item.Id:X8} on 0x{(uint)corpseId:X8} still has no name after the wait (value={item.Values(19, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)}) -> left");
_processedCorpseItems.Add(item.Id);
continue;
}
@ -1248,7 +1338,7 @@ public sealed partial class RynthAiPlugin
// once the assess window expires, so an unappraised item can match a
// rule it should not. If keeps correlate with appraised=False, that
// is the cause.
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
LootDiag($"[LootEval] '{item.Name}' cls={item.ObjectClass} id=0x{(uint)item.Id:X8} value={item.Values(19, 0)} stack={item.Values(12, 0)} type=0x{item.Values(1, 0):X} wcid={item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0)} appraised={hasAppraisalData} timedOut={assessTimedOut} -> " +
(classified ? $"KEEP [{actionLabel}] rule='{ruleLabel}'" : "leave"));
if (classified)
@ -1306,8 +1396,14 @@ public sealed partial class RynthAiPlugin
return;
}
// The last pickup's bend-down still plays: the engine holds a move sent now until
// it ends, so wait and send it then.
if (PickupAnimating(CorpseNowMs))
return;
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
_currentLootItemId = firstMatchId;
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId));
Host.SelectItem(unchecked((uint)firstMatchId));
LootDiag($"[RynthAi] Corpse loot: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}.");
@ -1377,6 +1473,42 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>Longest a pickup waits on the motion queue (the engine's own hold is 2.5 s).</summary>
internal const long PickupAnimMaxMs = 3000;
/// <summary>After the item leaves the corpse: how long to wait for its bend-down to start.</summary>
internal const long PickupSettleMs = 1000;
/// <summary>Off the corpse but not seen in the inventory: counted after this anyway.</summary>
internal const long PickupArriveMaxMs = 4000;
/// <summary>The container is the character or a pack it carries.</summary>
private bool InPlayerInventory(int containerId)
{
if (containerId == 0 || _playerId == 0 || _objectCache == null) return false;
int player = unchecked((int)_playerId);
return containerId == player || _objectCache.GetContainerId(containerId) == player;
}
/// <summary>
/// The character still has motions queued (the engine's cast gate, GetCastBusyState):
/// the bend-down of the last pickup is playing. False after PickupAnimMaxMs of it, so a
/// stuck queue can't stop looting, and on an engine without the gate.
/// </summary>
private bool PickupAnimating(long now)
{
bool busy;
try { busy = Host.HasGetCastBusyState && Host.GetCastBusyState() != 0; } catch { busy = false; }
if (!busy)
{
_pickupAnimSince = 0;
return false;
}
if (_pickupAnimSince == 0)
_pickupAnimSince = now;
return now - _pickupAnimSince < PickupAnimMaxMs;
}
private void TickPendingCorpsePickup(LegacyUiSettings settings)
{
if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0)
@ -1390,10 +1522,24 @@ public sealed partial class RynthAiPlugin
int currentContainer = currentItem?.Container ?? 0;
bool stillVisibleOnCorpse = IsCorpseItemVisible(_openedContainerId, _currentLootItemId);
// Check every tick — confirm immediately as soon as the item leaves the corpse.
// Don't gate this on a timer; the timer only applies to the RETRY path below.
// Watch for this pickup's bend-down (the server plays it once the move reaches it).
bool animating = PickupAnimating(now);
if (animating) _currentLootItemSawAnim = true;
// Off the corpse is not done yet: confirming then closed the corpse while the pickup was
// still under way, and the character picked the last item up after the corpse closed
// (2026-10-07). It counts once the item shows up in the inventory (the main pack, a side
// pack, or merged into a stack already there: the picked object is gone) and its
// bend-down has played out. Off the corpse but never seen in the inventory: counted
// after PickupArriveMaxMs anyway, so looting can't stall on it.
if (currentItem == null || !stillVisibleOnCorpse || (currentContainer != 0 && currentContainer != _openedContainerId))
{
if (_currentLootItemLeftAt == 0) _currentLootItemLeftAt = now;
bool inInventory = currentItem == null || InPlayerInventory(currentContainer);
long since = now - _currentLootItemLeftAt;
bool settled = !animating && (_currentLootItemSawAnim || since >= PickupSettleMs);
if (!(inInventory && settled) && since < PickupArriveMaxMs)
return;
ConfirmCurrentLootItemMoved(
now,
currentItem == null
@ -1404,9 +1550,20 @@ public sealed partial class RynthAiPlugin
return;
}
// Item still on corpse — wait before retrying the UseObject.
// Item still on corpse — wait before retrying the UseObject. The window counts from
// when the character is still: while a pickup animation plays the engine holds the
// move, and a retry timed from the send gave up on items whose move had not gone
// out yet (2026-10-07: moves ran ~2.2 s late, 3 tries at 0.5 s skipped the item).
if (PickupAnimating(now))
{
_currentLootItemStillSince = 0;
return;
}
if (_currentLootItemStillSince == 0)
_currentLootItemStillSince = now;
long verifyWindowMs = Math.Max(150, settings.LootRetryTimeoutMs);
if (now - _currentLootItemMoveRequestedAt < verifyWindowMs)
long windowStart = Math.Max(_currentLootItemMoveRequestedAt, _currentLootItemStillSince);
if (now - windowStart < verifyWindowMs)
return;
if (_currentLootItemMoveAttempts >= 3)
@ -1421,6 +1578,7 @@ public sealed partial class RynthAiPlugin
if (_busyCount > 0)
return; // Client is busy — don't queue retry
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId));
Host.SelectItem(unchecked((uint)_currentLootItemId));
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
@ -1555,6 +1713,11 @@ public sealed partial class RynthAiPlugin
if (!settings.IsMacroRunning || !settings.EnableLooting)
return false;
// The server refuses every use (UseRefusalWatch, Stuck): no loot work until the back-off
// ends, so the arbiter lets nav and combat run on instead of standing at the corpses.
if (_openedContainerId == 0 && _useRefusals.HoldsOpens(CorpseNowMs))
return false;
// Already committed to a body, or mid-loot with the container open.
if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive)
{
@ -2002,10 +2165,6 @@ public sealed partial class RynthAiPlugin
if (_manaStoneManager == null) return false;
if (!Host.HasGetObjectIntProperty) return false;
// ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps
// one (and its pending-drain count skips them, so the quota never filled): every
// high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05.
if (ManaStoneManager.IsWandLike(item)) return false;
int threshold = settings.ManaTapMinMana;
if (threshold <= 0) return false;
@ -2220,6 +2379,9 @@ public sealed partial class RynthAiPlugin
_currentLootItemMovePending = false;
_currentLootItemMoveRequestedAt = 0;
_currentLootItemMoveAttempts = 0;
_currentLootItemStillSince = 0;
_currentLootItemLeftAt = 0;
_currentLootItemSawAnim = false;
_currentLootItemActionLabel = string.Empty;
_currentLootItemName = string.Empty;
_currentLootItemIsSalvage = false;
@ -2306,13 +2468,187 @@ public sealed partial class RynthAiPlugin
// or a corpse the bot never reached?).
private int _lastOpenAttemptCorpseId;
private void AttemptOpenCorpse(int corpseId)
/// <summary>Sends one open. False when the use-refusal watch acted instead (nothing sent).</summary>
private bool AttemptOpenCorpse(int corpseId)
{
long now = CorpseNowMs;
bool watch = Host.HasUseDoneSeq;
if (watch)
{
// The previous open, answered with nothing opened, is judged before this one goes out:
// a clean stop or a back-off must not land right after a fresh use (it would cancel it).
var verdict = _useRefusals.SettleBeforeOpen(now);
if (verdict != UseRefusalWatch.Verdict.None)
{
ApplyUseRefusalVerdict(verdict, now);
return false;
}
// The back-off is over and this is the probe: jump first (clears the server's stuck
// animation queue, see UseRefusalWatch), send the probe after the pause.
if (_useRefusals.TakeProbeJump(now) && TryUseCheckJump(now, "before the probe"))
{
_lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
_lastCorpseOpenAttemptAt = 0;
_corpseTargetSince = now;
return false;
}
}
_lastOpenAttemptCorpseId = corpseId;
StopCorpseMovement();
int seqBefore = watch ? Host.GetUseDoneSeq() : 0;
Host.SelectItem(unchecked((uint)corpseId));
Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
if (watch && sent)
_useRefusals.OnOpenSent(corpseId, now, seqBefore);
LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}.");
return true;
}
// ── Server refuses every use (2026-10-06; Loot/UseRefusalWatch.cs) ─────────────────────
private readonly UseRefusalWatch _useRefusals = new();
private bool _useStuckAnnounced;
private bool _lootWedgeAnnounced;
/// <summary>Every tick while looting runs: the server's answers to our opens.</summary>
private void TickUseRefusalWatch(long now)
{
if (!Host.HasUseDoneSeq)
return;
int seq = Host.GetUseDoneSeq();
bool haveErr = Host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq;
ApplyUseRefusalVerdict(_useRefusals.OnTick(now, seq, err, haveErr), now);
}
private void ApplyUseRefusalVerdict(UseRefusalWatch.Verdict verdict, long now)
{
switch (verdict)
{
case UseRefusalWatch.Verdict.CleanStopAndRetry:
{
FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened");
Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a jump, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try.");
Host.SetAutoRunBy("Loot/UseCheck", false);
if (Host.HasStopCompletely)
Host.StopCompletelyBy("Loot/UseCheck");
_corpseAutorunActive = false;
_corpseApproachTurnsActive = false;
// The jump is the fix (see UseRefusalWatch): it empties the server's animation
// queues and cancels the stuck turn; the retry then gets a fresh server turn.
bool jumped = TryUseCheckJump(now, "for the retry");
// Without a jump: face the corpse for the retry. Since 2026-10-04 the bot leaves the
// turn to the server; if the server can't turn the character any more, a corpse already
// in front may still open (mid-stall, 06:28:19, a use by hand with the macro off
// opened one - the only open in those 13 minutes; whether it was faced isn't logged).
if (!jumped && _targetCorpseId != 0 && Host.HasTurnToHeading
&& TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _)
&& faceErr > 2.0)
{
Host.TurnToHeadingBy("Loot/UseCheck", (float)faceDeg);
Log($"[RynthAi] Use check: facing 0x{(uint)_targetCorpseId:X8} ({faceErr:0} deg off) for the retry.");
}
_lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
_lastCorpseOpenAttemptAt = 0; // the retry goes out as soon as the pause ends
if (_targetCorpseId != 0)
_corpseTargetSince = now; // and gets a full corpse timeout
break;
}
case UseRefusalWatch.Verdict.DropCorpse:
{
int id = _useRefusals.LastRefusedCorpse;
Log($"[RynthAi] Use check: corpse 0x{(uint)id:X8} is answered but never opens - giving up on it; the next corpse tells whether every use is refused.");
if (id != 0 && _targetCorpseId == id && _openedContainerId == 0)
AbandonCurrentCorpse(now, "refused");
else if (id != 0)
_corpseCooldownUntil[id] = now + NeverOpenedAbandonRetryMs;
break;
}
case UseRefusalWatch.Verdict.Stuck:
{
FlightRecorderSignal.Dump(Host, "use check: server refuses every use");
Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop{(_useCheckJumpAt != 0 ? ", the jump" : "")} and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again{(Host.HasTapJump ? " after a jump" : "")}.");
_useCheckJumpAt = 0;
if (!_useStuckAnnounced)
{
_useStuckAnnounced = true;
ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every few minutes.");
}
ResetCorpseTarget();
break;
}
case UseRefusalWatch.Verdict.StillStuck:
Log($"[RynthAi] Use check: still refused{(_useCheckJumpAt != 0 ? " after the jump" : "")} - next try in {_useRefusals.BackoffMs / 60_000} min.");
_useCheckJumpAt = 0;
ResetCorpseTarget();
break;
case UseRefusalWatch.Verdict.Recovered:
Log("[RynthAi] Use check: a corpse opened - uses work again, looting resumes.");
if (_useStuckAnnounced)
ChatLine("[RynthAi] Objects open again; looting is back on.");
_useStuckAnnounced = false;
break;
}
}
/// <summary>When the use check last jumped (0 = not since the last open).</summary>
private long _useCheckJumpAt;
/// <summary>
/// One jump in place for the use check. On ACE the jump (0xF61B, the keyboard path: TapJump)
/// is the only in-world action that empties the server's animation queues for the character
/// (Player.HandleActionJump: RemoveLinkAnimations drains MotionTableManager.PendingAnimations,
/// MotionInterp.PendingMotions.Clear(), IsAnimating = false) and it cancels the stuck walk/turn
/// (GameActionJump -> StopExistingMoveToChains2). JumpNonAutonomous (0xF7C9) is not used: ACE
/// has no handler for it. Not while the pacer has an action out (a jump in Magic stance fails a
/// cast on the server).
/// </summary>
private bool TryUseCheckJump(long now, string why)
{
if (!Host.HasTapJump)
return false;
if (ActionPacer.Outstanding(Host, out var pending) && pending != null)
{
Log($"[RynthAi] Use check: no jump {why} - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)}.");
return false;
}
Host.SetAutoRunBy("Loot/UseCheck", false);
bool ok = Host.TapJump();
if (ok)
_useCheckJumpAt = now;
Log($"[RynthAi] Use check: jump {why} (clears the server's stuck animation queue; a relog was the only other fix) ok={ok}.");
return ok;
}
private string RefusedList() =>
string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}"));
// The arbiter's wantLoot of the current tick (HasLootWork), for LootHoldsIdlePeace.
private bool _lastWantLoot;
/// <summary>
/// CombatManager's idle peace-mode swap waits while looting has work: a corpse to claim, a
/// claimed or open corpse, or a door/corpse use the server is still answering. On ACE a
/// combat-mode change cancels the server's walk/turn to a used corpse (HandleActionCancelAttack
/// -> cancel_moveto), so the swap that went out 3 ms after the 06:18:44 open (2026-10-06) made
/// it fail; and between kills in a busy spawn it flipped peace/war every few seconds. Opening a
/// corpse needs no peace mode; the swap happens once looting is done.
/// </summary>
private bool LootHoldsIdlePeace() =>
_targetCorpseId != 0
|| _openedContainerId != 0
|| _lastWantLoot
|| RynthCore.Plugin.Shared.UseAudit.WorldUseInFlight(Host, out _);
/// <summary>A fresh session (logout/login): a relog is what clears a server that refuses uses.</summary>
private void ResetUseRefusalState()
{
_useRefusals.Reset();
_useCheckJumpAt = 0;
_useStuckAnnounced = false;
_lootWedgeAnnounced = false;
_consecutiveLootTimeouts = 0;
_lootHaltUntil = 0;
}
private void SyncCorpseContainerState()
@ -2551,6 +2887,11 @@ public sealed partial class RynthAiPlugin
/// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing
/// (the server closes the corpse when the next one is opened, as before).
/// </summary>
// The last close sent, until the server's CloseGroundContainer answers it (see TickCorpseOpening).
private int _closeSentFor;
private long _closeSentAt;
private const long CloseAnswerWaitMs = 500;
private void CloseCorpseContainer(int corpseId, string why)
{
if (corpseId == 0 || !Host.HasCloseContainer)
@ -2562,7 +2903,11 @@ public sealed partial class RynthAiPlugin
return;
if (Host.CloseContainer(unchecked((uint)corpseId)))
{
_closeSentFor = corpseId;
_closeSentAt = CorpseNowMs;
LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why}).");
}
else
LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why}).");
}
@ -2592,7 +2937,7 @@ public sealed partial class RynthAiPlugin
long ageMs = _corpseTargetSince != 0 ? now - _corpseTargetSince : 0;
LootDiag($"[RynthAi] Corpse loot: abandoning corpse 0x{(uint)corpseId:X8} after {ageMs}ms ({reason}).");
ChatLine($"[RynthAi] Corpse timeout: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
ChatLine($"[RynthAi] Corpse {(reason == "refused" ? "refuses to open" : "timeout")}: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
// Only a corpse we actually OPENED earns the completed mark (30-min
// do-not-touch — its loot is permanently skipped). A never-opened
@ -2664,13 +3009,19 @@ public sealed partial class RynthAiPlugin
/// </summary>
private void HandleLootWedge(long now)
{
FlightRecorderSignal.Dump(Host, "loot wedge");
_lootHaltUntil = now + LootWedgeHaltMs;
_consecutiveLootTimeouts = 0; // re-arm; if still wedged it trips again after the halt
if (Host.HasCancelAttack) Host.CancelAttack();
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
// Peace only when not already in it (2026-10-06): an unneeded request went to the server as
// a raw 0x53 anyway, and on ACE a mode change cancels whatever walk/turn is pending. Not
// while a server action is unanswered either (ChangeCombatModeFor holds it then).
Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset");
if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge");
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// No ForceResetBusyCount (2026-10-06): AC's busy count is the count of actions the server
// has not answered; zeroing it fixed nothing here (the lock is the server's or the
// client's item-request gates below) and let the next action out on top of them.
// The lock is client-side: AC's pending-item-request slot or attacking
// flag (see the engine's ClientActionGates). Open both now.
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions");
@ -2680,7 +3031,12 @@ public sealed partial class RynthAiPlugin
if (_combatManager != null) _combatManager.BusyCount = 0;
if (_buffManager != null) _buffManager.BusyCount = 0;
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
// Once per stall (until a corpse opens): 2026-10-06 it fired 11 times in 13 minutes.
if (!_lootWedgeAnnounced)
{
_lootWedgeAnnounced = true;
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
}
Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired.");
}
@ -2716,6 +3072,10 @@ public sealed partial class RynthAiPlugin
ChatLine($"[RynthAi] Corpse ranges: max={ConvertMetersToYards(maxMeters):F1} yd / {maxMeters:F1} m, min={ConvertMetersToYards(minMeters):F1} yd / {minMeters:F1} m");
uint rawOpen = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
ChatLine($"[RynthAi] Corpse state: target=0x{(uint)_targetCorpseId:X8}, corpse-open=0x{(uint)_openedContainerId:X8}, raw-open=0x{rawOpen:X8}, busy={_busyCount}, inv-update={(_openedContainerInventoryObservedAt != 0 ? 1 : 0)}, completed={_completedCorpses.Count}");
long infoNow = CorpseNowMs;
ChatLine($"[RynthAi] Use check: {_useRefusals.State}, {_useRefusals.Refusals} refused open(s) since the last open"
+ (_useRefusals.HoldsOpens(infoNow) ? $", looting paused {(_useRefusals.BackoffUntil - infoNow) / 1000}s more (the server refuses uses; a relog fixes it)" : "")
+ (Host.HasUseDoneSeq ? "" : " (this engine can't report the server's answers: the check is off)"));
if (TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters))
ChatLine($"[RynthAi] Nearest corpse: {corpse!.Name} (0x{(uint)corpse.Id:X8}) at {ConvertMetersToYards(distanceMeters):F1} yd / {distanceMeters:F1} m");

View file

@ -28,7 +28,7 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
/// </summary>
internal sealed class CreatureProfileStore
{
internal const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
private const string FileName = "creatures.json";
private readonly object _lock = new();

View file

@ -283,7 +283,7 @@ internal static class CreatureWeakness
}
/// <summary>The on-disk copy of the weakness table next to RynthAi (optional; the DLL has one built in).</summary>
internal const string WeaknessFile = @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json";
internal static readonly string WeaknessFile = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Data", "creature_weakness.json");
// JSON keys → Elements index (the table spells Lightning "electric").
private static readonly (string Key, int Index)[] JsonKeys =

View file

@ -24,7 +24,8 @@ namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardStore
{
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
private static readonly string Folder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"DungeonHazards");
// Settable so the host tests point it at their scratch folder.
internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "DungeonHazards");
private static string PathFor(uint landblockKey)
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");

View file

@ -37,7 +37,7 @@ namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardSurfaces
{
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
private static readonly string Folder = RynthInstallPaths.RynthAiDir;
private static readonly string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir;
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
private static readonly object _gate = new();

View file

@ -0,0 +1,28 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Asks the engine's flight recorder (RynthCore Net/FlightRecorder.cs, 2026-10-06) to write its
/// buffer: the last minutes of client/server messages and engine markers. Called where RynthAi
/// notices a stall (LOOT WEDGE, the use-refusal check, a held-cast nudge), so the dump holds
/// the message sequence that led into it. The engine writes at most one automatic dump per
/// 10 minutes, so calling this often is harmless. Uses the plugin-command broker (API v64)
/// with a name the engine reserves; an engine without the recorder finds no such plugin and
/// nothing happens. Never throws.
/// </summary>
internal static class FlightRecorderSignal
{
public const string Target = "RynthCore.FlightRecorder";
public static void Dump(RynthCoreHost host, string reason)
{
try
{
if (host.HasSendPluginCommand)
host.SendPluginCommand(Target, "dump", "RynthAi " + reason);
}
catch { }
}
}

View file

@ -0,0 +1,308 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.Editing;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>One item's appraisal values, as <see cref="ItemInfoText"/> reads them.</summary>
internal interface IItemInfoSource
{
/// <summary>The name the client shows ("" when unknown).</summary>
string Name { get; }
bool TryInt(uint key, out int value);
bool TryFloat(uint key, out double value);
/// <summary>The item's spells (empty when none or not appraised).</summary>
IReadOnlyList<int> SpellIds { get; }
}
/// <summary>
/// /ra iteminfo's text: one item on one chat line, in the spirit of Mag-Tools' item info
/// (name, type, set, armor, ratings, damage and mods, imbues, slayer, tinks, spells by name,
/// wield and activation requirements, craft, material, value and burden). A field the
/// appraisal doesn't carry is left out. Pure: no host calls, so the host tests feed it a
/// fake source.
/// </summary>
internal static class ItemInfoText
{
// STypeInt (AC / ACE PropertyInt numbering; the names in Meta/PropertyNames.cs).
internal const uint IntItemType = 1, IntEncumbrance = 5, IntStackSize = 12, IntRareId = 17, IntValue = 19,
IntArmorLevel = 28, IntBonded = 33, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48,
IntWeaponTime = 49, IntWorkmanship = 105, IntSpellcraft = 106, IntCurMana = 107, IntMaxMana = 108,
IntItemDifficulty = 109, IntAllegianceRankLimit = 110, IntAttuned = 114, IntSkillLevelLimit = 115,
IntMaterial = 131, IntWieldReq = 158, IntWieldSkill = 159, IntWieldDiff = 160, IntSlayerType = 166,
IntTinks = 171, IntImbued = 179, IntElementalBonus = 204, IntSetId = 265, IntWieldReq2 = 270,
IntWieldSkill2 = 271, IntWieldDiff2 = 272, IntItemMaxLevel = 319;
// STypeFloat (ACE PropertyFloat numbering).
internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63,
FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152;
/// <summary>Gear ratings (STypeInt 370-389) and their short tags, in print order.</summary>
internal static readonly (uint Key, string Tag)[] Ratings =
{
(370, "D"), (371, "DR"), (372, "C"), (373, "CR"), (374, "CD"), (375, "CDR"),
(376, "HB"), (379, "Vit"), (377, "NR"), (378, "LR"), (388, "OP"), (389, "OPR"),
(383, "PvP D"), (384, "PvP DR"),
};
// ItemType flags (STypeInt 1), most specific first.
private static readonly (uint Flag, string Name)[] Types =
{
(0x00040000, "Promissory Note"), (0x00080000, "Mana Stone"), (0x00001000, "Spell Component"),
(0x00000800, "Gem"), (0x00004000, "Key"), (0x40000000, "Salvage"), (0x20000000, "Tinkering Tool"),
(0x00000200, "Container"), (0x00008000, "Caster"), (0x00000100, "Missile Weapon"),
(0x00000001, "Melee Weapon"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
(0x00000020, "Food"), (0x00000040, "Money"), (0x00002000, "Writable"), (0x00000080, "Misc"),
};
// ImbuedEffect flags (STypeInt 179).
private static readonly (uint Flag, string Name)[] Imbues =
{
(0x0001, "Critical Strike"), (0x0002, "Crippling Blow"), (0x0004, "Armor Rending"),
(0x0008, "Slash Rending"), (0x0010, "Pierce Rending"), (0x0020, "Bludgeon Rending"),
(0x0040, "Acid Rending"), (0x0080, "Cold Rending"), (0x0100, "Lightning Rending"),
(0x0200, "Fire Rending"), (0x0400, "Melee Defense"), (0x0800, "Missile Defense"),
(0x1000, "Magic Defense"), (0x4000, "Nether Rending"),
};
// Equipment sets (STypeInt 265) whose ids are certain: the loot armor sets and Aetheria.
private static readonly Dictionary<int, string> Sets = new()
{
[13] = "Soldier's", [14] = "Adept's", [15] = "Archer's", [16] = "Defender's", [17] = "Tinker's",
[18] = "Crafter's", [19] = "Hearty", [20] = "Dexterous", [21] = "Wise", [22] = "Swift",
[23] = "Hardened", [24] = "Reinforced", [25] = "Interlocking", [26] = "Flame Proof",
[27] = "Acid Proof", [28] = "Cold Proof", [29] = "Lightning Proof",
[35] = "Aetheria: Defense", [36] = "Aetheria: Destruction", [37] = "Aetheria: Fury",
[38] = "Aetheria: Growth", [39] = "Aetheria: Vigor",
};
// Attributes and vitals for attribute/vital wield requirements (ACE PropertyAttribute / PropertyAttribute2nd).
private static readonly string[] Attributes = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
private static readonly string[] Vitals = { "", "Max Health", "Health", "Max Stamina", "Stamina", "Max Mana", "Mana" };
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
/// <summary>
/// The item on one line. <paramref name="spellName"/> names a spell id (the plugin's
/// spell table). <paramref name="identified"/> false adds a note that the server never
/// answered the ID, so only what the client already knew is shown.
/// </summary>
public static string Describe(IItemInfoSource item, Func<int, string> spellName, bool identified = true)
{
var parts = new List<string>(24);
int type = Int(item, IntItemType);
// Name, with the material in front the way the game names loot ("Gold Ring").
string name = item.Name.Trim();
int material = Int(item, IntMaterial);
string full = WeaponNames.Full(name, material);
if (full.Length == 0) full = "(unnamed item)";
string typeName = TypeName(type);
int stack = Int(item, IntStackSize);
var head = new StringBuilder(full);
if (stack > 1) head.Append(" x").Append(stack.ToString("N0", Inv));
if (typeName.Length > 0) head.Append(" (").Append(typeName).Append(')');
parts.Add(head.ToString());
if (Int(item, IntSetId) is int set and > 0)
parts.Add((Sets.TryGetValue(set, out string? setName) ? setName : "Set " + set) + " Set");
if (item.TryInt(IntArmorLevel, out int al) && (al > 0 || (type & 0x2) != 0))
parts.Add("AL " + al.ToString(Inv));
string ratings = RatingText(item);
if (ratings.Length > 0) parts.Add(ratings);
AddWeapon(item, type, parts);
string imbues = ImbueText(Int(item, IntImbued));
if (imbues.Length > 0) parts.Add(imbues);
if (Int(item, IntSlayerType) is int slayer and > 0)
parts.Add(CreatureTypeNames.Name(slayer) + " Slayer");
if (item.TryInt(IntTinks, out int tinks) && tinks > 0)
parts.Add("Tinks " + tinks.ToString(Inv));
string spells = SpellText(item.SpellIds, spellName);
if (spells.Length > 0) parts.Add(spells);
string wield = WieldText(item, IntWieldReq, IntWieldSkill, IntWieldDiff);
if (wield.Length > 0) parts.Add(wield);
string wield2 = WieldText(item, IntWieldReq2, IntWieldSkill2, IntWieldDiff2);
if (wield2.Length > 0) parts.Add(wield2);
if (Int(item, IntSkillLevelLimit) is int skillLimit and > 0) parts.Add("Skill " + skillLimit.ToString(Inv) + " to activate");
if (Int(item, IntAllegianceRankLimit) is int rank and > 0) parts.Add("Rank " + rank.ToString(Inv));
if (Int(item, IntItemDifficulty) is int diff and > 0) parts.Add("Diff " + diff.ToString(Inv));
if (Int(item, IntSpellcraft) is int spellcraft and > 0) parts.Add("Spellcraft " + spellcraft.ToString(Inv));
if (item.TryInt(IntMaxMana, out int maxMana) && maxMana > 0)
parts.Add("Mana " + (item.TryInt(IntCurMana, out int cur) ? cur.ToString(Inv) + "/" : "") + maxMana.ToString(Inv));
if (Int(item, IntItemMaxLevel) is int maxLevel and > 0) parts.Add("Max Level " + maxLevel.ToString(Inv));
if (item.TryInt(IntWorkmanship, out int craft) && craft > 0) parts.Add("Craft " + craft.ToString(Inv));
string matName = WeaponNames.Material(material);
if (matName.Length > 0) parts.Add("Mat " + matName);
if (Int(item, IntBonded) == 1) parts.Add("Bonded");
if (Int(item, IntAttuned) == 1) parts.Add("Attuned");
if (Int(item, IntRareId) is int rare and > 0) parts.Add("Rare #" + rare.ToString(Inv));
if (item.TryInt(IntValue, out int value)) parts.Add("Value " + value.ToString("N0", Inv));
if (item.TryInt(IntEncumbrance, out int burden)) parts.Add("BU " + burden.ToString("N0", Inv));
if (!identified) parts.Add("(not identified: no reply from the server)");
return string.Join(", ", parts);
}
private static int Int(IItemInfoSource item, uint key) => item.TryInt(key, out int v) ? v : 0;
/// <summary>The item's kind from its ItemType flags ("" when none is set).</summary>
internal static string TypeName(int itemType)
{
uint t = unchecked((uint)itemType);
foreach (var (flag, n) in Types)
if ((t & flag) != 0) return n;
return "";
}
/// <summary>"[D3 CD2 CDR1]" for the gear ratings that are set; "" for none.</summary>
internal static string RatingText(IItemInfoSource item)
{
var sb = new StringBuilder();
foreach (var (key, tag) in Ratings)
{
if (!item.TryInt(key, out int r) || r <= 0) continue;
sb.Append(sb.Length == 0 ? "[" : " ").Append(tag).Append(r.ToString(Inv));
}
return sb.Length == 0 ? "" : sb.Append(']').ToString();
}
private static void AddWeapon(IItemInfoSource item, int type, List<string> parts)
{
uint t = unchecked((uint)type);
bool melee = (t & 0x1) != 0, missile = (t & 0x100) != 0, caster = (t & 0x8000) != 0;
bool weapon = melee || missile || caster;
if (Int(item, IntWeaponSkill) is int skill and > 0 && weapon)
parts.Add(SkillName(skill));
int dmgType = Int(item, IntDamageType);
if (item.TryInt(IntDamage, out int max) && max > 0)
{
string dmg = "Dmg " + max.ToString(Inv);
if (item.TryFloat(FloatDamageVariance, out double variance) && variance > 0 && variance < 1)
{
int min = (int)Math.Round(max * (1.0 - variance), MidpointRounding.AwayFromZero);
dmg = $"Dmg {min.ToString(Inv)}-{max.ToString(Inv)}";
}
string element = DamageTypeName(dmgType);
if (element.Length > 0) dmg += " " + element;
parts.Add(dmg);
}
else if (weapon && dmgType > 0)
{
string element = DamageTypeName(dmgType);
if (element.Length > 0) parts.Add(element);
}
if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg");
if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv));
// Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too.
var mods = new List<string>(6);
AddPercent(item, FloatWeaponOffense, "atk", mods, weapon);
if (missile) AddPercent(item, FloatDamageMod, "dmg", mods, true);
if (caster) AddPercent(item, FloatElementalDamage, "vs monsters", mods, true);
AddPercent(item, FloatMeleeDefense, "md", mods, weapon);
AddPercent(item, FloatMissileDefense, "mid", mods, weapon);
AddPercent(item, FloatMagicDefense, "mgd", mods, weapon);
AddPercent(item, FloatManaConversion, "mana c", mods, true);
if (mods.Count > 0) parts.Add("(" + string.Join(", ", mods) + ")");
}
private static void AddPercent(IItemInfoSource item, uint key, string label, List<string> mods, bool allowed)
{
if (!allowed || !item.TryFloat(key, out double v) || double.IsNaN(v)) return;
// Multipliers (attack, defense, damage) are stored as 1.xx; mana conversion as 0.xx.
double pct = key == FloatManaConversion ? v * 100.0 : (v - 1.0) * 100.0;
int rounded = (int)Math.Round(pct, MidpointRounding.AwayFromZero);
if (rounded == 0) return;
mods.Add((rounded > 0 ? "+" : "") + rounded.ToString(Inv) + "% " + label);
}
/// <summary>"Crippling Blow, Fire Rending" for the imbue flags; "" for none.</summary>
internal static string ImbueText(int flags)
{
if (flags == 0) return "";
uint f = unchecked((uint)flags);
var names = new List<string>(2);
foreach (var (flag, n) in Imbues)
if ((f & flag) != 0) names.Add(n);
return string.Join(", ", names);
}
/// <summary>"Spells: A, B, C" by name, in the item's order, each once; "" for none.</summary>
internal static string SpellText(IReadOnlyList<int> spellIds, Func<int, string> spellName)
{
if (spellIds.Count == 0) return "";
var seen = new HashSet<int>();
var names = new List<string>(spellIds.Count);
foreach (int id in spellIds)
{
if (id <= 0 || !seen.Add(id)) continue;
string n = spellName(id);
names.Add(string.IsNullOrWhiteSpace(n) ? "spell " + id.ToString(Inv) : n);
}
return names.Count == 0 ? "" : "Spells: " + string.Join(", ", names);
}
/// <summary>One wield requirement ("Wield Lvl 180", "Heavy Weapons 375 to wield"); "" for none.</summary>
internal static string WieldText(IItemInfoSource item, uint reqKey, uint skillKey, uint diffKey)
{
int req = Int(item, reqKey);
if (req <= 0) return "";
int skill = Int(item, skillKey);
int diff = Int(item, diffKey);
string d = diff.ToString(Inv);
return req switch
{
1 => $"{SkillName(skill)} {d} to wield",
2 => $"Base {SkillName(skill)} {d} to wield",
3 => $"{Pick(Attributes, skill, "Attribute")} {d} to wield",
4 => $"Base {Pick(Attributes, skill, "Attribute")} {d} to wield",
5 => $"{Pick(Vitals, skill, "Vital")} {d} to wield",
6 => $"Base {Pick(Vitals, skill, "Vital")} {d} to wield",
7 => $"Wield Lvl {d}",
8 => $"{(diff >= 3 ? "Specialized" : "Trained")} {SkillName(skill)} to wield",
12 => $"Heritage {d} to wield",
_ => $"Wield requirement {req.ToString(Inv)} ({skill.ToString(Inv)}, {d})",
};
}
private static string Pick(string[] names, int i, string fallback) =>
i > 0 && i < names.Length ? names[i] : $"{fallback} {i.ToString(Inv)}";
/// <summary>AC's skill name for a skill id ("skill N" when unknown).</summary>
internal static string SkillName(int id)
{
foreach (var (sid, n) in LootRuleText.Skills)
if (sid == id) return n;
return "skill " + id.ToString(Inv);
}
/// <summary>The damage type's name ("Slashing/Piercing" etc.); "" for none.</summary>
internal static string DamageTypeName(int flags)
{
if (flags <= 0) return "";
foreach (var (id, n) in LootRuleText.DamageTypes)
if (id == flags) return n;
// Other combinations: the single flags joined.
var names = new List<string>(3);
foreach (var (id, n) in LootRuleText.DamageTypes)
if (id > 0 && (id & (id - 1)) == 0 && (flags & id) != 0) names.Add(n);
return string.Join("/", names);
}
}

View file

@ -1,673 +0,0 @@
// MagItemDescriber.cs — one-line "Mag-style" item info (Mag-Tools ItemInfo / UtilityBelt ub-IT ItemInfo).
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, CS, Undead Slayer, Tinks 4,
// Applied: Steel x2, 152.48-236, 0.35v, +18%a, 12%md, Legendary Blood Thirst, Wield Lvl 180,
// Heavy Weapons 375, Diff 270, Craft 8, [D 3, CD 2]
//
// The same fields can also print as the pet-roster layout (IltPetStats: identity line, stats
// line, ratings/requirements line), plus a spells line:
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8
// CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md
// [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270
// Spells: Legendary Blood Thirst
//
// Field order and per-class gating follow ub-IT (Tools/ItemInfo.cs ItemDescriptions.ToString,
// Lib/ItemDescribeMagShorthand.cs, Lib/ItemInfoHelper/ItemIdentifyFieldSet.cs); labels and the
// spell filter follow Mag-Tools. All ids are raw ACE properties (RynthCore reads CBaseQualities by
// STypeInt/STypeFloat/STypeString id — not Decal's remapped LongValueKey/DoubleValueKey numbers).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Property reads for one item. Implemented over the live object cache (see
/// <see cref="CacheItemPropertySource"/>); a missing property returns false / empty.</summary>
internal interface IItemPropertySource
{
string Name { get; }
AcObjectClass ObjectClass { get; }
bool TryGetInt(uint stype, out int value);
bool TryGetDouble(uint stype, out double value);
string GetString(uint stype);
/// <summary>Spell ids on the item (inscribed + cantrips), unsorted.</summary>
IReadOnlyList<int> SpellIds { get; }
}
/// <summary>Per-call output options, snapshotted from <see cref="MagItemInfoSettings"/>.</summary>
internal readonly record struct MagItemInfoOptions(
MagItemInfoField Hidden, int HiddenRatings, bool ShowValueAndBurden, bool AllSpells, int MaxListedSpells)
{
/// <summary>Everything shown, Mag spell filter — used when no settings are loaded yet.</summary>
public static readonly MagItemInfoOptions Default = new(MagItemInfoField.None, 0, false, false, 26);
public static MagItemInfoOptions From(MagItemInfoSettings? s) => s == null
? Default
: new((MagItemInfoField)s.HiddenFields, s.HiddenRatings, s.ShowValueAndBurden,
s.SpellMode == MagItemInfoSettings.SpellModeAll, s.MaxListedSpells);
public bool Shows(MagItemInfoField f) => (Hidden & f) == 0;
}
/// <summary>Which pet-style line a field lands on (<see cref="MagItemDescription.ToPetLines"/>).</summary>
internal enum MagItemSection
{
/// <summary>Line 1 after the name: set, AL, tinks, applied, craft, keyring.</summary>
Identity,
/// <summary>Line 2: imbues, slayer, damage, attack/defense/mana-conversion, protections.</summary>
Combat,
/// <summary>Line 3 lead: the "[D 3, CD 2]" cluster.</summary>
Ratings,
/// <summary>Line 3 tail: wield / activation / difficulty, value and burden.</summary>
Requirements,
/// <summary>Line 4: spell names.</summary>
Spells,
}
/// <summary>
/// One described item: the title plus fields tagged with their section, kept in Mag print order
/// so <see cref="ToOneLine"/> reproduces the classic line exactly.
/// </summary>
internal sealed class MagItemDescription
{
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
public string Title = string.Empty;
public readonly List<(MagItemSection Section, string Text)> Segments = new();
public void Add(MagItemSection section, string text)
{
if (!string.IsNullOrEmpty(text)) Segments.Add((section, text));
}
/// <summary>Classic Mag one-liner: title, then every field comma-separated.</summary>
public string ToOneLine()
{
var sb = new StringBuilder(Title, 256);
foreach (var (_, text) in Segments) sb.Append(", ").Append(text);
return sb.ToString();
}
/// <summary>
/// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are
/// dropped so plain armor stays short.
/// </summary>
public List<string> ToPetLines()
{
var lines = new List<string>(4);
var identity = new StringBuilder(Title);
foreach (string t in Section(MagItemSection.Identity)) identity.Append(", ").Append(t);
lines.Add(identity.ToString());
string combat = string.Join(", ", Section(MagItemSection.Combat));
if (combat.Length > 0) lines.Add(combat);
// Like the pet roster's third line: ratings first, then the rest two-space separated.
var tail = new List<string>(2);
string ratings = string.Join(", ", Section(MagItemSection.Ratings));
if (ratings.Length > 0) tail.Add(ratings);
string reqs = string.Join(", ", Section(MagItemSection.Requirements));
if (reqs.Length > 0) tail.Add(reqs);
if (tail.Count > 0) lines.Add(string.Join(" ", tail));
var spells = Section(MagItemSection.Spells);
if (spells.Count > 0)
{
// The verbose list is a single pre-labelled "Spells: a; b" segment.
lines.Add(spells.Count == 1 && spells[0].StartsWith("Spells:", StringComparison.Ordinal)
? spells[0]
: "Spells: " + string.Join(", ", spells));
}
return lines;
}
private List<string> Section(MagItemSection section)
{
var list = new List<string>();
foreach (var (s, text) in Segments)
if (s == section) list.Add(text);
return list;
}
}
/// <summary>Builds the Mag-style item info line.</summary>
internal static class MagItemDescriber
{
// ── ACE PropertyInt ids ──────────────────────────────────────────────────
private const uint IntBurden = 5; // EncumbranceVal
private const uint IntValue = 19;
private const uint IntArmorLevel = 28;
private const uint IntResistMagic = 36; // >= 9999 = unenchantable
private const uint IntMaxDamage = 44; // Damage
private const uint IntDamageType = 45;
private const uint IntAttackType = 47;
private const uint IntStructure = 92; // keyring uses remaining
private const uint IntWorkmanship = 105;
private const uint IntItemDifficulty = 109; // arcane lore requirement ("Diff")
private const uint IntActivationLevel = 115; // ItemSkillLevelLimit
private const uint IntMaterial = 131;
private const uint IntWieldReq = 158;
private const uint IntWieldSkill = 159;
private const uint IntWieldValue = 160;
private const uint IntSlayerCreature = 166;
private const uint IntNumItemsInMaterial = 170; // salvage: workmanship = 105 / 170
private const uint IntTinks = 171;
private const uint IntActivationSkill = 176; // AppraisalItemSkill
private const uint IntImbued = 179; // ImbuedEffect (+ 303..306 for 2..5)
private const uint IntNumKeys = 193;
private const uint IntElementalBonus = 204;
private const uint IntEquipmentSet = 265;
private const uint IntWieldReq2 = 270;
private const uint IntWieldSkill2 = 271;
private const uint IntWieldValue2 = 272;
private const uint IntWeaponType = 353; // mastery
private const uint IntUseRequiresSkill = 366;
private const uint IntUseRequiresSkillLvl = 367;
private const uint IntUseRequiresSpec = 368;
private const uint IntUseRequiresLevel = 369;
private const uint IntSplitArrows = 9031; // ACECustom SplitArrowCount
// ── ACE PropertyFloat ids ────────────────────────────────────────────────
private const uint FloatArmorVsSlash = 13; // 13..19 = Slash/Pierce/Bludgeon/Cold/Fire/Acid/Electric
private const uint FloatVariance = 22;
private const uint FloatMaxVelocity = 26;
private const uint FloatMeleeDefense = 29; // WeaponDefense
private const uint FloatAttack = 62; // WeaponOffense
private const uint FloatDamageMod = 63;
private const uint FloatCritMultiplier = 136;
private const uint FloatManaConversion = 144;
private const uint FloatCritFrequency = 147;
private const uint FloatMissileDefense = 149;
private const uint FloatMagicDefense = 150;
private const uint FloatVsMonsters = 152; // ElementalDamageMod
private const uint FloatIgnoreArmor = 155; // armor cleaving
// ── ACE PropertyString ids ───────────────────────────────────────────────
private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids
/// <summary>Gear ratings are small (1..~50). Anything above is a wrong key leaking through.</summary>
private const int MaxPlausibleRating = 200;
/// <summary>Class-specific fields (ub-IT ItemIdentifyFieldSet). Generic fields print for every class.</summary>
[Flags]
private enum Field
{
None = 0,
DamageType = 1 << 0,
CritStats = 1 << 1,
Splits = 1 << 2,
Cleaves = 1 << 3,
Slayer = 1 << 4,
Range = 1 << 5,
Damage = 1 << 6,
AttackBonus = 1 << 7,
MeleeDefense = 1 << 8,
MissileDefense = 1 << 9,
MagicDefense = 1 << 10,
ManaConversion = 1 << 11,
ArmorCleave = 1 << 12,
WeaponDefenses = MeleeDefense | MissileDefense | MagicDefense,
}
private static Field FieldsFor(AcObjectClass cls) => cls switch
{
AcObjectClass.MissileWeapon => Field.DamageType | Field.CritStats | Field.Splits | Field.Cleaves
| Field.Slayer | Field.Range | Field.Damage | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.MeleeWeapon => Field.DamageType | Field.CritStats | Field.Cleaves | Field.Slayer
| Field.Damage | Field.AttackBonus | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.WandStaffOrb => Field.DamageType | Field.CritStats | Field.Slayer | Field.Damage
| Field.WeaponDefenses | Field.ManaConversion,
AcObjectClass.Jewelry => Field.None,
// Armor / clothing / misc: keep Mag's generic bonus lines (shields roll %md etc.).
_ => Field.AttackBonus | Field.WeaponDefenses | Field.ManaConversion,
};
/// <summary>Full Mag-style line for one item (name first, comma-separated fields).</summary>
public static string Describe(IItemPropertySource item, MagItemInfoOptions options)
=> Build(item, options).ToOneLine();
/// <summary>Reads every enabled field once, tagged by section (one-line or pet-style output).</summary>
public static MagItemDescription Build(IItemPropertySource item, MagItemInfoOptions options)
{
var d = new MagItemDescription();
var sb = new StringBuilder(128); // title only
AcObjectClass cls = item.ObjectClass;
Field fields = FieldsFor(cls);
bool Has(Field f) => (fields & f) == f;
bool Show(MagItemInfoField f) => options.Shows(f);
int Int(uint id) => item.TryGetInt(id, out int v) ? v : 0;
double Dbl(uint id, double fallback) => item.TryGetDouble(id, out double v) ? v : fallback;
// ── Name: "[Material ]Name (DamageType Mastery)" ────────────────────────
int material = Int(IntMaterial);
if (material > 0 && Show(MagItemInfoField.Material))
{
string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}";
// Loot names usually omit the material; don't double it when the name already starts with it.
if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase))
sb.Append(matName).Append(' ');
}
sb.Append(item.Name);
if (Has(Field.DamageType) && Show(MagItemInfoField.TypeMastery))
{
string dmgType = MagItemInfoTables.DamageTypeName(Int(IntDamageType));
int mastery = Int(IntWeaponType);
string masteryName = mastery > 0
? (MagItemInfoTables.Masteries.TryGetValue(mastery, out string? mn) ? mn : $"Unknown mastery {mastery}")
: string.Empty;
string inner = $"{dmgType} {masteryName}".Trim();
if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')');
}
d.Title = sb.ToString();
const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements;
string I(int v) => v.ToString(CultureInfo.InvariantCulture);
// ── Set ─────────────────────────────────────────────────────────────────
int set = Int(IntEquipmentSet);
if (set > 0 && Show(MagItemInfoField.Set))
d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
// ── Armor level ─────────────────────────────────────────────────────────
int al = Int(IntArmorLevel);
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al));
// ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ─────────
if (Show(MagItemInfoField.Imbues))
d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306)));
if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0)
d.Add(Cbt, "AC");
if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats))
{
double critMult = Dbl(FloatCritMultiplier, 0);
if (critMult > 0) d.Add(Cbt, $"CritMult ({Fmt(critMult)})");
double critFreq = Dbl(FloatCritFrequency, 0);
if (critFreq > 0) d.Add(Cbt, $"CritFreq ({Fmt(critFreq)})");
}
if (Has(Field.Splits) && Show(MagItemInfoField.Splits))
{
int splits = Int(IntSplitArrows);
if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})");
}
if (Has(Field.Range) && Show(MagItemInfoField.Range))
{
int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0));
if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd");
}
if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike))
{
int attackType = Int(IntAttackType);
int mastery = Int(IntWeaponType);
bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0);
if (cleaving) d.Add(Cbt, "Cleaving");
else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike");
else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)");
}
// ── Slayer ──────────────────────────────────────────────────────────────
if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer))
{
string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature));
if (slayer != null) d.Add(Cbt, slayer + " Slayer");
}
// ── Tinks + applied materials (TinkerLog) ──────────────────────────────
int tinks = Int(IntTinks);
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks));
if (Show(MagItemInfoField.Applied))
{
string applied = FormatTinkerLog(item.GetString(StringTinkerLog));
if (applied.Length > 0) d.Add(Id, "Applied: " + applied);
}
// ── Damage ──────────────────────────────────────────────────────────────
if (Has(Field.Damage) && Show(MagItemInfoField.Damage))
AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus),
Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1));
// ── Attack / defense / mana conversion percents ───────────────────────
bool defenses = Show(MagItemInfoField.Defenses);
if (Has(Field.AttackBonus) && Show(MagItemInfoField.Attack)) AddPercent(d, Dbl(FloatAttack, 1), "%a", 0);
if (Has(Field.MeleeDefense) && defenses) AddPercent(d, Dbl(FloatMeleeDefense, 1), "%md", 0);
if (Has(Field.MagicDefense) && defenses) AddPercent(d, Dbl(FloatMagicDefense, 1), "%mgc.d", 1);
if (Has(Field.MissileDefense) && defenses) AddPercent(d, Dbl(FloatMissileDefense, 1), "%msl.d", 1);
if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion))
{
double mc = Dbl(FloatManaConversion, 0);
if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
}
// ── Spells ──────────────────────────────────────────────────────────────
bool unenchantable = Int(IntResistMagic) >= 9999;
if (Show(MagItemInfoField.Spells))
AddSpells(d, item.SpellIds, unenchantable, options.AllSpells, options.MaxListedSpells);
// ── Requirements ────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Wield))
{
AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue));
AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2));
}
if (Show(MagItemInfoField.Activation))
{
int useLevel = Int(IntUseRequiresLevel);
if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel));
// "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it.
int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel);
if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel))
d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
// Summoning essences / gems.
int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec);
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}");
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
}
int diff = Int(IntItemDifficulty);
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff));
// ── Workmanship ─────────────────────────────────────────────────────────
int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0;
if (cls == AcObjectClass.Salvage)
{
int items = Int(IntNumItemsInMaterial);
if (work > 0)
{
double avg = items > 0 ? (double)work / items : work;
d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
}
}
else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked
{
d.Add(Id, "Craft " + I(work));
}
// ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ─────────────
if (cls == AcObjectClass.Armor && unenchantable && Show(MagItemInfoField.Protections))
{
var prot = new StringBuilder("[");
for (uint i = 0; i < 7; i++)
{
if (i > 0) prot.Append('/');
prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture));
}
d.Add(Cbt, prot.Append(']').ToString());
}
if (options.ShowValueAndBurden)
{
int value = Int(IntValue);
if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
int burden = Int(IntBurden);
if (burden > 0) d.Add(Req, "BU " + I(burden));
}
// ── Ratings ─────────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Ratings))
d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings));
if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring)
&& item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase))
{
d.Add(Id, "Keys: " + I(Int(IntNumKeys)));
d.Add(Id, "Uses: " + I(Int(IntStructure)));
}
return d;
}
/// <summary>Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether
/// rend); empty when no known bit is set.</summary>
private static string ImbueLabels(int mask)
{
if (mask == 0) return string.Empty;
var sb = new StringBuilder();
void Flag(int bit, string label)
{
if ((mask & bit) == 0) return;
if (sb.Length > 0) sb.Append(' ');
sb.Append(label);
}
Flag(0x0001, "CS");
Flag(0x0002, "CB");
Flag(0x0004, "AR");
Flag(0x0008, "SlashRend");
Flag(0x0010, "PierceRend");
Flag(0x0020, "BludgeRend");
Flag(0x0040, "AcidRend");
Flag(0x0080, "FrostRend");
Flag(0x0100, "LightRend");
Flag(0x0200, "FireRend");
Flag(0x4000, "NetherRend");
Flag(0x0400, "MeleeImbue");
Flag(0x0800, "MissileImbue");
Flag(0x1000, "MagicImbue");
Flag(0x2000, "Hematited");
Flag(0x20000000, "MagicAbsorb");
return sb.ToString(); // only unknown bits → empty → field skipped
}
/// <summary>Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line).</summary>
private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance,
int elemBonus, double dmgMod, double vsMonsters)
{
const MagItemSection Cbt = MagItemSection.Combat;
if (cls != AcObjectClass.MissileWeapon && maxDmg > 0)
{
string max = maxDmg.ToString(CultureInfo.InvariantCulture);
d.Add(Cbt, variance > 0
? (maxDmg - maxDmg * variance).ToString("N2", CultureInfo.InvariantCulture) + "-" + max
: max);
}
if (variance > 0)
d.Add(Cbt, Math.Round(variance, 2).ToString(CultureInfo.InvariantCulture) + "v");
if (elemBonus != 0)
d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture));
// A missing/zero multiplier means "no bonus" (0 would print as -100%).
if (dmgMod > 0 && dmgMod != 1)
d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
if (vsMonsters > 0 && vsMonsters != 1)
d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
}
/// <summary>Mag "18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0.</summary>
private static void AddPercent(MagItemDescription d, double multiplier, string suffix, int decimals)
{
if (multiplier <= 0 || multiplier == 1) return;
double pct = Math.Round((multiplier - 1) * 100, decimals);
d.Add(MagItemSection.Combat, pct.ToString(CultureInfo.InvariantCulture) + suffix);
}
/// <summary>"Wield Lvl 180" for a level requirement, else "Heavy Weapons 375".</summary>
private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value)
{
if (value <= 0) return;
string v = value.ToString(CultureInfo.InvariantCulture);
d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level
? "Wield Lvl " + v
: SkillName(skillOrAttr) + " " + v);
}
private static string SkillName(int skill) =>
MagItemInfoTables.Skills.TryGetValue(skill, out string? name) ? name : $"Skill {skill}";
/// <summary>
/// Mag-Tools spell filter (ub-IT applies it to every item): keep cantrip Impen, Augmented
/// (trinket) spells, banes/Impen only on unenchantable gear, level 7+ weapon auras, and
/// named high-tier spells (cantrips); drop I–VI, level-7 lore buffs and Incantations.
/// Verbose lists every spell (capped) for troubleshooting.
/// </summary>
private static void AddSpells(MagItemDescription d, IReadOnlyList<int> spellIds, bool unenchantable,
bool verbose, int maxVerbose)
{
if (spellIds.Count == 0) return;
var ids = new List<int>(spellIds);
ids.Sort();
ids.Reverse(); // Mag lists highest spell id first
var seen = new HashSet<int>();
var verboseList = verbose ? new StringBuilder() : null;
int shown = 0, skippedVerbose = 0;
foreach (int id in ids)
{
if (!seen.Add(id)) continue;
bool known = SpellDatabase.HasSpell(id);
if (verboseList != null)
{
// Verbose is the troubleshooting view: list ids SpellData.txt doesn't know too.
if (shown >= maxVerbose) { skippedVerbose++; continue; }
verboseList.Append(shown == 0 ? "Spells: " : "; ")
.Append(known ? SpellDatabase.GetSpellName(id) : $"Spell {id}");
shown++;
continue;
}
if (!known) continue;
string name = SpellDatabase.GetSpellName(id);
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
if (ShouldShowSpell(name, family, difficulty, unenchantable))
d.Add(MagItemSection.Spells, name);
}
if (verboseList == null || verboseList.Length == 0) return;
if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)");
d.Add(MagItemSection.Spells, verboseList.ToString());
}
private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable)
{
if (name.Contains("Minor Impenetrability") || name.Contains("Major Impenetrability")
|| name.Contains("Epic Impenetrability") || name.Contains("Legendary Impenetrability"))
return true;
if (name.Contains("Augmented"))
return true;
// Banes / Impen / Brogard's: only meaningful on unenchantable gear (loot armor
// already reflects them in AL and protections).
bool baneLike = name.Contains(" Bane") || name.Contains("Impen") || name.StartsWith("Brogard", StringComparison.Ordinal);
if (baneLike) return unenchantable;
// Weapon auras (Elysa's Sight .. Swift Killer, Hermetic Link, Vision of the Hunter):
// level 7 (300) and 8+ (400+) only.
if ((family >= 152 && family <= 158) || family == 195 || family == 325)
return difficulty == 300 || difficulty >= 400;
if (name.EndsWith(" I") || name.EndsWith(" II") || name.EndsWith(" III")
|| name.EndsWith(" IV") || name.EndsWith(" V") || name.EndsWith(" VI"))
return false;
if (difficulty == 300) return false; // level-7 lore buffs (Might of the Lugians …)
if (name.Contains("Incantation")) return false;
return true; // cantrips: Legendary Strength, Epic Defender …
}
/// <summary>Rating cluster "[D 11, C 8, CD 4]" from ACE Gear* ratings 370–389
/// (<see cref="MagItemInfoCatalog.Ratings"/>); bit i of <paramref name="hiddenMask"/> skips rating i.</summary>
private static string RatingsCluster(IItemPropertySource item, int hiddenMask)
{
var sb = new StringBuilder();
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
if ((hiddenMask & (1 << i)) != 0) continue;
if (!item.TryGetInt(ratings[i].StatId, out int v) || v <= 0 || v > MaxPlausibleRating) continue;
sb.Append(sb.Length == 0 ? "[" : ", ").Append(ratings[i].Tag).Append(' ')
.Append(v.ToString(CultureInfo.InvariantCulture));
}
return sb.Length > 0 ? sb.Append(']').ToString() : string.Empty;
}
/// <summary>ACECustom TinkerLog CSV ("64,64,46") → "Steel x2, White Quartz".</summary>
private static string FormatTinkerLog(string csv)
{
if (string.IsNullOrWhiteSpace(csv)) return string.Empty;
var order = new List<int>();
var counts = new Dictionary<int, int>();
foreach (string raw in csv.Split(','))
{
if (!int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) || id <= 0)
continue;
if (counts.TryGetValue(id, out int c)) counts[id] = c + 1;
else { counts[id] = 1; order.Add(id); }
}
var sb = new StringBuilder();
foreach (int id in order)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(MagItemInfoTables.Materials.TryGetValue(id, out string? name) ? name : $"material {id}");
if (counts[id] > 1) sb.Append(" x").Append(counts[id]);
}
return sb.ToString();
}
/// <summary>Max ballistic range (45° arc, v²/g) in yards; 0 when velocity is missing.</summary>
private static int MissileRangeYards(double velocity)
{
if (double.IsNaN(velocity) || velocity <= 0) return 0;
double meters = velocity * velocity / 9.8;
return (int)Math.Round(meters * 1.0936133);
}
private static string Fmt(double v) => Math.Round(v, 2).ToString(CultureInfo.InvariantCulture);
}
/// <summary><see cref="IItemPropertySource"/> over the live client object (RynthCore host reads).</summary>
internal sealed class CacheItemPropertySource : IItemPropertySource
{
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
private readonly uint _id;
private IReadOnlyList<int>? _spells;
public CacheItemPropertySource(RynthCore.PluginSdk.RynthCoreHost host, WorldObject wo)
{
_host = host;
_id = unchecked((uint)wo.Id);
Name = wo.Name;
ObjectClass = wo.ObjectClass;
}
public string Name { get; }
public AcObjectClass ObjectClass { get; }
public bool TryGetInt(uint stype, out int value)
{
value = 0;
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, stype, out value);
}
public bool TryGetDouble(uint stype, out double value)
{
value = 0;
return _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(_id, stype, out value);
}
public string GetString(uint stype) =>
_host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(_id, stype, out string? v) && v != null
? v
: string.Empty;
public IReadOnlyList<int> SpellIds => _spells ??= ReadSpells();
private IReadOnlyList<int> ReadSpells()
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
uint[] buf = new uint[128];
int n = _host.GetObjectSpellIds(_id, buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
int take = Math.Min(n, buf.Length);
var list = new List<int>(take);
for (int i = 0; i < take; i++) list.Add(unchecked((int)buf[i]));
return list;
}
}

View file

@ -1,251 +0,0 @@
// MagItemInfoSettings.cs — user options for the Mag-style item info line (/ra iteminfo).
//
// Stored per character inside LegacyUiSettings.ItemInfoSettings. Field visibility is kept as a
// *hidden* bitmask so any field added in a later release shows by default for existing profiles.
using System;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Toggleable sections of the item info line (bit set in HiddenFields = not printed).</summary>
[Flags]
public enum MagItemInfoField
{
None = 0,
Material = 1 << 0,
TypeMastery = 1 << 1,
Set = 1 << 2,
ArmorLevel = 1 << 3,
Imbues = 1 << 4,
ArmorCleave = 1 << 5,
CritStats = 1 << 6,
Splits = 1 << 7,
Range = 1 << 8,
CleaveMultiStrike = 1 << 9,
Slayer = 1 << 10,
Tinks = 1 << 11,
Applied = 1 << 12,
Damage = 1 << 13,
Attack = 1 << 14,
Defenses = 1 << 15,
ManaConversion = 1 << 16,
Spells = 1 << 17,
Wield = 1 << 18,
Activation = 1 << 19,
Difficulty = 1 << 20,
Craft = 1 << 21,
Protections = 1 << 22,
Ratings = 1 << 23,
Keyring = 1 << 24,
}
/// <summary>Persisted item-info options (JSON fields; see RynthAiJsonContext IncludeFields).</summary>
public sealed class MagItemInfoSettings
{
/// <summary>Spell list modes for <see cref="SpellMode"/>.</summary>
public const int SpellModeMag = 0, SpellModeAll = 1;
/// <summary>Mouse triggers for <see cref="ClickTrigger"/>.</summary>
public const int ClickOff = 0, ClickLeft = 1, ClickRight = 2;
/// <summary>Output layouts for <see cref="Layout"/>.</summary>
public const int LayoutOneLine = 0, LayoutPetLines = 1;
/// <summary><see cref="DetailChatType"/> value meaning "use <see cref="ChatType"/>".</summary>
public const int SameAsHeader = -1;
// ── When to print ────────────────────────────────────────────────────────
/// <summary>Print automatically when an item is selected.</summary>
public bool OnSelect;
/// <summary>
/// Print the selected item after a left (<see cref="ClickLeft"/>) or right (<see cref="ClickRight"/>)
/// click in the game world / inventory — also re-prints an item that was already selected.
/// </summary>
public int ClickTrigger = ClickOff;
/// <summary>On-select class filters (manual /ra iteminfo ignores them).</summary>
public bool OnSelectWeapons = true;
public bool OnSelectArmor = true;
public bool OnSelectJewelry = true;
public bool OnSelectOther = true;
/// <summary>Seconds to wait for an ID before printing partial data.</summary>
public float IdTimeoutSec = 3f;
// ── What to print ────────────────────────────────────────────────────────
/// <summary><see cref="MagItemInfoField"/> bits that are NOT printed.</summary>
public int HiddenFields;
/// <summary>Bit i set = <see cref="MagItemInfoCatalog.Ratings"/>[i] not printed.</summary>
public int HiddenRatings;
/// <summary>Append ", Value N, BU N".</summary>
public bool ShowValueAndBurden;
/// <summary><see cref="SpellModeMag"/> (Mag filter) or <see cref="SpellModeAll"/>.</summary>
public int SpellMode = SpellModeMag;
/// <summary>Cap for the "all spells" list.</summary>
public int MaxListedSpells = 26;
// ── How to print ─────────────────────────────────────────────────────────
/// <summary><see cref="LayoutPetLines"/> (pet-roster style lines) or <see cref="LayoutOneLine"/> (Mag one-liner).</summary>
public int Layout = LayoutPetLines;
/// <summary>AC chat type passed to WriteToChat (selects the chat colour / window).</summary>
public int ChatType = 1;
/// <summary>Chat type for pet-style lines 2+, or <see cref="SameAsHeader"/>.</summary>
public int DetailChatType = SameAsHeader;
/// <summary>Text put in front of every line.</summary>
public string Prefix = "[RynthAi] ";
/// <summary>Item Info settings window open.</summary>
public bool ShowWindow;
public bool IsHidden(MagItemInfoField f) => (HiddenFields & (int)f) != 0;
public void SetHidden(MagItemInfoField f, bool hidden) =>
HiddenFields = hidden ? HiddenFields | (int)f : HiddenFields & ~(int)f;
public bool IsRatingHidden(int index) => (HiddenRatings & (1 << index)) != 0;
public void SetRatingHidden(int index, bool hidden) =>
HiddenRatings = hidden ? HiddenRatings | (1 << index) : HiddenRatings & ~(1 << index);
/// <summary>Clamp values a hand-edited or older profile could carry out of range.</summary>
public void Sanitize()
{
if (float.IsNaN(IdTimeoutSec) || IdTimeoutSec < 0.5f) IdTimeoutSec = 0.5f;
if (IdTimeoutSec > 15f) IdTimeoutSec = 15f;
if (SpellMode is not (SpellModeMag or SpellModeAll)) SpellMode = SpellModeMag;
MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64);
if (ChatType < 0 || ChatType > 31) ChatType = 1;
if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader;
if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff;
if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines;
Prefix ??= string.Empty;
if (Prefix.Length > 32) Prefix = Prefix[..32];
}
/// <summary>Back to first-run defaults (window stays open).</summary>
public void ResetToDefaults()
{
var d = new MagItemInfoSettings();
OnSelect = d.OnSelect;
ClickTrigger = d.ClickTrigger;
Layout = d.Layout;
DetailChatType = d.DetailChatType;
OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor;
OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther;
IdTimeoutSec = d.IdTimeoutSec;
HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings;
ShowValueAndBurden = d.ShowValueAndBurden;
SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells;
ChatType = d.ChatType; Prefix = d.Prefix;
}
}
/// <summary>Labels for the settings window and the /ra iteminfo field|rating commands.</summary>
public static class MagItemInfoCatalog
{
public readonly record struct FieldInfo(MagItemInfoField Field, string Label, string Example);
public readonly record struct RatingInfo(uint StatId, string Tag, string Name);
/// <summary>In print order.</summary>
public static readonly FieldInfo[] Fields =
{
new(MagItemInfoField.Material, "Material", "Gold Ornate Long Sword"),
new(MagItemInfoField.TypeMastery, "Damage type / mastery","(Slash Sword)"),
new(MagItemInfoField.Set, "Equipment set", "Noble Relic Set"),
new(MagItemInfoField.ArmorLevel, "Armor level", "AL 650"),
new(MagItemInfoField.Imbues, "Imbues", "CS, AR, FireRend"),
new(MagItemInfoField.ArmorCleave, "Armor cleaving", "AC"),
new(MagItemInfoField.CritStats, "Crit mult / freq", "CritMult (1.5), CritFreq (0.15)"),
new(MagItemInfoField.Splits, "Split arrows", "Splits (2)"),
new(MagItemInfoField.Range, "Missile range", "Range 120yd"),
new(MagItemInfoField.CleaveMultiStrike, "Cleaving / Multi-Strike", "Cleaving"),
new(MagItemInfoField.Slayer, "Slayer", "Undead Slayer"),
new(MagItemInfoField.Tinks, "Tinks", "Tinks 4"),
new(MagItemInfoField.Applied, "Applied materials", "Applied: Steel x2"),
new(MagItemInfoField.Damage, "Damage", "152.48-236, 0.35v, +18, +10%"),
new(MagItemInfoField.Attack, "Attack bonus", "+18%a"),
new(MagItemInfoField.Defenses, "Defense bonuses", "12%md, 1.5%mgc.d, 1%msl.d"),
new(MagItemInfoField.ManaConversion, "Mana conversion", "6%mc"),
new(MagItemInfoField.Spells, "Spells", "Legendary Blood Thirst"),
new(MagItemInfoField.Wield, "Wield requirements", "Wield Lvl 180, Heavy Weapons 375"),
new(MagItemInfoField.Activation, "Activation / use reqs","Lvl 50, Melee Defense 300 to Activate"),
new(MagItemInfoField.Difficulty, "Arcane difficulty", "Diff 270"),
new(MagItemInfoField.Craft, "Craft / salvage work", "Craft 8"),
new(MagItemInfoField.Protections, "Protections (unenchantable armor)", "[1.0/0.8/1.2/...]"),
new(MagItemInfoField.Ratings, "Ratings", "[D 3, CD 2]"),
new(MagItemInfoField.Keyring, "Keyring keys / uses", "Keys: 3, Uses: 25"),
};
/// <summary>ACE gear ratings (PropertyInt 370–389) in Mag print order.</summary>
public static readonly RatingInfo[] Ratings =
{
new(370, "D", "Damage"),
new(371, "DR", "Damage Resist"),
new(372, "C", "Crit"),
new(374, "CD", "Crit Damage"),
new(373, "CR", "Crit Resist"),
new(375, "CDR", "Crit Damage Resist"),
new(376, "HB", "Healing Boost"),
new(379, "V", "Vitality"),
new(377, "NR", "Nether Resist"),
new(378, "LR", "Life Resist"),
new(383, "PKD", "PK Damage"),
new(384, "PKDR", "PK Damage Resist"),
new(388, "OP", "Overpower"),
new(389, "OPR", "Overpower Resist"),
};
/// <summary>Labels for <see cref="MagItemInfoSettings.ClickTrigger"/>, indexed by value.</summary>
public static readonly string[] ClickTriggers = { "Off", "Left mouse click", "Right mouse click" };
/// <summary>Labels for <see cref="MagItemInfoSettings.Layout"/>, indexed by value.</summary>
public static readonly string[] Layouts = { "One line (Mag-Tools)", "Pet-style lines" };
/// <summary>Common AC chat types for the colour picker (value passed to WriteToChat).</summary>
public static readonly (int Type, string Label)[] ChatTypes =
{
(0, "0 - Broadcast"),
(1, "1 - RynthAi default"),
(2, "2 - Speech"),
(3, "3 - Tell"),
(4, "4 - Outgoing tell"),
(5, "5 - System"),
(6, "6 - Combat"),
(7, "7 - Magic"),
(8, "8 - Channels"),
(10, "10 - Social"),
(12, "12 - Emote"),
(13, "13 - Advancement"),
(15, "15 - Help"),
(16, "16 - Appraisal"),
(17, "17 - Spellcasting"),
(18, "18 - Allegiance"),
(19, "19 - Fellowship"),
(21, "21 - Combat (enemy)"),
(22, "22 - Combat (self)"),
(24, "24 - Craft"),
(25, "25 - Salvaging"),
};
/// <summary>Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery").</summary>
public static bool TryFindField(string key, out MagItemInfoField field)
{
foreach (var f in Fields)
{
if (f.Field.ToString().Equals(key, StringComparison.OrdinalIgnoreCase)
|| f.Label.Replace(" ", string.Empty).StartsWith(key, StringComparison.OrdinalIgnoreCase))
{
field = f.Field;
return true;
}
}
field = MagItemInfoField.None;
return false;
}
/// <summary>Rating index by tag ("CD") or name ("critdamage"), case-insensitive.</summary>
public static int FindRating(string key)
{
for (int i = 0; i < Ratings.Length; i++)
{
if (Ratings[i].Tag.Equals(key, StringComparison.OrdinalIgnoreCase)
|| Ratings[i].Name.Replace(" ", string.Empty).Equals(key, StringComparison.OrdinalIgnoreCase))
return i;
}
return -1;
}
}

View file

@ -1,159 +0,0 @@
// MagItemInfoTables.cs — name tables for the Mag-style item info line (MagItemDescriber).
// Skill / mastery / set / material names follow UtilityBelt ub-IT (Lib/ItemInfoHelper/Dictionaries.cs,
// itself from Mag-Tools / Alinco / VTank). Slayer names use the full ACE CreatureType enum instead of
// ub-IT's 17-entry subset so every slayer resolves.
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
internal static class MagItemInfoTables
{
/// <summary>Skill id → name (wield / activation / summoning requirements).</summary>
public static readonly Dictionary<int, string> Skills = new()
{
{ 0x01, "Axe" }, { 0x02, "Bow" }, { 0x03, "Crossbow" }, { 0x04, "Dagger" }, { 0x05, "Mace" },
{ 0x06, "Melee Defense" }, { 0x07, "Missile Defense" }, { 0x08, "Sling" }, { 0x09, "Spear" },
{ 0x0A, "Staff" }, { 0x0B, "Sword" }, { 0x0C, "Thrown Weapons" }, { 0x0D, "Unarmed Combat" },
{ 0x0E, "Arcane Lore" }, { 0x0F, "Magic Defense" }, { 0x10, "Mana Conversion" },
{ 0x12, "Item Tinkering" }, { 0x13, "Assess Person" }, { 0x14, "Deception" }, { 0x15, "Healing" },
{ 0x16, "Jump" }, { 0x17, "Lockpick" }, { 0x18, "Run" }, { 0x1B, "Assess Creature" },
{ 0x1C, "Weapon Tinkering" }, { 0x1D, "Armor Tinkering" }, { 0x1E, "Magic Item Tinkering" },
{ 0x1F, "Creature Enchantment" }, { 0x20, "Item Enchantment" }, { 0x21, "Life Magic" },
{ 0x22, "War Magic" }, { 0x23, "Leadership" }, { 0x24, "Loyalty" }, { 0x25, "Fletching" },
{ 0x26, "Alchemy" }, { 0x27, "Cooking" }, { 0x28, "Salvaging" }, { 0x29, "Two Handed Combat" },
{ 0x2A, "Gearcraft" }, { 0x2B, "Void" }, { 0x2C, "Heavy Weapons" }, { 0x2D, "Light Weapons" },
{ 0x2E, "Finesse Weapons" }, { 0x2F, "Missile Weapons" }, { 0x30, "Shield" }, { 0x31, "Dual Wield" },
{ 0x32, "Recklessness" }, { 0x33, "Sneak Attack" }, { 0x34, "Dirty Fighting" }, { 0x35, "Challenge" },
{ 0x36, "Summoning" },
};
/// <summary>ACE PropertyInt.WeaponType (353) → mastery name.</summary>
public static readonly Dictionary<int, string> Masteries = new()
{
{ 1, "Unarmed Weapon" }, { 2, "Sword" }, { 3, "Axe" }, { 4, "Mace" }, { 5, "Spear" }, { 6, "Dagger" },
{ 7, "Staff" }, { 8, "Bow" }, { 9, "Crossbow" }, { 10, "Thrown" }, { 11, "Two Handed Combat" }, { 12, "Wand" },
};
/// <summary>ACE PropertyInt.MaterialType (131) → material name.</summary>
public static readonly Dictionary<int, string> Materials = new()
{
{ 1, "Ceramic" }, { 2, "Porcelain" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" }, { 7, "Velvet" },
{ 8, "Wool" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" }, { 13, "Aquamarine" },
{ 14, "Azurite" }, { 15, "Bag of Abyssal-Touched" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" },
{ 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" },
{ 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" },
{ 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smokey Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" },
{ 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" },
{ 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" },
{ 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" },
{ 55, "Reed Shark Hide" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" },
{ 61, "Iron" }, { 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 66, "Alabaster" },
{ 67, "Granite" }, { 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" },
{ 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
};
/// <summary>ACE PropertyInt.EquipmentSetId (265) → set name.</summary>
public static readonly Dictionary<int, string> EquipmentSets = BuildSets();
/// <summary>ACE CreatureType enum, index = value (0..101). Used for SlayerCreatureType (166).</summary>
private static readonly string[] CreatureTypes =
{
"Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker",
"Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo",
"Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus",
"Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman",
"Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny",
"Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion",
"Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun",
"Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental",
"Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken",
"Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", "Target",
"Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", "Remoran", "Swarm",
"Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", "Paradox Olthoi", "Harvest",
"Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", "Gear Knight", "Gurog", "A'nekshay",
};
/// <summary>Slayer creature name, or null for 0 / unknown values.</summary>
public static string? CreatureTypeName(int value) =>
value > 0 && value < CreatureTypes.Length ? CreatureTypes[value] : null;
/// <summary>
/// ACE DamageType flags (45) → "Slash", "Slash/Pierce", "Lightning" … Empty when no known bit is set.
/// </summary>
public static string DamageTypeName(int flags)
{
if (flags <= 0) return string.Empty;
var sb = new StringBuilder();
void Add(int bit, string name)
{
if ((flags & bit) == 0) return;
if (sb.Length > 0) sb.Append('/');
sb.Append(name);
}
Add(0x001, "Slash");
Add(0x002, "Pierce");
Add(0x004, "Bludgeon");
Add(0x008, "Cold");
Add(0x010, "Fire");
Add(0x020, "Acid");
Add(0x040, "Lightning");
Add(0x400, "Nether");
return sb.ToString();
}
private static Dictionary<int, string> BuildSets()
{
var d = new Dictionary<int, string>
{
{ 2, "Test" }, { 4, "Carraida's Benediction" }, { 5, "Noble Relic Set" }, { 6, "Ancient Relic Set" },
{ 7, "Relic Alduressa Set" }, { 8, "Shou-jen Set" }, { 9, "Empyrean Rings Set" },
{ 10, "Arm, Mind, Heart Set" }, { 11, "Coat of the Perfect Light Set" },
{ 12, "Leggings of Perfect Light Set" }, { 13, "Soldier's Set" }, { 14, "Adept's Set" },
{ 15, "Archer's Set" }, { 16, "Defender's Set" }, { 17, "Tinker's Set" }, { 18, "Crafter's Set" },
{ 19, "Hearty Set" }, { 20, "Dexterous Set" }, { 21, "Wise Set" }, { 22, "Swift Set" },
{ 23, "Hardened Set" }, { 24, "Reinforced Set" }, { 25, "Interlocking Set" },
{ 26, "Flame Proof Set" }, { 27, "Acid Proof Set" }, { 28, "Cold Proof Set" },
{ 29, "Lightning Proof Set" }, { 30, "Dedication Set" }, { 31, "Gladiatorial Clothing Set" },
{ 32, "Ceremonial Clothing" }, { 33, "Protective Clothing" }, { 34, "Noobie Armor" },
{ 35, "Sigil of Defense" }, { 36, "Sigil of Destruction" }, { 37, "Sigil of Fury" },
{ 38, "Sigil of Growth" }, { 39, "Sigil of Vigor" }, { 40, "Heroic Protector Set" },
{ 41, "Heroic Destroyer Set" }, { 42, "Olthoi Armor D Red" }, { 43, "Olthoi Armor C Rat" },
{ 44, "Olthoi Armor C Red" }, { 45, "Olthoi Armor D Rat" }, { 46, "Upgraded Relic Alduressa Set" },
{ 47, "Upgraded Ancient Relic Set" }, { 48, "Upgraded Noble Relic Set" },
{ 49, "Weave of Alchemy" }, { 50, "Weave of Arcane Lore" }, { 51, "Weave of Armor Tinkering" },
{ 52, "Weave of Assess Person" }, { 53, "Weave of Light Weapons" }, { 54, "Weave of Missile Weapons" },
{ 55, "Weave of Cooking" }, { 56, "Weave of Creature Enchantment" }, { 57, "Weave of Missile Weapons" },
{ 58, "Weave of Finesse" }, { 59, "Weave of Deception" }, { 60, "Weave of Fletching" },
{ 61, "Weave of Healing" }, { 62, "Weave of Item Enchantment" }, { 63, "Weave of Item Tinkering" },
{ 64, "Weave of Leadership" }, { 65, "Weave of Life Magic" }, { 66, "Weave of Loyalty" },
{ 67, "Weave of Light Weapons" }, { 68, "Weave of Magic Defense" },
{ 69, "Weave of Magic Item Tinkering" }, { 70, "Weave of Mana Conversion" },
{ 71, "Weave of Melee Defense" }, { 72, "Weave of Missile Defense" }, { 73, "Weave of Salvaging" },
{ 74, "Weave of Light Weapons" }, { 75, "Weave of Light Weapons" }, { 76, "Weave of Heavy Weapons" },
{ 77, "Weave of Missile Weapons" }, { 78, "Weave of Two Handed Combat" }, { 79, "Weave of Light Weapons" },
{ 80, "Weave of Void Magic" }, { 81, "Weave of War Magic" }, { 82, "Weave of Weapon Tinkering" },
{ 83, "Weave of Assess Creature" }, { 84, "Weave of Dirty Fighting" }, { 85, "Weave of Dual Wield" },
{ 86, "Weave of Recklessness" }, { 87, "Weave of Shield" }, { 88, "Weave of Sneak Attack" },
{ 89, "Ninja_New" }, { 90, "Weave of Summoning" }, { 91, "Shrouded Soul" }, { 92, "Darkened Mind" },
{ 93, "Clouded Spirit" }, { 130, "Shimmering Shadows" }, { 131, "Brown Society Locket" },
{ 132, "Yellow Society Locket" }, { 133, "Red Society Band" }, { 134, "Green Society Band" },
{ 135, "Purple Society Band" }, { 136, "Blue Society Band" }, { 137, "Gauntlet Garb" },
{ 138, "Paragon" }, { 139, "Paragon" }, { 140, "Paragon" },
};
// 94..129: Minor / Major / Blackfire × Stinging / Sparking / Smoldering / Shivering ×
// Shrouded Soul / Darkened Mind / Clouded Spirit (same order as the VTank set list).
string[] tiers = { "Minor", "Major", "Blackfire" };
string[] souls = { "Shrouded Soul", "Darkened Mind", "Clouded Spirit" };
string[] elements = { "Stinging", "Sparking", "Smoldering", "Shivering" };
int id = 94;
foreach (string tier in tiers)
foreach (string soul in souls)
foreach (string element in elements)
d[id++] = $"{tier} {element} {soul}";
return d;
}
}

View file

@ -0,0 +1,27 @@
using System;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>
/// Items RynthAi selects by itself (the looter picking an item up, a meta's selectitem), so the
/// selection-change handler can tell them from the player's own clicks: Item Info on select
/// prints only for the player's. <see cref="Mark"/> goes right before Host.SelectItem.
/// </summary>
internal static class SelfSelect
{
/// <summary>A selection change this soon after <see cref="Mark"/>, for the same id, is ours.</summary>
internal const long WindowMs = 2000;
internal static Func<long> Clock = () => Environment.TickCount64;
private static uint _id;
private static long _at;
internal static void Mark(uint id)
{
_at = Clock();
_id = id;
}
internal static bool IsOurs(uint id) => id != 0 && id == _id && Clock() - _at <= WindowMs;
}

View file

@ -15,6 +15,7 @@ internal sealed class LegacyAdvancedSettingsUi
private string? _serverNamesEdit;
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
public LegacyAdvancedSettingsUi(LegacyUiSettings settings)
@ -214,6 +215,14 @@ internal sealed class LegacyAdvancedSettingsUi
catch { return false; }
}
/// <summary>One cell of the Protections and Banes grid: ticked = cast it.</summary>
private void BuffToggle((string Buff, string Label) toggle)
{
bool on = !_settings.IsBuffDisabled(toggle.Buff);
if (ImGui.Checkbox($"{toggle.Label}##buff_{toggle.Buff}", ref on))
_settings.SetBuffEnabled(toggle.Buff, on);
}
private void RenderTabContent(int tabIndex)
{
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
@ -295,6 +304,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Patrol On Login", ref _settings.PatrolOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
ImGui.Checkbox("Escape Acid and Lava", ref _settings.EscapeHazards);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose.");
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
ImGui.Separator();
@ -430,6 +442,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam At", ref _settings.RestamAt, 0, 100);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Re-stam To", ref _settings.RestamTo, 0, 100);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Once a recharge starts under Re-stam At, keep recharging until stamina reaches this %.\n0 = one recharge, as before.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt("Get Mana At", ref _settings.GetManaAt, 0, 100);
ImGui.Spacing();
@ -527,12 +542,12 @@ internal sealed class LegacyAdvancedSettingsUi
"Below 200ms may cause fizzles or dropped casts on laggy servers.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 250, 5000);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Delay between offensive (war/void) COMBAT casts only.\n" +
"Spacing casts ~1-2s (1500ms default) stops back-to-back\n" +
"\"You're too busy!\" refusals that drop casts and cost kills.\n" +
"Least time between offensive (war/void) COMBAT casts at one target.\n" +
"The next cast also waits until the last one is finished (the server's\n" +
"answer and the casting animation), so 0 = cast again as soon as it is.\n" +
"Does NOT affect buffing speed.");
ImGui.Spacing();
@ -546,6 +561,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.InputInt("Min Blast Targets", ref _settings.MinBlastTargets);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If this many monsters are within ring range, ring spells are used instead of arc/bolt/streak.");
ImGui.InputInt("Wall Range (0 = off)", ref _settings.WallRange);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Monster rules with Wall on cast their element's wall spell when enough monsters\n" +
"are within this many yards in the wall's path toward the target.\n" +
"The character turns to face the target first. 0 = no walls.");
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
ImGui.Spacing();
ImGui.Separator();
@ -599,7 +620,7 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
_settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Follow stops this close to its leader; the nav marker ring shows it.");
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Up to 2 nav walks right up to each point before turning (tight dungeons); bigger values round corners. Follow stops this close to its leader; the nav marker ring shows it.");
ImGui.Spacing();
ImGui.Text("Nav Marker Display");
@ -619,6 +640,11 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Show Terrain Passability", ref _settings.ShowTerrainPassability);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Highlight impassable terrain triangles in red.");
ImGui.SetNextItemWidth(160);
ImGui.Combo("Waypoint Labels", ref _settings.NavLabelMode, NavLabelModeNames, NavLabelModeNames.Length);
ImGui.Checkbox("Guide Line", ref _settings.NavGuideLine);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("A line from your character to the waypoint nav is heading for.");
ImGui.Spacing();
ImGui.Separator();
@ -689,7 +715,7 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.InputFloat("Lookahead (yd)", ref _settings.NavLookaheadYards, 0.5f, 1f, "%.1f");
if (_settings.NavLookaheadYards < 0f) _settings.NavLookaheadYards = 0f;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to round corners. The nav point reach limits it to 2 yd per yard of reach over 1 yd (no rounding up to a 2 yd reach), never more than this. 0 = off (aim straight at each waypoint).");
ImGui.SetNextItemWidth(80);
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
@ -753,6 +779,31 @@ internal sealed class LegacyAdvancedSettingsUi
"For servers with buff augments, where your own cast is stronger or\n" +
"lasts longer. On by default: on retail it costs a few extra casts.");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Protections and Banes");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Untick a protection or bane to stop the bot casting it.\n" +
"Unticked buffs are skipped and never hold the bot in Buffing.\n" +
"All on by default.");
if (ImGui.BeginTable("##protsBanes", 2, ImGuiTableFlags.SizingStretchSame))
{
ImGui.TableSetupColumn("Protections");
ImGui.TableSetupColumn("Banes");
ImGui.TableHeadersRow();
int rows = Math.Max(BuffManager.ToggleProtections.Length, BuffManager.ToggleBanes.Length);
for (int i = 0; i < rows; i++)
{
ImGui.TableNextRow();
ImGui.TableSetColumnIndex(0);
if (i < BuffManager.ToggleProtections.Length) BuffToggle(BuffManager.ToggleProtections[i]);
ImGui.TableSetColumnIndex(1);
if (i < BuffManager.ToggleBanes.Length) BuffToggle(BuffManager.ToggleBanes[i]);
}
ImGui.EndTable();
}
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
@ -802,6 +853,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoOnSelect);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Selecting an item prints its details to chat (/ra iteminfo).");
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");

View file

@ -60,16 +60,16 @@ internal sealed partial class LegacyDashboardRenderer
// escaped the snapshot poll's reverse-P/Invoke boundary it fail-fasted the
// NativeAOT runtime. Copy-under-lock on read; lock the Clear+AddRange swap.
private readonly object _profileListsLock = new();
private readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
private readonly string _lootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
private readonly string _metaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
private readonly string _navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
private readonly string _lootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
private readonly string _metaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
// Profiles are kept per server: SettingsProfiles\<server>\<character> and
// MonsterProfiles\<server>\<character>.json, the server being the world name
// the server sends at login. Before 2026-09-28 every server shared
// SettingsProfiles\ACEmulator, so the same character name on two servers
// shared one profile; that folder is still used when no name is known.
private const string ProfilesBase = @"C:\Games\RynthSuite\RynthAi\SettingsProfiles";
private const string MonstersBase = @"C:\Games\RynthSuite\RynthAi\MonsterProfiles";
private static readonly string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
private static readonly string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles");
private const string LegacyServerFolder = "ACEmulator";
private string _serverFolder = LegacyServerFolder;
private string _settingsRoot => Path.Combine(ProfilesBase, _serverFolder);
@ -113,7 +113,8 @@ internal sealed partial class LegacyDashboardRenderer
private DateTime _sessionStartUtc = DateTime.UtcNow;
private long _sessionKills; // Interlocked: incremented on the pump thread, read in the snapshot
private double _killsPerHour;
private long _lastKillTicks; // DateTime.UtcNow.Ticks of the last kill (0 = none yet this session)
/// <summary>The plugin's kill clock (secsSinceLastKill); set once at plugin init.</summary>
internal KillClock? KillClock { get; set; }
// volatile: written on the pump thread (SetFreeSlots/SetComponentCounts), read on the snapshot-poll
// thread (BuildSnapshotJson). x86 int writes are atomic but give no visibility guarantee — without
// volatile the reader can see a stale value indefinitely. (_sessionKills uses Interlocked for the same reason.)
@ -950,6 +951,7 @@ internal sealed partial class LegacyDashboardRenderer
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec,
GiveQueueIntervalMs = s.GiveQueueIntervalMs,
T11ItemAugsOverride = s.T11ItemAugsOverride,
// Recharge
HealAt = s.HealAt,
UsePotions = s.UsePotions,
@ -966,6 +968,7 @@ internal sealed partial class LegacyDashboardRenderer
StopLootingWhenPackFull = s.StopLootingWhenPackFull,
StopMacroWhenPackFull = s.StopMacroWhenPackFull,
RestamAt = s.RestamAt,
RestamTo = s.RestamTo,
GetManaAt = s.GetManaAt,
TopOffHP = s.TopOffHP,
TopOffStam = s.TopOffStam,
@ -989,6 +992,8 @@ internal sealed partial class LegacyDashboardRenderer
MinRingTargets = s.MinRingTargets,
BlastRange = s.BlastRange,
MinBlastTargets = s.MinBlastTargets,
WallRange = s.WallRange,
MinWallTargets = s.MinWallTargets,
MinSkillLevelTier1 = s.MinSkillLevelTier1,
MinSkillLevelTier2 = s.MinSkillLevelTier2,
MinSkillLevelTier3 = s.MinSkillLevelTier3,
@ -1012,6 +1017,8 @@ internal sealed partial class LegacyDashboardRenderer
NavHeightOffset = s.NavHeightOffset,
NavSlopeSink = s.NavSlopeSink,
ShowTerrainPassability = s.ShowTerrainPassability,
NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode),
NavGuideLine = s.NavGuideLine,
OpenDoors = s.OpenDoors,
OpenDoorRange = s.OpenDoorRange,
AutoUnlockDoors = s.AutoUnlockDoors,
@ -1037,6 +1044,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
DisabledBuffs = new List<string>(s.DisabledBuffs),
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
@ -1058,7 +1066,9 @@ internal sealed partial class LegacyDashboardRenderer
LootJumpHeight = s.LootJumpHeight,
LootOwnership = s.LootOwnership,
LootOwnCorpse = s.LootOwnCorpse,
EscapeHazards = s.EscapeHazards,
TravelToOwnCorpse = s.TravelToOwnCorpse,
ItemInfoOnSelect = s.ItemInfoOnSelect,
EnableAutostack = s.EnableAutostack,
ReadUnknownScrolls = s.ReadUnknownScrolls,
EnableCombineSalvage = s.EnableCombineSalvage,
@ -1091,7 +1101,6 @@ internal sealed partial class LegacyDashboardRenderer
OffhandDefault = s.OffhandDefault,
PreferDualWield = s.PreferDualWield,
EnableGroundLoot = s.EnableGroundLoot,
ItemInfoOnSelect = s.ItemInfoSettings.OnSelect,
// Diagnostics (per PC, RynthLog)
DiagDebugToChat = RynthLog.DebugToChat,
DiagFileLogAll = RynthLog.FileLogAll,
@ -1163,6 +1172,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
s.T11ItemAugsOverride = p.T11ItemAugsOverride ?? -1;
// Recharge
s.HealAt = p.HealAt;
s.UsePotions = p.UsePotions;
@ -1179,6 +1189,7 @@ internal sealed partial class LegacyDashboardRenderer
s.StopLootingWhenPackFull = p.StopLootingWhenPackFull;
s.StopMacroWhenPackFull = p.StopMacroWhenPackFull;
s.RestamAt = p.RestamAt;
s.RestamTo = p.RestamTo ?? 0;
s.GetManaAt = p.GetManaAt;
s.TopOffHP = p.TopOffHP;
s.TopOffStam = p.TopOffStam;
@ -1197,11 +1208,13 @@ internal sealed partial class LegacyDashboardRenderer
s.PetMinMonsters = p.PetMinMonsters;
// Spell Combat
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
s.AttackSpellIntervalMs = p.AttackSpellIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
s.MinRingTargets = p.MinRingTargets;
s.BlastRange = p.BlastRange;
s.MinBlastTargets = p.MinBlastTargets;
if (p.WallRange is int wallRange) s.WallRange = wallRange; // null = an engine without walls
if (p.MinWallTargets is int minWall) s.MinWallTargets = minWall;
s.MinSkillLevelTier1 = p.MinSkillLevelTier1;
s.MinSkillLevelTier2 = p.MinSkillLevelTier2;
s.MinSkillLevelTier3 = p.MinSkillLevelTier3;
@ -1225,6 +1238,8 @@ internal sealed partial class LegacyDashboardRenderer
s.NavHeightOffset = p.NavHeightOffset;
s.NavSlopeSink = p.NavSlopeSink;
s.ShowTerrainPassability = p.ShowTerrainPassability;
if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode);
if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine;
s.OpenDoors = p.OpenDoors;
s.OpenDoorRange = p.OpenDoorRange;
s.AutoUnlockDoors = p.AutoUnlockDoors;
@ -1250,6 +1265,7 @@ internal sealed partial class LegacyDashboardRenderer
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List<string>(disabledBuffs); // absent = unchanged
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
@ -1267,8 +1283,10 @@ internal sealed partial class LegacyDashboardRenderer
s.LootJumpEnabled = p.LootJumpEnabled;
s.LootJumpHeight = p.LootJumpHeight;
s.LootOwnership = p.LootOwnership;
if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged
s.EnableAutostack = p.EnableAutostack;
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
s.EnableCombineSalvage = p.EnableCombineSalvage;
@ -1302,7 +1320,6 @@ internal sealed partial class LegacyDashboardRenderer
if (p.OffhandDefault is string od && OffhandRules.TryParse(od, out var odMode)) s.OffhandDefault = OffhandRules.SettingValue(odMode);
if (p.PreferDualWield is bool pdw) s.PreferDualWield = pdw;
s.EnableGroundLoot = p.EnableGroundLoot;
s.ItemInfoSettings.OnSelect = p.ItemInfoOnSelect;
// Diagnostics: each setter rewrites diagnostics.json, so only touch what changed.
if (p.DiagDebugToChat != RynthLog.DebugToChat) RynthLog.DebugToChat = p.DiagDebugToChat;
if (p.DiagFileLogAll != RynthLog.FileLogAll) RynthLog.FileLogAll = p.DiagFileLogAll;
@ -1640,6 +1657,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.StopLootingWhenPackFull = tmp.StopLootingWhenPackFull;
dst.StopMacroWhenPackFull = tmp.StopMacroWhenPackFull;
dst.RestamAt = tmp.RestamAt;
dst.RestamTo = tmp.RestamTo;
dst.GetManaAt = tmp.GetManaAt;
dst.TopOffHP = tmp.TopOffHP;
dst.TopOffStam = tmp.TopOffStam;
@ -1654,6 +1672,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.MinRingTargets = tmp.MinRingTargets;
dst.BlastRange = tmp.BlastRange;
dst.MinBlastTargets = tmp.MinBlastTargets;
dst.WallRange = tmp.WallRange;
dst.MinWallTargets = tmp.MinWallTargets;
dst.FollowNavMin = tmp.FollowNavMin;
dst.NavRingThickness = tmp.NavRingThickness;
dst.NavLineThickness = tmp.NavLineThickness;
@ -1675,13 +1695,16 @@ internal sealed partial class LegacyDashboardRenderer
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
dst.LootOwnership = tmp.LootOwnership;
dst.LootOwnCorpse = tmp.LootOwnCorpse;
dst.EscapeHazards = tmp.EscapeHazards;
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect;
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlacklistAttempts = tmp.BlacklistAttempts;
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
@ -1780,7 +1803,10 @@ internal sealed partial class LegacyDashboardRenderer
dst.FeatureServerNames = tmp.FeatureServerNames ?? new(IltHub.ServerFeatureGate.DefaultServerNames);
dst.ForceServerFeatures = tmp.ForceServerFeatures;
dst.ShowTerrainPassability = tmp.ShowTerrainPassability;
dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode);
dst.NavGuideLine = tmp.NavGuideLine;
dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs;
dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride;
dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs;
dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs;
dst.EmbeddedNavs = tmp.EmbeddedNavs;
@ -1912,15 +1938,13 @@ internal sealed partial class LegacyDashboardRenderer
{
_sessionStartUtc = DateTime.UtcNow;
System.Threading.Interlocked.Exchange(ref _sessionKills, 0);
System.Threading.Interlocked.Exchange(ref _lastKillTicks, 0);
}
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour
/// and the "time since last kill" liveness signal.
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour.
/// The "time since last kill" signal is the plugin's KillClock.
public void RecordKill()
{
System.Threading.Interlocked.Increment(ref _sessionKills);
System.Threading.Interlocked.Exchange(ref _lastKillTicks, DateTime.UtcNow.Ticks);
}
/// Pushed from the plugin tick (it owns the inventory cache) — main-pack empty slots. -1 = unknown.
@ -2108,6 +2132,43 @@ internal sealed partial class LegacyDashboardRenderer
_selectedNavIdx = sel;
}
private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp;
private long _nextNavFolderCheckMs;
/// <summary>
/// Lists a folder again when it changed since the last look (a file added, removed or renamed:
/// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings
/// profile saved), so its picker shows it without a relog or a reload. NavProfiles since
/// 2026-10; LootProfiles, MetaFiles and the character's settings profiles since 2026-10-08
/// (a loot profile copied in didn't show until a hot reload). One folder time check each every
/// 3 s. Plugin tick.
/// </summary>
public void TickNavFolder()
{
long now = Environment.TickCount64;
if (now < _nextNavFolderCheckMs) return;
_nextNavFolderCheckMs = now + 3000;
if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles();
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
}
/// <summary>True when <paramref name="folder"/>'s write time moved since the last call (never on
/// the first look, which only records it: the lists were built at load).</summary>
private static bool FolderChanged(string? folder, ref DateTime stamp)
{
try
{
DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue;
if (now == stamp) return false;
bool first = stamp == default;
stamp = now;
return !first;
}
catch { return false; }
}
/// <summary>Save button and /ra nav save [name]. Returns the chat line.</summary>
public string SaveRoute(string? name)
{
@ -2563,11 +2624,8 @@ internal sealed partial class LegacyDashboardRenderer
// (kill counter + inventory cache); the rest of the player stats are engine top-level.
AppendFloat(sb, "killsPerHour", (float)_killsPerHour); sb.Append(',');
AppendInt(sb, "sessionKills", (int)System.Threading.Interlocked.Read(ref _sessionKills)); sb.Append(',');
long lastKillTicks = System.Threading.Interlocked.Read(ref _lastKillTicks);
int secsSinceLastKill = lastKillTicks == 0
? -1
: (int)Math.Clamp((DateTime.UtcNow - new DateTime(lastKillTicks, DateTimeKind.Utc)).TotalSeconds, 0, int.MaxValue);
AppendInt(sb, "secsSinceLastKill", secsSinceLastKill); sb.Append(',');
// -1 before the first kill this session (the plugin's KillClock, reset at login).
AppendInt(sb, "secsSinceLastKill", KillClock?.SecondsSinceKillOnly() ?? -1); sb.Append(',');
AppendInt(sb, "freeSlots", _freeSlots); sb.Append(',');
// D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning).
AppendInt(sb, "scanTotal", _scanTotal); sb.Append(',');
@ -2776,7 +2834,7 @@ internal sealed partial class LegacyDashboardRenderer
// ── Meta bridge ───────────────────────────────────────────────────────────
private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
// Result of the last set_source, reported in BuildMetaJson (under MetaRulesLock).
private long _metaApplySeq;
@ -3037,11 +3095,10 @@ internal sealed partial class LegacyDashboardRenderer
break;
case "update_rule":
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
{
_settings.MetaRules[cmd.Index] = DtoToMetaRule(cmd.Rule);
// The engine's editor saves every change (2026-10-05): keep the running rule's
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule)))
TryAutoSaveMetaCmd();
}
break;
case "delete_rule":
@ -3072,7 +3129,9 @@ internal sealed partial class LegacyDashboardRenderer
case "duplicate_rule":
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
{
_settings.MetaRules.Insert(cmd.Index + 1, DtoToMetaRule(cmd.Rule));
var copy = DtoToMetaRule(cmd.Rule);
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
_settings.MetaRules.Insert(cmd.Index + 1, copy);
TryAutoSaveMetaCmd();
}
break;

View file

@ -1,295 +0,0 @@
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.ItemInfo;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// "RynthAi Item Info" window: every option of the Mag-style item info line (/ra iteminfo) with
/// a live preview of the selected item. Edits go straight into
/// <see cref="LegacyUiSettings.ItemInfoSettings"/> and are saved by the dashboard autosave.
/// Opened from Advanced Settings → Display or with /ra iteminfo settings.
/// </summary>
internal sealed class LegacyItemInfoUi
{
private readonly LegacyUiSettings _settings;
// Supplied by RynthAiPlugin (it owns the host + object cache).
private Func<string?>? _describeSelected; // selected item's line (no prefix) or null when nothing is selected
private Action? _printSelected; // same path as /ra iteminfo (requests an ID when needed)
private Action<int>? _testChatType; // prints a sample line with the given chat type
// Preview is rebuilt on a timer or when an output option changes, not every frame.
private const long PreviewRefreshMs = 500;
private string? _previewText;
private long _previewAt;
private MagItemInfoOptions _previewOptions;
private static readonly Vector4 ExampleColor = new(0.60f, 0.66f, 0.74f, 1f);
public LegacyItemInfoUi(LegacyUiSettings settings) => _settings = settings;
public void SetHooks(Func<string?> describeSelected, Action printSelected, Action<int> testChatType)
{
_describeSelected = describeSelected;
_printSelected = printSelected;
_testChatType = testChatType;
}
public void Render()
{
// Re-read every frame: loading a character profile replaces the settings object.
MagItemInfoSettings s = _settings.ItemInfoSettings;
if (!s.ShowWindow) return;
ImGui.SetNextWindowSize(new Vector2(560, 600), ImGuiCond.FirstUseEver);
if (ImGui.Begin("RynthAi Item Info##ItemInfoSettings", ref s.ShowWindow))
{
RenderPreview(s);
RenderWhen(s);
RenderFields(s);
RenderSpellsAndRatings(s);
RenderChat(s);
ImGui.Spacing();
ImGui.Separator();
if (ImGui.Button("Reset all to defaults##ii"))
{
s.ResetToDefaults();
_previewAt = 0;
}
ImGui.SameLine();
if (ImGui.Button("Close##ii")) s.ShowWindow = false;
}
ImGui.End();
}
// ── Preview ──────────────────────────────────────────────────────────────
private void RenderPreview(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Preview (selected item)##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
var options = MagItemInfoOptions.From(s);
long now = Environment.TickCount64;
if (_describeSelected != null && (now - _previewAt >= PreviewRefreshMs || options != _previewOptions))
{
try { _previewText = _describeSelected(); }
catch (Exception ex) { _previewText = "Preview failed: " + ex.Message; }
_previewAt = now;
_previewOptions = options;
}
// Pet-style output is up to four lines plus wrapping.
float previewHeight = s.Layout == MagItemInfoSettings.LayoutPetLines ? 110 : 70;
ImGui.BeginChild("iiPreview", new Vector2(0, previewHeight), ImGuiChildFlags.Borders);
if (string.IsNullOrEmpty(_previewText))
ImGui.TextDisabled("Select an item to preview its info line.");
else
ImGui.TextWrapped(s.Prefix + _previewText);
ImGui.EndChild();
if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Same as /ra iteminfo: IDs the selected item first when needed.");
ImGui.SameLine();
if (ImGui.Button("Refresh##iiRefresh")) _previewAt = 0;
}
// ── When to print ────────────────────────────────────────────────────────
private static void RenderWhen(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("When to print##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
ImGui.Checkbox("Describe items when selected##iiOnSel", ref s.OnSelect);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Print the info every time the selection changes to an item.\n/ra iteminfo always works, whatever is set here.");
RenderClickTrigger(s, "##iiClick");
ImGui.Text("Item types:");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Which items the select / click triggers describe.\n/ra iteminfo and Print to chat ignore these.");
ImGui.Indent();
ImGui.BeginDisabled(!s.OnSelect && s.ClickTrigger == MagItemInfoSettings.ClickOff);
ImGui.Checkbox("Weapons##iiSelW", ref s.OnSelectWeapons); ImGui.SameLine();
ImGui.Checkbox("Armor & clothing##iiSelA", ref s.OnSelectArmor); ImGui.SameLine();
ImGui.Checkbox("Jewelry##iiSelJ", ref s.OnSelectJewelry); ImGui.SameLine();
ImGui.Checkbox("Other items##iiSelO", ref s.OnSelectOther);
ImGui.EndDisabled();
ImGui.Unindent();
ImGui.SetNextItemWidth(200);
if (ImGui.SliderFloat("ID wait (seconds)##iiTimeout", ref s.IdTimeoutSec, 0.5f, 15f, "%.1f s"))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How long to wait for an unidentified item's appraisal\nbefore printing what is already known.");
}
/// <summary>
/// "ID on click" combo (Off / Left / Right). Shared with Advanced Settings → Display, so
/// <paramref name="idSuffix"/> keeps the ImGui ids unique per window.
/// </summary>
public static void RenderClickTrigger(MagItemInfoSettings s, string idSuffix)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("ID + print on click" + idSuffix, ref s.ClickTrigger,
MagItemInfoCatalog.ClickTriggers, MagItemInfoCatalog.ClickTriggers.Length))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Clicking an item in the world or your packs IDs it and prints its info,\n" +
"even when it was already selected. Clicks on RynthCore windows, drags and\n" +
"held-button camera turns are ignored.\n" +
"Right click prints whatever item is selected after the click: if your client\n" +
"doesn't select on right click, left-click to select, then right-click to print.\n" +
"Needs the ImGui overlay enabled.");
}
/// <summary>Layout combo (pet-style lines / one line). Shared with Advanced Settings → Display.</summary>
public static void RenderLayout(MagItemInfoSettings s, string idSuffix)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Layout" + idSuffix, ref s.Layout, MagItemInfoCatalog.Layouts, MagItemInfoCatalog.Layouts.Length))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Pet-style lines (like the ILT Hub pet roster):\n" +
" 1 Name (type mastery), set, AL, tinks, applied, craft\n" +
" 2 imbues, slayer, damage, variance, %a / %md / %mc\n" +
" 3 [ratings] wield / activation / diff, value\n" +
" 4 Spells: …\n" +
"One line: the classic Mag-Tools single line.");
}
// ── Field toggles ────────────────────────────────────────────────────────
private void RenderFields(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Fields##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
if (ImGui.SmallButton("All on##iiFields")) s.HiddenFields = 0;
ImGui.SameLine();
if (ImGui.SmallButton("All off##iiFields"))
{
foreach (var f in MagItemInfoCatalog.Fields) s.SetHidden(f.Field, true);
}
ImGui.SameLine();
ImGui.TextDisabled("(the item name is always printed)");
if (ImGui.BeginTable("iiFieldTable", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Field", ImGuiTableColumnFlags.WidthStretch, 0.45f);
ImGui.TableSetupColumn("Example", ImGuiTableColumnFlags.WidthStretch, 0.55f);
foreach (var f in MagItemInfoCatalog.Fields)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool shown = !s.IsHidden(f.Field);
if (ImGui.Checkbox($"{f.Label}##iiF{(int)f.Field}", ref shown))
s.SetHidden(f.Field, !shown);
ImGui.TableNextColumn();
ImGui.TextColored(ExampleColor, f.Example);
}
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Checkbox("Value & burden##iiValBu", ref s.ShowValueAndBurden);
ImGui.TableNextColumn();
ImGui.TextColored(ExampleColor, "Value 12,500, BU 220");
ImGui.EndTable();
}
}
// ── Spells + per-rating toggles ──────────────────────────────────────────
private static void RenderSpellsAndRatings(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Spells & ratings##ii")) return;
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Spells));
ImGui.Text("Spell list:");
ImGui.SameLine();
ImGui.RadioButton("Mag filter##iiSpMag", ref s.SpellMode, MagItemInfoSettings.SpellModeMag);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Cantrips, level 7+ weapon auras, Augmented spells,\nand Impen/banes only on unenchantable gear.");
ImGui.SameLine();
ImGui.RadioButton("All spells##iiSpAll", ref s.SpellMode, MagItemInfoSettings.SpellModeAll);
if (s.SpellMode == MagItemInfoSettings.SpellModeAll)
{
ImGui.SetNextItemWidth(200);
if (ImGui.SliderInt("Max spells listed##iiSpMax", ref s.MaxListedSpells, 1, 64))
s.Sanitize();
}
ImGui.EndDisabled();
ImGui.Spacing();
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Ratings));
ImGui.Text("Ratings shown:");
ImGui.SameLine();
if (ImGui.SmallButton("All##iiRat")) s.HiddenRatings = 0;
ImGui.SameLine();
if (ImGui.SmallButton("None##iiRat")) s.HiddenRatings = (1 << MagItemInfoCatalog.Ratings.Length) - 1;
if (ImGui.BeginTable("iiRatingTable", 3))
{
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
ImGui.TableNextColumn();
bool shown = !s.IsRatingHidden(i);
if (ImGui.Checkbox($"{ratings[i].Tag} - {ratings[i].Name}##iiR{i}", ref shown))
s.SetRatingHidden(i, !shown);
}
ImGui.EndTable();
}
ImGui.EndDisabled();
}
// ── Chat output ──────────────────────────────────────────────────────────
private void RenderChat(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Chat output##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
RenderLayout(s, "##iiLayout");
ChatTypeCombo("Chat type / colour##iiChat", ref s.ChatType, allowSameAsHeader: false);
ImGui.SameLine();
if (ImGui.Button("Test##iiChatTest")) _testChatType?.Invoke(s.ChatType);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Print a sample line with this chat type to see its colour.");
// Pet-style only: the roster draws its detail lines in a second colour.
ImGui.BeginDisabled(s.Layout != MagItemInfoSettings.LayoutPetLines);
ChatTypeCombo("Detail lines colour##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true);
ImGui.SameLine();
if (ImGui.Button("Test##iiChatDetailTest"))
_testChatType?.Invoke(s.DetailChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.DetailChatType);
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above).");
ImGui.SetNextItemWidth(220);
ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Text put in front of every item info line (may be empty).");
}
/// <summary>Chat type picker; <paramref name="allowSameAsHeader"/> adds the "same as name line" entry (-1).</summary>
private static void ChatTypeCombo(string label, ref int chatType, bool allowSameAsHeader)
{
const string SameLabel = "Same as name line";
string current = chatType == MagItemInfoSettings.SameAsHeader ? SameLabel : $"{chatType}";
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
if (type == chatType) { current = name; break; }
ImGui.SetNextItemWidth(220);
if (!ImGui.BeginCombo(label, current)) return;
if (allowSameAsHeader && ImGui.Selectable(SameLabel, chatType == MagItemInfoSettings.SameAsHeader))
chatType = MagItemInfoSettings.SameAsHeader;
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
if (ImGui.Selectable(name, type == chatType)) chatType = type;
ImGui.EndCombo();
}
}

View file

@ -47,7 +47,7 @@ internal sealed class LegacyMetaUi
private string _statusMessage = "";
private DateTime _statusTime = DateTime.MinValue;
private static readonly string MetaFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
/// <summary>Warnings from the most recent LoadMacroFile, so the Avalonia
/// bridge can surface them too (it doesn't see the LoadedMeta).</summary>
@ -699,6 +699,9 @@ internal sealed class LegacyMetaUi
case MetaConditionType.VitaePHE:
condHint = "Vitae penalty % (e.g. 5)";
break;
case MetaConditionType.NoKillsWithinMinutes:
condHint = "Minutes without a kill (e.g. 5 or 2.5)";
break;
}
}

View file

@ -143,7 +143,7 @@ internal sealed class LegacyNavigationUi
for (int ri = 0; ri < ids.Length; ri++)
{
string name = $"Spell {ids[ri]}";
string name = NavPoint.RecallName(ids[ri]);
if (ImGui.Selectable($"{name} ({ids[ri]})"))
{
if (_host.HasGetPlayerPose && _host.TryGetPlayerPose(out _, out float x, out float y, out float z, out _, out _, out _, out _))

View file

@ -45,7 +45,7 @@ public sealed class LegacyUiSettings
public float NavResumeTurnAngle = 10f;
public float NavDeadZone = 4f;
public float NavSweepMult = 2.5f;
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
public float NavLookaheadYards = 4.0f; // most the aim point is blended toward the next waypoint (0 = off); the nav point reach scales it down (NavigationEngine.CornerLookaheadYards)
public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point)
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
@ -82,10 +82,6 @@ public sealed class LegacyUiSettings
public bool ShowTargetStaminaMana;
/// <summary>Mag-style item info (/ra iteminfo): on-select, per-field visibility, chat type, prefix.
/// Edited in the "RynthAi Item Info" window.</summary>
public RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoSettings ItemInfoSettings = new();
public bool EnableMissileCrafting = true;
public int MissileCraftAmmoThreshold = 1000;
@ -137,6 +133,11 @@ public sealed class LegacyUiSettings
public bool StopLootingWhenPackFull = true;
public bool StopMacroWhenPackFull = false;
public int RestamAt = 30;
/// <summary>
/// In combat, once stamina drops under Re-stam At, keep recharging until it reaches this %
/// (one Revitalize often doesn't get far). 0, or not above Re-stam At = one recharge, as before.
/// </summary>
public int RestamTo = 0;
public int GetManaAt = 40;
public int TopOffHP = 95;
public int TopOffStam = 95;
@ -160,6 +161,12 @@ public sealed class LegacyUiSettings
// degrees) toward the target; otherwise its other shape. 0 = off: Blast is just a shape.
public int BlastRange = 0;
public int MinBlastTargets = 3;
// Wall spells (2026-10-08): with WallRange > 0, a rule with Wall on casts its element's wall
// (Slithering Flames, Os' Wall...) when MinWallTargets monsters are within WallRange in the
// wall's path toward the target, turning to face the target first (a wall flies along the
// caster's facing). Below a due ring, above a due blast. 0 = off: no walls at all.
public int WallRange = 0;
public int MinWallTargets = 3;
// Nav point reach (VTank "Follow/Nav Min Distance"), yards: how close nav gets to each
// nav point before moving on to the next, and how close Follow gets to its leader.
// Metas set it as FollowNavMin (yards) or VTank's NavCloseStopRange (landblock units,
@ -175,6 +182,11 @@ public sealed class LegacyUiSettings
public float NavHeightOffset = 0.05f;
public float NavSlopeSink = 1.5f;
public bool ShowTerrainPassability = true;
// Nav3D extras, both off by default: labels over the route's waypoints (NavLabelModes:
// 0 off, 1 numbers, 2 numbers and what happens there) and a line from the character to
// the waypoint nav is heading for.
public int NavLabelMode;
public bool NavGuideLine;
public double MaxMonRange = 12.0;
public bool SummonPets;
public int CustomPetRange = 5;
@ -200,10 +212,22 @@ public sealed class LegacyUiSettings
/// </summary>
public bool LootOwnCorpse = true;
/// <summary>
/// Out of acid or lava at once (RynthAiPlugin.HazardEscape.cs): the first hotspot hit stops
/// everything and walks back out, and the spot becomes a hazard the patrol avoids. On by
/// default (2026-10-07); off for characters that walk through acid on purpose (then the spot
/// isn't learned either). A profile saved before this setting loads it as on.
/// </summary>
public bool EscapeHazards = true;
/// <summary>
/// After a death and respawn, travel back to where you died (RynthNav, outdoors only), fight
/// on the way as usual, recover the corpse, then carry on. Off by default.
/// </summary>
public bool TravelToOwnCorpse;
/// <summary>
/// Selecting an item prints its details to chat (/ra iteminfo, Mag-Tools style),
/// identifying it first when needed. Items RynthAi selects itself are skipped. On by default.
/// </summary>
public bool ItemInfoOnSelect = true;
public bool LootOnlyRareCorpses;
/// <summary>Also pick up loose ground items that match the loot profile, within the corpse max range.</summary>
public bool EnableGroundLoot;
@ -232,6 +256,35 @@ public sealed class LegacyUiSettings
/// as on for good (the behaviour before 2026-10-05).
/// </summary>
public bool CastBuffsOverItemBuffs = true;
/// <summary>
/// Buff base names the player unticked in Buffing settings (the Protections and Banes grid,
/// e.g. "Fire Protection Self", "Flame Bane"): left out of the buff list, so never cast and
/// never waited on. Empty = every buff on, which is also what a profile saved before this
/// setting existed loads as. Replaced, not edited in place (SetBuffEnabled), so a reader
/// holding the old list never sees it change under it.
/// </summary>
public List<string> DisabledBuffs
{
get => _disabledBuffs;
set => _disabledBuffs = value ?? new List<string>();
}
private List<string> _disabledBuffs = new();
public bool IsBuffDisabled(string buffBaseName)
{
foreach (string b in _disabledBuffs)
if (string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
public void SetBuffEnabled(string buffBaseName, bool enabled)
{
if (enabled == !IsBuffDisabled(buffBaseName)) return;
var next = new List<string>(_disabledBuffs);
if (enabled) next.RemoveAll(b => string.Equals(b, buffBaseName, StringComparison.OrdinalIgnoreCase));
else next.Add(buffBaseName);
_disabledBuffs = next;
}
public bool StartMacroOnLogin;
public bool PatrolOnLogin;
/// <summary>
@ -276,6 +329,13 @@ public sealed class LegacyUiSettings
public int GiveQueueIntervalMs = 150;
/// <summary>
/// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield").
/// -1 = automatic (read from the server's "/aug" reply). ACECustom doesn't send the count
/// at login, so this is the fallback when "/aug" is unavailable. Set with /ra t11 augs.
/// </summary>
public int T11ItemAugsOverride = -1;
public int SpellCastIntervalMs = 400;
/// <summary>
@ -630,6 +690,10 @@ public sealed class MonsterRule
/// <summary>Blast spells (Flame Blast, Frost Blast...: a spread of projectiles). Off in files
/// from before 2026-10-03. Wins over Bolt when both are on; see CombatManager.PickBaseShape.</summary>
public bool UseBlast { get; set; }
/// <summary>Wall spells (Slithering Flames, Os' Wall...: a row of projectiles flying straight
/// ahead). An override like the ring, cast only with Wall Range on and enough monsters in the
/// wall's path; a wall-only rule casts Bolt between walls. Off in files from before 2026-10-08.</summary>
public bool UseWall { get; set; }
public string ExVuln { get; set; } = "None";
/// <summary>The off hand for this rule: 0 = the global setting (OffhandDefault), 1 Auto,
/// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed
@ -823,6 +887,7 @@ public sealed class SettingsBridgePayload
public int BlacklistCastSettleMs { get; set; } = -1;
public int TargetNoProgressTimeoutSec { get; set; }
public int GiveQueueIntervalMs { get; set; }
public int? T11ItemAugsOverride { get; set; }
// Recharge
public int HealAt { get; set; }
@ -840,6 +905,7 @@ public sealed class SettingsBridgePayload
public bool StopLootingWhenPackFull { get; set; }
public bool StopMacroWhenPackFull { get; set; }
public int RestamAt { get; set; }
public int? RestamTo { get; set; }
public int GetManaAt { get; set; }
public int TopOffHP { get; set; }
public int TopOffStam { get; set; }
@ -860,11 +926,16 @@ public sealed class SettingsBridgePayload
// Spell Combat
public int SpellCastIntervalMs { get; set; }
public int AttackSpellIntervalMs { get; set; }
// Nullable since 0 became a real value (2026-10-08): a file without it keeps the default.
public int? AttackSpellIntervalMs { get; set; }
public bool CastDispelSelf { get; set; }
public int MinRingTargets { get; set; }
public int BlastRange { get; set; }
public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default
// Walls (2026-10-08): null = sent by an engine without the Wall Range control, which then
// leaves the plugin's own values alone (a profile's or a meta's) instead of zeroing them.
public int? WallRange { get; set; }
public int? MinWallTargets { get; set; }
public int MinSkillLevelTier1 { get; set; }
public int MinSkillLevelTier2 { get; set; }
public int MinSkillLevelTier3 { get; set; }
@ -890,6 +961,9 @@ public sealed class SettingsBridgePayload
public float NavHeightOffset { get; set; }
public float NavSlopeSink { get; set; }
public bool ShowTerrainPassability { get; set; }
// Absent from an older engine: -1 / null keep the plugin's value.
public int NavLabelMode { get; set; } = -1;
public bool? NavGuideLine { get; set; }
public bool OpenDoors { get; set; }
public float OpenDoorRange { get; set; }
public bool AutoUnlockDoors { get; set; }
@ -918,6 +992,8 @@ public sealed class SettingsBridgePayload
// Nullable: an engine that predates the setting doesn't send it, and a save from its
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List<string>? DisabledBuffs { get; set; }
public int BuffMinSkillLevelTier1 { get; set; }
public int BuffMinSkillLevelTier2 { get; set; }
public int BuffMinSkillLevelTier3 { get; set; }
@ -943,7 +1019,9 @@ public sealed class SettingsBridgePayload
// Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them,
// and its save must leave them alone.
public bool? LootOwnCorpse { get; set; }
public bool? EscapeHazards { get; set; }
public bool? TravelToOwnCorpse { get; set; }
public bool? ItemInfoOnSelect { get; set; }
public bool EnableAutostack { get; set; }
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
public bool EnableCombineSalvage { get; set; }
@ -980,8 +1058,6 @@ public sealed class SettingsBridgePayload
// Ground loot (GroundLootController; also /ra groundloot on|off).
public bool EnableGroundLoot { get; set; }
// Item info: describe an item in chat when it is selected (/ra iteminfo onselect).
public bool ItemInfoOnSelect { get; set; }
// Diagnostics. Stored per PC in Logs\Diagnostics\diagnostics.json (RynthLog), not in
// the character profile; applied only when a value differs, so a save of other
@ -1030,7 +1106,11 @@ public enum MetaConditionType
MainManaLE,
MainManaPHE,
MainStamLE,
VitaePHE
VitaePHE,
/// <summary>RynthAi only (2026-10-06): no kill for at least N minutes (ConditionData = minutes,
/// decimals allowed). Appended last: the value is the wire / JSON number, and an older RynthAi
/// that reads it treats the unknown number (and the .af keyword NoKillsInMins) as never true.</summary>
NoKillsWithinMinutes
}
public enum MetaActionType

View file

@ -74,12 +74,24 @@ public sealed class NavPoint
/// </summary>
public bool Doorway { get; set; }
/// <summary>"Lifestone Recall": a recall step by its spell's name (it showed "Spell 1635",
/// 2026-10-08); the id when the spell table doesn't know it.</summary>
internal static string RecallName(int spellId)
{
string? name = SpellNameLookup?.Invoke(spellId);
return string.IsNullOrEmpty(name) ? $"Spell {spellId}" : name;
}
/// <summary>The spell table's name for an id; RynthAi sets it (this file is also compiled into
/// tools without the spell table, which keep "Spell N").</summary>
internal static Func<int, string?>? SpellNameLookup { get; set; }
public override string ToString()
{
return Type switch
{
NavPointType.Point => $"[Point] {NS:F3}, {EW:F3}",
NavPointType.Recall => $"[Recall] Spell {SpellId}",
NavPointType.Recall => $"[Recall] {RecallName(SpellId)}",
NavPointType.Pause => $"[Pause] {PauseTimeMs / 1000.0:F1}s",
NavPointType.Chat => $"[Chat] {ChatCommand}",
NavPointType.OpenVendor => $"[Vendor] {TargetName}",

View file

@ -20,7 +20,7 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// </summary>
internal sealed class LootEditorBridge
{
public const string LootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
public static readonly string LootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
private readonly object _sync = new();
private readonly LootEditSession _session = new();
@ -182,8 +182,10 @@ internal sealed class LootEditorBridge
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like);
d.IncludeT11 = req.IncludeT11;
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
d.IsT11 = facts.T11?.IsT11 == true;
d.ItemName = facts.Name;
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
d.Stackable = facts.Stackable;
@ -207,6 +209,7 @@ internal sealed class LootEditorBridge
Action = req.Action == 0 ? null : (VTankLootAction)req.Action,
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
@ -336,8 +339,11 @@ internal sealed class LootItemHooks
{
/// <summary>The item selected in the game, or 0.</summary>
public Func<uint> SelectedItemId { get; set; } = () => 0;
/// <summary>The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified).</summary>
public Func<uint, bool, LootItemFacts?> Facts { get; set; } = (_, _) => null;
/// <summary>
/// The item's facts from the object cache, or null. The bools: "items like this" and
/// "include T11 attributes"; either asks for an ID when the item isn't identified.
/// </summary>
public Func<uint, bool, bool, LootItemFacts?> Facts { get; set; } = (_, _, _) => null;
/// <summary>The first rule of the .utl profile that matches the item now, or -1.</summary>
public Func<uint, VTankLootProfile, int> FirstMatchUtl { get; set; } = (_, _) => -1;
/// <summary>The first rule of the native profile that matches the item now, or -1.</summary>

View file

@ -72,7 +72,7 @@ public static class LootEvaluator
private static double EvalMinDamage(WorldObject item)
{
int maxDamage = item.Values(54, 0); // STypeInt MAX_DAMAGE
int maxDamage = item.Values(44, 0); // Damage, the weapon profile's max (was 54, WeaponEncumbrance, until 2026-10-07)
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
return maxDamage - variance * maxDamage;
}

View file

@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using RynthCore.Loot.T11;
namespace RynthCore.Plugin.RynthAi.Loot;
/// <summary>
/// T11 (tier 11+ ACECustom) loot support for <see cref="WorldObject.Values(int, int)"/>:
/// answers the virtual T11 keys (<see cref="T11Keys"/>) and puts back the wield-requirement and
/// rating properties the server strips from T11 appraisals. Parsed item text is cached per
/// object and re-parsed only when the text changes. Holds the player's "/aug" counters for
/// the "Can Wield" key. One character per process, so the state is static.
/// </summary>
internal static class T11ItemSupport
{
/// <summary>The logged-in character's T11 wield counters.</summary>
public static T11PlayerAugs Player { get; } = new();
private static readonly T11AugReportParser AugParser = new();
private static readonly object Gate = new();
private static readonly Dictionary<int, Entry> Parsed = new();
// Bound so a long session's corpse items can't grow the cache without limit; a full
// clear is fine because re-parsing is cheap and only happens for items still in use.
private const int MaxEntries = 4096;
private sealed class Entry
{
public string Name = string.Empty;
public string LongDesc = string.Empty;
public string Use = string.Empty;
public T11ItemInfo Info = T11ItemInfo.None;
}
/// <summary>True when <paramref name="name"/> carries the server's T11 drop prefix.</summary>
public static bool HasT11Name(string? name)
=> !string.IsNullOrEmpty(name) && name.StartsWith(T11Catalog.NamePrefix, StringComparison.Ordinal);
/// <summary>The parsed T11 view of <paramref name="item"/> (<see cref="T11ItemInfo.None"/> for other items).</summary>
public static T11ItemInfo Get(WorldObject item)
{
string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty);
string longDesc = item.Values(StringValueKey.LongDesc, string.Empty);
string use = item.Values(StringValueKey.Use, string.Empty);
lock (Gate)
{
if (Parsed.TryGetValue(item.Id, out Entry? e)
&& string.Equals(e.Name, name, StringComparison.Ordinal)
&& string.Equals(e.LongDesc, longDesc, StringComparison.Ordinal)
&& string.Equals(e.Use, use, StringComparison.Ordinal))
return e.Info;
}
T11ItemInfo info = T11ItemInfo.Parse(name, longDesc, use);
lock (Gate)
{
if (Parsed.Count >= MaxEntries) Parsed.Clear();
Parsed[item.Id] = new Entry { Name = name, LongDesc = longDesc, Use = use, Info = info };
}
return info;
}
/// <summary>A virtual T11 key's value, or <paramref name="defaultValue"/> for an unused id.</summary>
public static int VirtualValue(WorldObject item, int key, int defaultValue)
{
try
{
return T11Keys.TryGetValue(Get(item), key, Player, out int value) ? value : defaultValue;
}
catch
{
return defaultValue;
}
}
/// <summary>
/// The value a T11 appraisal stripped for a retail key (158/159/160, 370-379), else
/// <paramref name="fallback"/>. Only T11-named items are parsed, so other items pay a
/// string compare.
/// </summary>
public static int StrippedValue(WorldObject item, int key, int fallback)
{
if (!T11Keys.IsStrippedKey(key)) return fallback;
try
{
string name = item.Name.Length > 0 ? item.Name : item.Values(StringValueKey.Name, string.Empty);
if (!HasT11Name(name)) return fallback;
return T11Keys.TryGetStrippedValue(Get(item), key, out int value) ? value : fallback;
}
catch
{
return fallback;
}
}
/// <summary>Feeds a chat line to the "/aug" reader. Returns true when a counter changed.</summary>
public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player);
/// <summary>Applies the saved item-aug override (-1 = automatic). Cheap; called every tick.</summary>
public static void SyncOverride(int itemAugsOverride)
=> Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null;
/// <summary>Drops the cached parse of a deleted object.</summary>
public static void Forget(int objectId)
{
lock (Gate) Parsed.Remove(objectId);
}
/// <summary>Forgets the character's counters and every cached item (logout).</summary>
public static void Reset()
{
Player.Clear();
lock (Gate) Parsed.Clear();
}
}

View file

@ -0,0 +1,213 @@
// ============================================================================
// RynthAi - Loot/UseRefusalWatch.cs
// Notices when the server answers every corpse open but nothing opens.
//
// Why (2026-10-06, Drakkon on DreamWeave): from 06:18:44 every use of a corpse
// or door got the server's "use done" (UseDone, no error) about one round trip
// after it was sent, and nothing opened. Fighting, healing kits and spells kept
// working. Macro off, walking, jumping and /rc unlockactions changed nothing; a
// relog fixed it at once, for the very same corpses. The bot hammered corpses
// for 13 minutes: 33 abandons, 11 "LOOT WEDGE" resets, a chat line each.
//
// What this does: each corpse open is remembered with the server's UseDone
// count at the time. A UseDone that arrives after it with no error, with no
// corpse opening within AnswerGraceMs, is a refusal. A successful open of any
// corpse clears everything.
// - RefusalsBeforeRetry refusals in a row: stop all movement once, pause a
// moment, try once more (CleanStopAndRetry).
// - The retry refused too, with refusals on two different corpses since the
// last open: the server refuses every use. Say so once and back off
// (Stuck), then try one corpse every BackoffMs (doubling, capped). Each
// probe that is refused again is StillStuck (log only); one that opens is
// Recovered.
// - The retry refused but only one corpse has ever refused: that corpse can't
// be opened (its loot rights, say). Give up on it (DropCorpse); the next
// corpse's first refusal decides.
//
// A UseDone with an error (0x1D "too busy", ...) says nothing either way, and
// an open the server never answers is left to the corpse timeout as before.
// No game calls here: the controller acts on the verdicts.
//
// The jump (2026-10-06 afternoon): the stuck state is the server's animation
// bookkeeping for the character (ACE: MotionInterp.PendingMotions/IsAnimating
// and the MotionTableManager queue never drain, so the server's turn to the
// corpse never starts and the use's callback never runs). Besides leaving the
// world, the only thing on ACE that empties those queues is the player's jump
// (Player.HandleActionJump: RemoveLinkAnimations drains the motion table queue,
// PendingMotions.Clear, IsAnimating = false; the jump also cancels the pending
// walk/turn). So the controller jumps at the clean stop, and once more before
// each probe after a back-off (TakeProbeJump).
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.Loot;
internal sealed class UseRefusalWatch
{
/// <summary>After the server's answer, a corpse that opens does so within a few frames.</summary>
public const long AnswerGraceMs = 1500;
/// <summary>An open the server hasn't answered after this long is forgotten (the corpse timeout handles it).</summary>
public const long UnansweredForgetMs = 15_000;
public const int RefusalsBeforeRetry = 3;
/// <summary>The pause after the clean stop, before the one retry.</summary>
public const long CleanStopPauseMs = 1500;
public const long FirstBackoffMs = 5 * 60_000;
public const long MaxBackoffMs = 20 * 60_000;
public enum Phase { Normal, Retrying, Stuck }
public enum Verdict
{
None,
/// <summary>Several refusals in a row: stop all movement, pause CleanStopPauseMs, try once more.</summary>
CleanStopAndRetry,
/// <summary>The retry was refused but only this corpse ever refused: give up on it.</summary>
DropCorpse,
/// <summary>The server refuses every use: tell the player once, back off until BackoffUntil.</summary>
Stuck,
/// <summary>A probe after the back-off was refused too: back off again (longer), quietly.</summary>
StillStuck,
/// <summary>A corpse opened after Stuck: uses work again.</summary>
Recovered,
}
public Phase State { get; private set; } = Phase.Normal;
public int Refusals { get; private set; }
public long BackoffUntil { get; private set; }
public long BackoffMs { get; private set; }
/// <summary>The corpses refused since the last successful open.</summary>
public IReadOnlyCollection<int> RefusedCorpses => _refused;
/// <summary>The corpse of the last refusal (what a verdict is about).</summary>
public int LastRefusedCorpse { get; private set; }
private readonly HashSet<int> _refused = new();
private bool _probeJumpTaken;
private bool _pending;
private int _pendingId;
private long _sentAt;
private int _seqAtSend;
private long _answeredAt;
/// <summary>While Stuck: no opens until the back-off ends (then one probe).</summary>
public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil;
/// <summary>The back-off is over and the probe is next: true once per back-off, meaning
/// "jump first, then send the probe after the pause".</summary>
public bool TakeProbeJump(long now)
{
if (State != Phase.Stuck || now < BackoffUntil || _probeJumpTaken)
return false;
_probeJumpTaken = true;
return true;
}
/// <summary>Call before sending the next open: the previous one, answered with nothing opened,
/// counts as refused now (the next attempt came before its grace ran out). A verdict other than
/// None means: act on it and don't send this open.</summary>
public Verdict SettleBeforeOpen(long now)
{
if (!_pending || _answeredAt == 0)
return Verdict.None;
_pending = false;
return Refused(_pendingId, now);
}
/// <summary>An open of <paramref name="corpseId"/> went out; <paramref name="useDoneSeq"/> is the
/// server UseDone count read just before it was sent.</summary>
public void OnOpenSent(int corpseId, long now, int useDoneSeq)
{
_pending = true;
_pendingId = corpseId;
_sentAt = now;
_seqAtSend = useDoneSeq;
_answeredAt = 0;
}
/// <summary>Every tick: <paramref name="useDoneSeq"/> is the server UseDone count now,
/// <paramref name="lastError"/> the error of the latest one when the engine can say
/// (<paramref name="haveLastError"/>).</summary>
public Verdict OnTick(long now, int useDoneSeq, uint lastError, bool haveLastError)
{
if (!_pending)
return Verdict.None;
if (_answeredAt == 0)
{
if (useDoneSeq != _seqAtSend)
{
if (haveLastError && lastError != 0)
{
_pending = false; // "too busy" or another error: says nothing about refusals
return Verdict.None;
}
_answeredAt = now;
}
else if (now - _sentAt >= UnansweredForgetMs)
{
_pending = false;
}
return Verdict.None;
}
if (now - _answeredAt < AnswerGraceMs)
return Verdict.None;
_pending = false;
return Refused(_pendingId, now);
}
/// <summary>A corpse opened (the server sent its contents): uses work.</summary>
public Verdict OnOpened(long now)
{
bool wasStuck = State == Phase.Stuck;
Reset();
return wasStuck ? Verdict.Recovered : Verdict.None;
}
/// <summary>Back to normal: a relog, a login, a successful open.</summary>
public void Reset()
{
State = Phase.Normal;
Refusals = 0;
BackoffUntil = 0;
BackoffMs = 0;
LastRefusedCorpse = 0;
_refused.Clear();
_probeJumpTaken = false;
_pending = false;
_answeredAt = 0;
}
private Verdict Refused(int corpseId, long now)
{
_refused.Add(corpseId);
LastRefusedCorpse = corpseId;
Refusals++;
switch (State)
{
case Phase.Normal:
if (Refusals < RefusalsBeforeRetry)
return Verdict.None;
State = Phase.Retrying;
return Verdict.CleanStopAndRetry;
case Phase.Retrying:
if (_refused.Count < 2)
return Verdict.DropCorpse; // stay Retrying: the next corpse's refusal decides
State = Phase.Stuck;
BackoffMs = FirstBackoffMs;
BackoffUntil = now + BackoffMs;
_probeJumpTaken = false;
return Verdict.Stuck;
default: // Stuck: a probe after the back-off
BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2));
BackoffUntil = now + BackoffMs;
_probeJumpTaken = false;
return Verdict.StillStuck;
}
}
}

View file

@ -194,8 +194,8 @@ public static class VTankLootEvaluator
VTankNodeTypes.StringValueMatch => MatchStringValue(item, d),
VTankNodeTypes.LongValKeyLE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) <= val,
VTankNodeTypes.LongValKeyGE => Long(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) <= val,
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
VTankNodeTypes.DoubleValKeyLE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) <= val,
VTankNodeTypes.DoubleValKeyGE => Double(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val,
VTankNodeTypes.DamagePercentGE => false, // VTank source returns false unconditionally
VTankNodeTypes.ObjectClass => ScrollLearner.ClassMatches(item, ReadInt(d, 0)), // Scroll (42) also matches scroll Books
VTankNodeTypes.SpellCountGE => ctx is null || ctx.GetItemSpellIds(itemId).Length >= ReadInt(d, 0),
@ -216,8 +216,8 @@ public static class VTankLootEvaluator
VTankNodeTypes.BuffedMedianDamageGE => MatchBuffedMedianDamageGE(item, d),
VTankNodeTypes.BuffedMissileDamageGE => MatchBuffedMissileDamageGE(item, d),
VTankNodeTypes.BuffedLongValKeyGE => DoubleKey(d) is var (val,key) && item.Values((LongValueKey)key, 0) >= val,
VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values((DoubleValueKey)key, 0.0) >= val,
VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(54, 0) >= ReadDouble(d, 0),
VTankNodeTypes.BuffedDoubleValKeyGE => DoubleKey(d) is var (val,key) && item.Values(FloatKey(key), 0.0) >= val,
VTankNodeTypes.CalcdBuffedTinkedDamageGE => item.Values(44, 0) >= ReadDouble(d, 0),
VTankNodeTypes.TotalRatingsGE => MatchTotalRatingsGE(item, d),
VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE => false, // not implemented
VTankNodeTypes.DisabledRule => MatchDisabledRule(d),
@ -278,7 +278,7 @@ public static class VTankLootEvaluator
private static bool MatchMinDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
if (maxDamage == 0) return false;
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
double minDamage = maxDamage - (variance * maxDamage);
@ -310,7 +310,7 @@ public static class VTankLootEvaluator
private static bool MatchBuffedMedianDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
if (maxDamage == 0) return false;
double variance = item.Values(DoubleValueKey.DamageVariance, 0.0);
double minDamage = maxDamage - (variance * maxDamage);
@ -320,7 +320,7 @@ public static class VTankLootEvaluator
private static bool MatchBuffedMissileDamageGE(WorldObject item, IList<string> d)
{
double threshold = ReadDouble(d, 0);
int maxDamage = item.Values(54, 0);
int maxDamage = item.Values(44, 0); // Damage: the weapon profile's max (54 is WeaponEncumbrance; until 2026-10-07)
if (maxDamage == 0) return false;
double elemBonus = item.Values((DoubleValueKey)152, 1.0);
if (elemBonus < 1.0) elemBonus = 1.0;
@ -356,4 +356,24 @@ public static class VTankLootEvaluator
private static (double Val, int Key) Double(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
// Buffed long/double helpers store value as double in slot 0 (matching VTank's "Read" of doubles).
private static (double Val, int Key) DoubleKey(IList<string> d) => (ReadDouble(d, 0), ReadInt(d, 1));
// A double key as the STypeFloat it reads. VTank files the appraisal's armor and weapon
// profiles under Decal's 0x0A0000xx keys (uTank2 LootPlugins.DoubleValueKey), which no
// object property has: read raw they were always 0, so LootSnob's "AttackBonus >=" rules
// never matched (until 2026-10-05). Range (0x0A00000D) and the physics keys stay unmapped.
private static DoubleValueKey FloatKey(int key) => unchecked((uint)key) switch
{
0x0A000000 => (DoubleValueKey)13, // SlashProt → ArmorModVsSlash
0x0A000001 => (DoubleValueKey)14, // PierceProt → ArmorModVsPierce
0x0A000002 => (DoubleValueKey)15, // BludgeonProt → ArmorModVsBludgeon
0x0A000003 => (DoubleValueKey)18, // AcidProt → ArmorModVsAcid
0x0A000004 => (DoubleValueKey)19, // LightningProt → ArmorModVsElectric
0x0A000005 => (DoubleValueKey)17, // FireProt → ArmorModVsFire
0x0A000006 => (DoubleValueKey)16, // ColdProt → ArmorModVsCold
0x0A000009 => (DoubleValueKey)280, // SalvageWorkmanship → the engine's workmanship read (as wobjectgetdoubleprop)
0x0A00000B => DoubleValueKey.DamageVariance, // Variance
0x0A00000C => DoubleValueKey.WeaponOffense, // AttackBonus
0x0A00000E => DoubleValueKey.DamageMod, // DamageBonus
_ => (DoubleValueKey)key,
};
}

View file

@ -289,7 +289,7 @@ public sealed partial class RynthAiPlugin
if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; }
Host.ChangeCombatMode(cm);
Host.ChangeCombatModeFor(cm, "Command", "/mt combat", force: true);
return true;
}
@ -379,7 +379,7 @@ public sealed partial class RynthAiPlugin
targetId = Host.GetPlayerId();
}
Host.CastSpell(targetId, spellId);
Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true);
return true;
}

View file

@ -110,8 +110,11 @@ internal sealed class ManaStoneManager
// off or the macro is stopped must leave the set too.
PruneLootedForTap(NowMs);
// An Eternal Mana Charge refills gear for free, so it works with tapping off too.
if (!_settings.EnableManaTapping && !HasEternalCharge()) { Reset(); return; }
// Refilling worn gear from a charged stone (or a free Eternal charge) works with tapping
// off too; only draining loot into empty stones needs tapping on. It used to need tapping
// on for any refill, so charged stones and bought Mana Charges were never used with it
// off (2026-10-08).
if (!_settings.EnableManaTapping && !HasChargedRefillStone()) { Reset(); return; }
if (!_settings.IsMacroRunning) { Reset(); return; }
long now = NowMs;
@ -418,7 +421,6 @@ internal sealed class ManaStoneManager
if (item == null) continue;
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
&& wield != 0) continue;
@ -488,12 +490,23 @@ internal sealed class ManaStoneManager
if (hasRule) return false; // explicit rules → match by name only
if (!_settings.EnableManaTapping) return false; // no rules → auto-detect only when tapping is on
if (item.ObjectClass == AcObjectClass.ManaStone) return true;
return !string.IsNullOrEmpty(item.Name)
&& (item.Name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase));
// Only the ordinary tapping stones and mana charges. Retail also has special stones
// (Aligned, Aetheria, Unstable, Enchanted, Adjanite Mana Stone) that are not for
// draining or recharging: an Aligned Mana Stone was used on a wand (2026-10-08). A
// special stone is only touched when a ManaStone consumable rule names it.
if (string.IsNullOrEmpty(item.Name))
return item.ObjectClass == AcObjectClass.ManaStone; // unnamed yet: the class decides (looting)
return OrdinaryStoneNames.Contains(item.Name)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The retail tapping stones (ACE world data names), smallest to largest.</summary>
internal static readonly HashSet<string> OrdinaryStoneNames = new(StringComparer.OrdinalIgnoreCase)
{
"Minor Mana Stone", "Lesser Mana Stone", "Moderate Mana Stone", "Mana Stone",
"Greater Mana Stone", "Major Mana Stone",
};
/// <summary>
/// An unlimited mana charge (Eternal Mana Charge: 10,000 mana, never used up). Always
/// "charged", never an empty stone to drain into, and preferred for refilling gear.
@ -501,6 +514,35 @@ internal sealed class ManaStoneManager
private static bool IsEternal(WorldObject item) =>
!string.IsNullOrEmpty(item.Name) && item.Name.StartsWith("Eternal Mana", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// A stone that may refill worn gear when charged: what <see cref="IsManaStone"/> takes, but
/// with tapping off as well (no rules: the ordinary stones and mana charges; with ManaStone
/// rules: the named ones).
/// </summary>
internal bool IsRefillStone(WorldObject item)
{
if (IsManaStone(item)) return true;
if (_settings.EnableManaTapping || string.IsNullOrEmpty(item.Name)) return false;
foreach (var rule in _settings.ConsumableRules)
if (rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(rule.Name))
return false; // rules decide (IsManaStone already said no)
return OrdinaryStoneNames.Contains(item.Name)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
// FindChargedStone walks every known object; with tapping off it gates the whole tick, so
// the answer is kept for a few seconds.
private long _chargedCheckAt;
private bool _chargedCached;
private bool HasChargedRefillStone()
{
long now = NowMs;
if (now - _chargedCheckAt < 5000) return _chargedCached;
_chargedCheckAt = now;
_chargedCached = HasEternalCharge() || FindChargedStone() != 0;
return _chargedCached;
}
private bool HasEternalCharge()
{
int playerId = unchecked((int)_host.GetPlayerId());
@ -609,7 +651,7 @@ internal sealed class ManaStoneManager
foreach (var item in _objectCache.AllKnownObjects())
{
if (!IsManaStone(item)) continue;
if (!IsRefillStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Skip stones that timed out on use-on-player recently.
@ -618,7 +660,6 @@ internal sealed class ManaStoneManager
// Eternal: always charged (its mana often can't be read), never used up — first choice.
if (IsEternal(item)) return item.Id;
if (!_settings.EnableManaTapping) continue; // tapping off: only the free charge
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int cur))
continue;
@ -649,13 +690,9 @@ internal sealed class ManaStoneManager
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
// Never tap a casting implement (wand/staff/orb). ACE refuses to
// drain mana out of these into a stone, so the tap can never complete
// and the loop spins forever (each attempt cancels movement + bumps
// busy). This is most often the character's OWN casting wand mis-read
// as a loose item — WieldedSlot can read 0 from a stale cache, so the
// equipped-skip below misses it. Mirrors CombatManager.IsWandObject.
if (IsWandLike(item)) continue;
// Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses
// retained items). Only items looted for Mana Tap are candidates, and the wielded /
// listed-item / loot-kept checks below protect the character's own casters.
// Skip items that recently failed to drain.
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
@ -682,11 +719,9 @@ internal sealed class ManaStoneManager
}
/// <summary>
/// True for casting implements (wand/staff/orb). ACE will not drain mana out
/// of these into a mana stone, so they must never be selected as a tap target
/// — otherwise the tap can never complete and loops forever. ObjectClass alone
/// is unreliable for unappraised items, so we fall back to the name, matching
/// CombatManager/BuffManager.IsWandObject.
/// True for casting implements (wand/staff/orb). They drain like any other item;
/// this is only a classifier. ObjectClass alone is unreliable for unappraised items,
/// so we fall back to the name, matching CombatManager/BuffManager.IsWandObject.
/// </summary>
internal static bool IsWandLike(WorldObject item)
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);

View file

@ -33,7 +33,7 @@ internal static class DungeonMapBake
private const int MaxDim = 8192; // the agent refuses bigger rasters
/// <summary>Where plans go. A test points this at its own folder.</summary>
internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
internal static string CacheDir { get; set; } = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps");
// Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours).
private static uint Argb(float r, float g, float b, float a) =>

View file

@ -476,6 +476,8 @@ internal static class AfFileParser
case MetaConditionType.MainManaPHE:
case MetaConditionType.MainStamLE:
case MetaConditionType.VitaePHE:
// RynthAi only: NoKillsInMins 5 (minutes, decimals allowed).
case MetaConditionType.NoKillsWithinMinutes:
// These use bare numbers (no braces): e.g. MainSlotsLE 4, BlockE F6820033
rule.ConditionData = ExtractBareOrBrace(rest);
break;

View file

@ -139,6 +139,9 @@ internal static class AfFileWriter
case MetaConditionType.MainManaPHE:
case MetaConditionType.MainStamLE:
case MetaConditionType.VitaePHE:
// RynthAi only (NoKillsInMins 5): metaf can't compile it to a .met, and an older
// RynthAi loads it as Never with an "unknown condition keyword" warning.
case MetaConditionType.NoKillsWithinMinutes:
// Bare values (no braces): MainSlotsLE 4, MainHealthLE 50
writer.Write($"{keyword} {data}");
break;
@ -341,7 +344,7 @@ internal static class AfFileWriter
5543 => "Neftet Recall",
6321 => "Rynthid Recall",
6322 => "Viridian Rise Recall",
_ => $"Spell {spellId}"
_ => NavPoint.RecallName(spellId)
};
}
}

View file

@ -62,7 +62,7 @@ internal sealed class ExpressionEngine
// The three data paths are settable only so offline tests can point them at a scratch
// folder before anything reads or writes them; the plugin never changes them.
internal static string ItemGiverDir { get; set; }
= Path.Combine(@"C:\Games\RynthSuite\RynthAi", "ItemGiver");
= Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
/// <summary>Millisecond tick for delayexec and the var-flush throttle. Tests swap it for a
/// fake clock; the plugin never changes it.</summary>
@ -107,8 +107,8 @@ internal sealed class ExpressionEngine
private long _lastVarFlushMs;
private string? _pvarPathCached;
private const long VarFlushIntervalMs = 2000;
internal static string PvarsDir { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars");
internal static string GvarsPath { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt");
internal static string PvarsDir { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "pvars");
internal static string GvarsPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "gvars.txt");
private Dictionary<string, (Func<string> Get, Action<string> Set)>? _settingsMap;
public IReadOnlyDictionary<string, string> Variables => _variables;
@ -156,6 +156,11 @@ internal sealed class ExpressionEngine
private CreatureProfileStore? _creatureStore;
public void SetCreatureStore(CreatureProfileStore? store) => _creatureStore = store;
// secondssincelastkill[]: the plugin's kill clock. Null (not wired) reads as 0, i.e.
// "just killed", so a "no kills for a while" test never holds by mistake.
private KillClock? _killClock;
public void SetKillClock(KillClock? clock) => _killClock = clock;
// ── Backward-compat shim ──────────────────────────────────────────────────
/// <summary>Executes an expression for its side effects. Always returns true.</summary>
@ -327,6 +332,8 @@ internal sealed class ExpressionEngine
"getdatetimelocal" => DateTime.Now.ToString(A(0)),
"getdatetimeutc" => DateTime.UtcNow.ToString(A(0)),
"getunixtime" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture),
// Whole seconds since our last kill; before the first, since the macro start (or login).
"secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture),
// ── World object queries ──────────────────────────────────────────
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
@ -342,7 +349,8 @@ internal sealed class ExpressionEngine
"wobjectfindallinventorybynamerx" => EvalWobjectFindAllInventoryByNameRx(Tmpl(0)),
"wobjectfindininventorybyname" => EvalWobjectFindInInventoryByName(Tmpl(0)),
"wobjectfindininventorybynamerx" => EvalWobjectFindInInventoryByNameRx(Tmpl(0)),
"wobjectfindalllandscapebytemplatetype" => EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebyobjectclass" => EvalWobjectFindAllLandscapeByObjectClass(A(0)),
"wobjectfindalllandscapebytemplatetype" =>EvalWobjectFindAllLandscapeByTemplateType(A(0)),
"wobjectfindalllandscapebynamerx" => EvalWobjectFindAllLandscapeByNameRx(Tmpl(0)),
"wobjectfindallbycontainer" => EvalWobjectFindAllByContainer(A(0)),
"wobjectgetselection" => EvalWobjectGetSelection(),
@ -1635,6 +1643,24 @@ internal sealed class ExpressionEngine
return NewList(items);
}
private string EvalWobjectFindAllLandscapeByObjectClass(string arg)
{
if (_worldObjectCache == null) return "[]";
if (!int.TryParse(arg.Trim(), out int targetClass)) return "[]";
var items = new List<string>();
var seen = new System.Collections.Generic.HashSet<int>();
void Check(WorldObject wo)
{
if (!seen.Add(wo.Id)) return;
if (ResolveEffectiveObjectClass(wo) == targetClass)
items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name));
}
foreach (var wo in _worldObjectCache.GetLandscapeObjects()) Check(wo);
foreach (var wo in _worldObjectCache.GetLandscape()) Check(wo);
return NewList(items);
}
private string EvalWobjectFindAllLandscapeByTemplateType(string arg)
{
if (_worldObjectCache == null || !_host.HasGetObjectWcid) return "[]";
@ -2412,8 +2438,8 @@ internal sealed class ExpressionEngine
{
if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0";
if (!_host.HasSelectItem) return "0";
_host.SelectItem(uid);
return "0";
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid);
return _host.SelectItem(uid) ? "1" : "0";
}
private string EvalActionTryUseItem(string arg)
@ -2440,7 +2466,7 @@ internal sealed class ExpressionEngine
if (!EnsureMagicModeForCast()) return "0";
_host.CastSpell(targetId, spellId);
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
return "1";
}
@ -2486,7 +2512,7 @@ internal sealed class ExpressionEngine
if (!_host.HasGetCurrentCombatMode)
{
// Can't read mode — best-effort flip and bail.
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
return false;
}
@ -2509,7 +2535,7 @@ internal sealed class ExpressionEngine
if (wandId == 0 || !_host.HasUseObject)
{
// No wand (or no UseObject) — try bare-handed magic.
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
return false;
}
@ -2613,7 +2639,7 @@ internal sealed class ExpressionEngine
if (_host.HasChangeCombatMode
&& (now - _castStanceLastFlipAt).TotalMilliseconds > CastStanceFlipGateMs)
{
_host.ChangeCombatMode(CombatMode.Magic);
_host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
_castStanceLastFlipAt = now;
}
return false;
@ -2717,7 +2743,7 @@ internal sealed class ExpressionEngine
if (targetId == 0) targetId = _host.GetPlayerId();
if (targetId == 0) return "2";
_host.CastSpell(targetId, spellId);
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
return "1";
}
@ -2867,7 +2893,11 @@ internal sealed class ExpressionEngine
_ => 0,
};
if (mode == 0) return "0";
return _host.ChangeCombatMode(mode) ? "1" : "0";
if (!_host.HasChangeCombatMode) return "0";
int seq = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
bool ok = _host.ChangeCombatMode(mode);
if (ok) ActionPacer.Begin(_host, PacedKind.CombatMode, 0, ActionPacer.ModeName(mode), "RynthAi/Meta (asked)", seq, mode);
return ok ? "1" : "0";
}
private string EvalGetBusyState()
@ -3306,7 +3336,9 @@ internal sealed class ExpressionEngine
["StopMacroOnNoComponents"] = (() => B(s.StopMacroOnNoComponents), v => s.StopMacroOnNoComponents = ToDouble(v) != 0),
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0),
["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0),
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0),
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
@ -3325,8 +3357,11 @@ internal sealed class ExpressionEngine
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
["BlastRange"] = (() => I(s.BlastRange), v => { if (int.TryParse(v, out int i)) s.BlastRange = i; }),
["MinBlastTargets"] = (() => I(s.MinBlastTargets), v => { if (int.TryParse(v, out int i)) s.MinBlastTargets = i; }),
["WallRange"] = (() => I(s.WallRange), v => { if (int.TryParse(v, out int i)) s.WallRange = i; }),
["MinWallTargets"] = (() => I(s.MinWallTargets), v => { if (int.TryParse(v, out int i)) s.MinWallTargets = i; }),
["HealAt"] = (() => I(s.HealAt), v => { if (int.TryParse(v, out int i)) s.HealAt = i; }),
["RestamAt"] = (() => I(s.RestamAt), v => { if (int.TryParse(v, out int i)) s.RestamAt = i; }),
["RestamTo"] = (() => I(s.RestamTo), v => { if (int.TryParse(v, out int i)) s.RestamTo = i; }),
["GetManaAt"] = (() => I(s.GetManaAt), v => { if (int.TryParse(v, out int i)) s.GetManaAt = i; }),
["TopOffHP"] = (() => I(s.TopOffHP), v => { if (int.TryParse(v, out int i)) s.TopOffHP = i; }),
["TopOffStam"] = (() => I(s.TopOffStam), v => { if (int.TryParse(v, out int i)) s.TopOffStam = i; }),
@ -3371,6 +3406,8 @@ internal sealed class ExpressionEngine
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),
["NavLabelMode"] = (() => I(s.NavLabelMode), v => { if (int.TryParse(v, out int i)) s.NavLabelMode = NavLabelModes.Clamp(i); }),
["NavGuideLine"] = (() => B(s.NavGuideLine), v => s.NavGuideLine = ToDouble(v) != 0),
["CurrentNavPath"] = (() => s.CurrentNavPath, v => s.CurrentNavPath = v),
["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v),
["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v),

View file

@ -728,6 +728,19 @@ getunixtime[]
Example: setvar[t, getunixtime[]] → snapshot a timestamp
Example: getunixtime[] - getvar[t] > 60 → true if 60s have elapsed
secondssincelastkill[]
Returns the whole number of seconds since your character's last kill.
Only kills credited to you count (the server's "you killed it" notice);
deaths you only see in chat, and your fellows' kills, do not.
Before your first kill this session it counts from when the macro was last
started, or from login (or a RynthAi reload) if the macro hasn't been started
since, so a meta can still react when nothing has been killed at all.
After a kill it is always the time since that kill, also across a macro stop/start.
The meta condition "No Kills Within Minutes" (.af: NoKillsInMins 5) uses the same clock.
Test in chat: /ra mexec secondssincelastkill[]
Example: secondssincelastkill[] → e.g. "42"
Example: secondssincelastkill[] >= 300 → true after 5 minutes without a kill
getaccounthash[]
Returns a lowercase MD5 hex string of the current account name.
Returns "" (empty string) if the account name is not yet available.

View file

@ -145,6 +145,15 @@ internal sealed class MetaManager
_expressions?.SetCreatureStore(store);
}
// The plugin's kill clock (secondssincelastkill[], No Kills Within Minutes). Without one
// (never in the plugin) the condition is false and the function says 0: fail closed.
private KillClock? _killClock;
public void SetKillClock(KillClock? clock)
{
_killClock = clock;
_expressions?.SetKillClock(clock);
}
public void SetPlayerId(uint id)
{
_playerId = id;
@ -201,6 +210,7 @@ internal sealed class MetaManager
engine.SetQuestTracker(_questTracker);
engine.SetSettings(_settings);
engine.SetCreatureStore(_creatureStore);
engine.SetKillClock(_killClock);
return engine;
}
@ -728,6 +738,14 @@ internal sealed class MetaManager
case MetaConditionType.NeedToBuff:
return _buffManager != null && _buffManager.NeedsAnyBuff();
// ── No kills within N minutes (RynthAi only) ──────────────────────
// The secondssincelastkill[] clock: our last kill (KillerNotification), or before
// the first one the last macro start / login. Bad or missing minutes never hold.
case MetaConditionType.NoKillsWithinMinutes:
return _killClock != null
&& KillClock.TryParseMinutes(rule.ConditionData, out double noKillMins)
&& _killClock.NoKillsFor(noKillMins);
default: return false;
}
}
@ -893,7 +911,7 @@ internal sealed class MetaManager
}
// Fallback: a standalone .nav file in NavProfiles.
string navFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"NavProfiles");
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
string fullPath = Path.Combine(navFolder, routeName + ".nav");
if (File.Exists(fullPath))
{
@ -1092,7 +1110,7 @@ internal sealed class MetaManager
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
string metaDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
string metaDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
string afPath = Path.Combine(metaDir, name + ".af");
string metPath = Path.Combine(metaDir, name + ".met");
@ -1156,7 +1174,7 @@ internal sealed class MetaManager
string path = name;
if (!File.Exists(path))
{
string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
string stem = name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
? name : name + ".utl";
string candidate = Path.Combine(folder, stem);

View file

@ -0,0 +1,52 @@
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// How a rule edited in the Meta panel replaces the running one (update_rule / duplicate_rule).
///
/// The engine's Meta editor saves every change on its own since 2026-10-05 (debounced), so an
/// update must not disturb a meta that is running:
/// - the rule keeps its runtime latch (HasFired) and LastFiredAt. A fresh MetaRule had
/// HasFired = false, so every save of a rule in the current state fired it again
/// (an IF Always DO EmbedNav rule restarted its route from point 0 on each save);
/// - the panel's DTO has no CallReturnState (CallState's return state) or ChatColors
/// (ChatCapture's chat types), so an update used to drop both from VTank-imported rules.
/// They are kept while the rule still has that action / condition.
/// Nothing here touches the current state, the state clocks, the watchdog or the call stack.
/// </summary>
internal static class MetaRuleEdits
{
/// <summary>Puts <paramref name="edited"/> at <paramref name="index"/>, keeping the old rule's
/// runtime latch and the fields the panel can't send. False when the index is out of range.</summary>
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited)
{
if (index < 0 || index >= rules.Count) return false;
MetaRule old = rules[index];
KeepHidden(old, edited);
edited.HasFired = old.HasFired;
edited.LastFiredAt = old.LastFiredAt;
rules[index] = edited;
return true;
}
/// <summary>Copies CallReturnState / ChatColors from <paramref name="from"/> into an edited copy
/// that still has the same action / condition and carries none of its own; children by position.</summary>
public static void KeepHidden(MetaRule from, MetaRule to)
{
if (to.Action == MetaActionType.CallMetaState && from.Action == MetaActionType.CallMetaState
&& string.IsNullOrEmpty(to.CallReturnState))
to.CallReturnState = from.CallReturnState;
if (to.Condition == MetaConditionType.ChatMessageCapture && from.Condition == MetaConditionType.ChatMessageCapture
&& string.IsNullOrEmpty(to.ChatColors))
to.ChatColors = from.ChatColors;
if (from.Children != null && to.Children != null)
for (int i = 0; i < from.Children.Count && i < to.Children.Count; i++)
KeepHidden(from.Children[i], to.Children[i]);
if (from.ActionChildren != null && to.ActionChildren != null)
for (int i = 0; i < from.ActionChildren.Count && i < to.ActionChildren.Count; i++)
KeepHidden(from.ActionChildren[i], to.ActionChildren[i]);
}
}

View file

@ -72,6 +72,8 @@ internal static class MetaSchema
new(MetaConditionType.MainManaPHE, "MainManaPHE", "Main Mana % >="),
new(MetaConditionType.MainStamLE, "MainStamLE", "Main Stam <="),
new(MetaConditionType.VitaePHE, "VitaePHE", "Vitae % >="),
// RynthAi only: VTank and metaf have no such condition (see AfFileWriter).
new(MetaConditionType.NoKillsWithinMinutes, "NoKillsInMins", "No Kills Within Minutes"),
};
// Index == (int)MetaActionType.

View file

@ -3,6 +3,7 @@ using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
@ -253,6 +254,13 @@ internal sealed class NavMarkerRenderer
int n = route.Points.Count;
bool circular = route.RouteType == NavRouteType.Circular;
// ── Waypoint labels and guide line (both off by default) ─────
// Worked out from the route here, on the plugin tick, into an immutable frame; the
// emit steps read only that frame. The guide goes in first so the route's lines can't
// crowd it out of the engine's line buffer; the labels go in last (pass 4).
NavOverlayFrame overlay = BuildOverlay(route, px, py, pz, playerNS, playerEW, heightOffset);
NavOverlay.EmitGuide(overlay, _sink ??= new HostNav3DSink(_host), lineThick);
// ── Pass 1: Submit rings ─────────────────────────────────────
// Arrays are indexed by window slot k (0..count), not absolute route
// index — the absolute index can run far past count on a long route.
@ -343,6 +351,68 @@ internal sealed class NavMarkerRenderer
_host.Nav3DAddRing(pwx, pwy, pwz, ringRadius, ringThick * 1.4f, ColorPortal3D);
_host.Nav3DAddLine(px, pwy, py, pwx, pwy, pwz, lineThick, ColorPortal3D);
}
// ── Pass 4: waypoint labels (filled strokes, Nav3D triangles) ─
if (overlay.Labels.Count > 0 && _host.HasNav3DTriangle)
NavOverlay.EmitLabels(overlay, _sink);
}
// ── Labels and guide line ────────────────────────────────────────
private NavOverlay.RouteText? _labelText;
private INav3DSink? _sink;
/// <summary>
/// The tick's labels and guide line from the route and the two settings (Navigation ▸
/// Waypoint Labels / Guide Line). Plugin tick only; returns an immutable frame.
/// </summary>
internal NavOverlayFrame BuildOverlay(NavRouteParser route, float px, float py, float pz,
double playerNS, double playerEW, float heightOffset)
{
int mode = NavLabelModes.Clamp(_settings.NavLabelMode);
bool guideOn = _settings.NavGuideLine;
if (mode == NavLabelModes.Off && !guideOn)
{
_labelText = null;
return NavOverlayFrame.Empty;
}
var points = route.Points;
int n = points.Count;
NavOverlay.RouteText? text = null;
if (mode != NavLabelModes.Off)
{
// Rebuilt only when the route, its length or the mode change (an edit in place keeps
// the count: the Nav panel's edits replace the route or change its length).
text = _labelText;
if (text == null || !ReferenceEquals(text.Route, route) || text.Count != n || text.Mode != mode)
_labelText = text = NavOverlay.BuildText(route, points, mode, SpellDatabase.GetSpellNameOrId);
}
else _labelText = null;
int active = _settings.ActiveNavIndex;
bool guide = guideOn && active >= 0 && active < n && HasGroundCoords(points[active].Type);
(float X, float Y, float Z) WorldOf(int i)
{
var pt = points[i];
return (px + (float)((pt.EW - playerEW) * 240.0),
ResolveMarkerWorldY(route, i, heightOffset),
py + (float)((pt.NS - playerNS) * 240.0));
}
// D3D frame: X = EW, Y = height, Z = NS; the player's height is pose z.
return NavOverlay.BuildFrame(text, guide, active, WorldOf, px, pz, py, heightOffset);
}
/// <summary>The engine's Nav3D buffer.</summary>
private sealed class HostNav3DSink : INav3DSink
{
private readonly RynthCoreHost _host;
public HostNav3DSink(RynthCoreHost host) => _host = host;
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
=> _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb);
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb)
=> _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb);
}
private void PrepareFloorCache(NavRouteParser route)

View file

@ -0,0 +1,234 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>Settings ▸ Navigation ▸ "Waypoint Labels" (LegacyUiSettings.NavLabelMode).</summary>
internal static class NavLabelModes
{
public const int Off = 0, Numbers = 1, Names = 2;
public static int Clamp(int mode) => mode is >= Off and <= Names ? mode : Off;
}
/// <summary>
/// One tick's waypoint labels and guide line, worked out from the route on the plugin tick and
/// then never changed: the emit step reads only this, never the route's lists. Positions are in
/// the Nav3D frame NavMarkerRenderer uses (X = east metres, Y = height, Z = north metres, in
/// the player's landblock).
/// </summary>
internal sealed class NavOverlayFrame
{
public static readonly NavOverlayFrame Empty = new(Array.Empty<NavLabel>(), null, 0f, 0f, 0f);
public NavOverlayFrame(NavLabel[] labels, NavGuide? guide, float playerX, float playerY, float playerZ)
{
Labels = labels;
Guide = guide;
PlayerX = playerX;
PlayerY = playerY;
PlayerZ = playerZ;
}
public IReadOnlyList<NavLabel> Labels { get; }
public NavGuide? Guide { get; }
public float PlayerX { get; }
public float PlayerY { get; }
public float PlayerZ { get; }
}
/// <summary>One text line over a waypoint. Row 0 sits just above the ring; higher rows stack above it.</summary>
internal sealed record NavLabel(float X, float Y, float Z, string Text, int Row, uint Color);
/// <summary>The line from the character's feet to the waypoint nav is heading for.</summary>
internal sealed record NavGuide(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint Color);
/// <summary>
/// Waypoint labels (numbers, or numbers and what happens there) and the guide line for the Nav3D
/// markers (Silentkelpie's rynth PR #1 idea, done on our pump-thread Nav3D path). Both are off by
/// default. Labels are drawn as filled strokes (Nav3D triangles) on an upright plane turned toward
/// the character, sized up with distance so far labels stay readable; the guide is one Nav3D line.
/// </summary>
internal static class NavOverlay
{
/// <summary>Labels further than this from the character are left out (metres).</summary>
public const float LabelRange = 60f;
/// <summary>At most this many label lines a tick, nearest first (the active point's always first).</summary>
public const int MaxLabelLines = 24;
/// <summary>At most this many action lines stacked over one point.</summary>
public const int MaxActionLines = 3;
/// <summary>Triangle budget for all labels together (the engine keeps 8192 a tick for every plugin).</summary>
public const int MaxLabelTriangles = 1600;
public const int MaxLabelChars = 22;
public const uint LabelColor = 0xFFE6FFFF; // near white, a cyan touch like the rings
public const uint ActiveLabelColor = 0xFFFF6A6A;
public const uint ActionLabelColor = 0xFFFFC040;
public const uint GuideColor = 0xFFFFD21E;
private const float GuideLift = 0.05f;
private const float MaxGuideLength = 500f;
// ── Text per route (rebuilt when the route or the mode changes) ──────
/// <summary>
/// Label text for every route point, built once per route and mode: <c>Own[i]</c> for a point
/// with ground coordinates (null otherwise), and the action lines ("13 RECALL ...") hung on
/// the ground point before them (the point where nav does them).
/// </summary>
internal sealed class RouteText
{
public readonly object Route;
public readonly int Count, Mode;
public readonly string?[] Own;
public readonly string[]?[] Actions;
public RouteText(object route, int count, int mode, string?[] own, string[]?[] actions)
{
Route = route; Count = count; Mode = mode; Own = own; Actions = actions;
}
}
public static RouteText BuildText(object route, IReadOnlyList<NavPoint> points, int mode, Func<int, string> spellName)
{
int n = points.Count;
var own = new string?[n];
var actions = new string[]?[n];
var pending = new List<string>();
int lastGround = -1;
for (int i = 0; i < n; i++)
{
NavPoint p = points[i];
if (HasGroundCoords(p.Type))
{
own[i] = mode == NavLabelModes.Names ? Fit(GroundName(i, p)) : i.ToString();
lastGround = i;
continue;
}
if (mode != NavLabelModes.Names || lastGround < 0) continue;
var list = actions[lastGround] ??= Array.Empty<string>();
if (list.Length < MaxActionLines)
actions[lastGround] = Append(list, Fit(ActionName(i, p, spellName)));
else if (list.Length == MaxActionLines)
actions[lastGround] = Append(list, "...");
}
return new RouteText(route, n, mode, own, actions);
}
private static string[] Append(string[] a, string s)
{
var b = new string[a.Length + 1];
Array.Copy(a, b, a.Length);
b[a.Length] = s;
return b;
}
private static bool HasGroundCoords(NavPointType t) => NavRouteParser.IsPlainWaypoint(t) || t == NavPointType.Jump;
private static string GroundName(int i, NavPoint p) => p.Type switch
{
NavPointType.Checkpoint => $"{i} CHECKPOINT",
NavPointType.Jump => $"{i} JUMP",
_ => i.ToString(),
};
private static string ActionName(int i, NavPoint p, Func<int, string> spellName) => p.Type switch
{
NavPointType.Recall => $"{i} {spellName(p.SpellId)}",
NavPointType.Pause => $"{i} PAUSE {Math.Max(0, p.PauseTimeMs) / 1000.0:0.#}S",
NavPointType.Chat => $"{i} CHAT {p.ChatCommand}",
NavPointType.OpenVendor => $"{i} VENDOR {p.TargetName}",
NavPointType.PortalNPC => $"{i} PORTAL {p.TargetName}",
NavPointType.Npc => $"{i} NPC {p.TargetName}",
_ => $"{i} {p.Type}",
};
private static string Fit(string s)
{
s = s.Trim().ToUpperInvariant();
return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s;
}
// ── The frame (plugin tick) ───────────────────────────────────────
/// <summary>
/// Builds the tick's overlay from <paramref name="text"/> (null: no labels) and the waypoints'
/// positions (<paramref name="worldOf"/>, only asked for points that have ground coordinates).
/// <paramref name="active"/> is the point nav is heading for; <paramref name="guide"/> draws the
/// line to it (the caller passes false when that point has no ground coordinates). Plugin tick only.
/// </summary>
public static NavOverlayFrame BuildFrame(RouteText? text, bool guide, int active,
Func<int, (float X, float Y, float Z)> worldOf, float playerX, float playerY, float playerZ, float lift)
{
NavGuide? g = null;
if (guide && active >= 0)
{
var (ax, ay, az) = worldOf(active);
float dx = ax - playerX, dz = az - playerZ;
if (dx * dx + dz * dz <= MaxGuideLength * MaxGuideLength)
g = new NavGuide(playerX, playerY + lift + GuideLift, playerZ, ax, ay, az, GuideColor);
}
if (text == null || text.Mode == NavLabelModes.Off)
return g == null ? NavOverlayFrame.Empty : new NavOverlayFrame(Array.Empty<NavLabel>(), g, playerX, playerY, playerZ);
// Ground points in range, nearest first; the active point first of all.
var near = new List<(float D2, int I, float X, float Y, float Z)>();
float range2 = LabelRange * LabelRange;
for (int i = 0; i < text.Count; i++)
{
if (text.Own[i] == null) continue;
var (x, y, z) = worldOf(i);
float dx = x - playerX, dz = z - playerZ;
float d2 = dx * dx + dz * dz;
if (d2 > range2) continue;
near.Add((i == active ? -1f : d2, i, x, y, z));
}
near.Sort((a, b) => a.D2.CompareTo(b.D2));
var labels = new List<NavLabel>(Math.Min(MaxLabelLines, near.Count * 2));
foreach (var (_, i, x, y, z) in near)
{
if (labels.Count >= MaxLabelLines) break;
labels.Add(new NavLabel(x, y, z, text.Own[i]!, 0, i == active ? ActiveLabelColor : LabelColor));
string[]? acts = text.Actions[i];
if (acts == null) continue;
for (int k = 0; k < acts.Length && labels.Count < MaxLabelLines; k++)
labels.Add(new NavLabel(x, y, z, acts[k], k + 1, ActionLabelColor));
}
return new NavOverlayFrame(labels.ToArray(), g, playerX, playerY, playerZ);
}
// ── Emit (plugin tick, into the Nav3D buffer) ──────────────────────
/// <summary>The guide line, if the frame has one: submitted before the route's lines so a full line buffer never drops it.</summary>
public static void EmitGuide(NavOverlayFrame frame, INav3DSink sink, float thickness)
{
NavGuide? g = frame.Guide;
if (g != null)
sink.Line(g.X1, g.Y1, g.Z1, g.X2, g.Y2, g.Z2, thickness, g.Color);
}
/// <summary>
/// Each label as filled strokes (triangles). Returns the number of triangles used (at most
/// <see cref="MaxLabelTriangles"/>).
/// </summary>
public static int EmitLabels(NavOverlayFrame frame, INav3DSink sink)
{
int tris = 0;
foreach (NavLabel l in frame.Labels)
{
if (!EmitLabel(l, frame.PlayerX, frame.PlayerZ, sink, ref tris)) break;
}
return tris;
}
/// <summary>The line height (m) for a label this far from the character.</summary>
internal static float LineHeight(float distance) => Nav3DText.LineHeight(distance);
// The text itself is drawn by the shared Nav3DText (Plugins/Shared/Nav3DText.cs), which
// RynthNav's path markers use too.
private static bool EmitLabel(NavLabel l, float playerX, float playerZ, INav3DSink sink, ref int tris)
=> Nav3DText.Emit(l.X, l.Y, l.Z, l.Text, l.Row, l.Color, playerX, playerZ, sink, ref tris, MaxLabelTriangles);
}

View file

@ -75,7 +75,16 @@ internal sealed class NavigationEngine
private bool _inPause;
private int _pauseIdx = -1; // the Pause waypoint _pauseUntil belongs to
private long _pauseUntil;
private double _prevDist = double.MaxValue;
// Closest the character has come to the current waypoint since it became the target (or
// since a pause / escape / teleport reset it). It used to hold only the previous tick's
// distance, so a "sweep pass" needed the distance to grow 0.3 yd in ONE 33 ms tick (over
// 9 yd/s straight away from the point): just past a point the distance grows slowly, the
// pass was never seen, and nav turned round and walked back to the point (2026-10-05).
private double _closestDist = double.MaxValue;
// Where the character stood when it started on the current waypoint (NaN = take it on the
// next steering tick). With the waypoint it gives the way the route arrives at the point,
// for the pass-through rule (PassedThrough).
private double _legStartNs = double.NaN, _legStartEw = double.NaN;
// ── Portal/Recall state machine ──────────────────────────────────────────
private enum PortalState
@ -147,7 +156,7 @@ internal sealed class NavigationEngine
public int Doorways;
public long StartedAt;
public long DeadlineAt;
public double PrevDist = double.MaxValue;
public double ClosestDist = double.MaxValue; // closest to the current detour point so far
public bool Paused; // nav was stopped (combat, loot, buff, door) mid-detour
public long PausedAt;
public double PausedNs = double.NaN, PausedEw = double.NaN;
@ -244,10 +253,39 @@ internal sealed class NavigationEngine
private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards;
private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult);
// Lookahead: within this distance of a waypoint, blend the aim point toward
// the next one so corners are cut smoothly. 0 = off (aim straight at each
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
// Lookahead (corner rounding): within this distance of a waypoint, blend the aim point
// toward the next one so corners are rounded. It used to be the Lookahead setting alone
// (4 yd), whatever the nav point reach: at a 1 yd reach the aim was already 75% of the way
// down the next leg when the character got to 1 yd, so it cut the corner, never got within
// the reach, and ran into the wall at the corner (2026-10-05). Now the reach decides how
// much rounding there is: none at or under CornerRoundFreeReachYd, then CornerRoundPerReachYd
// per yard of reach above it, never more than the Lookahead setting (Advanced > Navigation >
// Steering; 0 = off). Blending only matters where it starts outside the reach, so there is
// none up to a 2 yd reach (the 1.5 yd default gives 1 yd, inside it); it reaches the 4 yd
// setting at a 3 yd reach, so 3-5 yd round corners as before. Doorway points never blend.
internal const double CornerRoundFreeReachYd = 1.0, CornerRoundPerReachYd = 2.0;
internal static double CornerLookaheadYards(double lookaheadSetting, double reachYd)
=> Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting));
private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards);
// Pass-through: a plain waypoint the character has gone past (it is beyond the point along
// the way it came, and no farther to the side than the sweep radius) counts as reached,
// so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the
// point is behind the character: a corner cut toward the next point never qualifies.
// Doorway points keep their own tight reach and sweep and never use it.
private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction
private bool PassedThrough(NavPoint pt, double ns, double ew)
{
if (pt.Doorway || double.IsNaN(_legStartNs)) return false;
double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0;
double len = Math.Sqrt(ux * ux + uy * uy);
if (len < PassMinLegYd) return false;
ux /= len; uy /= len;
double ax = (ns - pt.NS) * 240.0, ay = (ew - pt.EW) * 240.0;
double along = ax * ux + ay * uy;
double side = Math.Abs(ax * uy - ay * ux);
return along > 0.0 && side <= SweepFor(pt);
}
// Mode 0 heading servo: cap the heading change we command per tick so the
@ -411,7 +449,7 @@ internal sealed class NavigationEngine
{
_lastRoute = route;
_inPause = false;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_linearDir = 1;
_watchdogNs = double.NaN;
_watchdogEw = double.NaN;
@ -462,7 +500,7 @@ internal sealed class NavigationEngine
_watchdogNs = double.NaN;
_watchdogEw = double.NaN;
_watchdogNext = Now + (long)WatchdogMs;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_globalSettling = false;
ResetRecovery("teleported");
}
@ -582,7 +620,7 @@ internal sealed class NavigationEngine
if (dist < ReachFor(pt))
{
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing");
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
UpdateStatusLine(idx, dist, route, 0.0);
// Advance before the jump: the Jumper pauses nav and later restores what it
// saw, so jumping first turned a finished Once route back on (re-run from [0]).
@ -591,17 +629,33 @@ internal sealed class NavigationEngine
return;
}
// Closest-approach detection — prevents circling.
// Matches old NavigationManager exactly.
if (_prevDist < SweepFor(pt) && dist > _prevDist + 0.3)
// First tick on this waypoint (or after a pause / escape / teleport): remember where
// the approach starts, for the pass-through rule.
if (_closestDist == double.MaxValue) { _legStartNs = ns; _legStartEw = ew; }
// Went past it: the point is behind, close enough to the side. Counts as reached
// instead of turning round to walk back to it.
if (PassedThrough(pt, ns, ew))
{
_host.Log($"Nav: sweep-pass [{idx}] prev={_prevDist:F1} now={dist:F1}yd → advancing");
_prevDist = double.MaxValue;
_host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing");
_closestDist = double.MaxValue;
UpdateStatusLine(idx, dist, route, 0.0);
Advance(route);
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
return;
}
_prevDist = dist;
// Closest-approach detection — prevents circling: within the sweep radius, then
// 0.3 yd farther out than the closest it came.
if (_closestDist < SweepFor(pt) && dist > _closestDist + 0.3)
{
_host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing");
_closestDist = double.MaxValue;
Advance(route);
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
return;
}
_closestDist = Math.Min(_closestDist, dist);
SteerToWaypoint(idx, pt, route, ns, ew, dist);
}
@ -622,7 +676,7 @@ internal sealed class NavigationEngine
// closest-approach reading from before the pause says nothing about where we
// are now; kept, the first tick back reads the displacement as a sweep-pass
// and advances past a waypoint that was never reached.
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_stopRequestedAt = long.MaxValue;
// A detour survives the pause: it re-plans on the way back if the pause
// moved us. Whatever moved us, being far off the route afterwards is not
@ -689,7 +743,7 @@ internal sealed class NavigationEngine
_host.Log($"Nav: macro start — {how} waypoint [{best}] ({Math.Sqrt(Sq(route.Points[best].NS - ns) + Sq(route.Points[best].EW - ew)) * 240.0:F0}yd) instead of [{cur}]");
_settings.ActiveNavIndex = best;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_stuckCount = 0;
_watchdogNs = double.NaN;
_watchdogEw = double.NaN;
@ -747,7 +801,7 @@ internal sealed class NavigationEngine
_linearDir = 1;
_stuckCount = 0;
_recoveryKind = RecoveryKind.Jump;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_watchdogNs = double.NaN;
_watchdogEw = double.NaN;
_hasGoodHeading = false;
@ -1146,7 +1200,7 @@ internal sealed class NavigationEngine
private void Advance(NavRouteParser route)
{
int oldIdx = _settings.ActiveNavIndex;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_portalState = PortalState.None;
// Reaching a waypoint is progress: the next snag gets a fresh detour budget.
_detourAttempts = 0;
@ -1238,7 +1292,7 @@ internal sealed class NavigationEngine
/// current route's iteration direction. Used by the dense-waypoint
/// skip loop in <see cref="Advance"/>. Mirrors the single-step logic
/// in the main switch; factored out so the skip loop can call it
/// without re-clearing _prevDist / _portalState.
/// without re-clearing _closestDist / _portalState.
/// </summary>
private void AdvanceOneIndex(NavRouteParser route)
{
@ -1352,7 +1406,7 @@ internal sealed class NavigationEngine
private void HoldAtCampRoute(int idx, double dist, NavRouteParser route)
{
if (_isMovingForward || _isTurning) StopMovement();
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
UpdateStatusLine(idx, dist, route, 0.0);
if (!_campHoldAnnounced)
{
@ -1448,7 +1502,7 @@ internal sealed class NavigationEngine
_host.Log($"Nav: no player id — cannot fire recall {pt.SpellId}");
return;
}
_host.CastSpell(target, pt.SpellId);
_host.CastSpellFor(target, pt.SpellId, "Nav", $"recall spell {pt.SpellId}");
_host.Log($"Nav: CastSpell(recall {pt.SpellId}) on player 0x{target:X8}");
}
@ -1707,7 +1761,7 @@ internal sealed class NavigationEngine
// teleport happened but wasn't seen, or the route stays on this side).
if (NextWalkTargetBeyond(route, _settings.ActiveNavIndex, OffTrackYards, out int farIdx, out double farYd))
{
string what = pt.Type == NavPointType.Recall ? $"the recall (spell {pt.SpellId})" : $"the portal '{pt.TargetName}'";
string what = pt.Type == NavPointType.Recall ? $"the recall ({NavPoint.RecallName(pt.SpellId)})" : $"the portal '{pt.TargetName}'";
string msg = $"Nav: {what} didn't teleport within {ActionTimeoutMs / 1000:F0}s, and the next waypoint [{farIdx}] is {farYd:F0}yd away - navigation stopped.";
_host.Log(msg);
_host.WriteToChat(msg, 1);
@ -2229,7 +2283,7 @@ internal sealed class NavigationEngine
// The escape moves us off the approach line, so the closest-approach
// tracker's last reading is meaningless — reset it or the next steer
// tick reads the retreat as a sweep-pass and advances the index.
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
}
// ══════════════════════════════════════════════════════════════════════════
@ -2577,7 +2631,7 @@ internal sealed class NavigationEngine
StopMovement();
_inRecovery = false;
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
_settings.NavIsStuck = true;
return true;
}
@ -2604,7 +2658,7 @@ internal sealed class NavigationEngine
+ $"reached {Math.Min(d.Index, d.Points.Count)}/{d.Points.Count}, door requests {d.DoorRequestCount}, re-plans {d.Replans}, "
+ $"{(Now - d.StartedAt) / 1000.0:F1}s - result: {result}");
_prevDist = double.MaxValue;
_closestDist = double.MaxValue;
if (!_inRecovery) _settings.NavIsStuck = false;
}
@ -2635,7 +2689,7 @@ internal sealed class NavigationEngine
// against the deadline; if the pause moved us, plan again from here.
d.Paused = false;
d.DeadlineAt += Now - d.PausedAt;
d.PrevDist = double.MaxValue;
d.ClosestDist = double.MaxValue;
double moved = double.IsNaN(d.PausedNs) ? 0.0 : NavYd(ns - d.PausedNs, ew - d.PausedEw);
if (moved > DetourReplanMovedYd && !ReplanDetour(route, d, moved)) return;
}
@ -2650,10 +2704,10 @@ internal sealed class NavigationEngine
var p = d.Points[d.Index];
double dist = NavYd(p.NS - ns, p.EW - ew);
if (dist < ReachFor(p) || (d.PrevDist < SweepFor(p) && dist > d.PrevDist + 0.3))
if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3))
{
d.Index++;
d.PrevDist = double.MaxValue;
d.ClosestDist = double.MaxValue;
if (d.Index >= d.Points.Count)
{
// Back on the route: resume at the rejoin waypoint; normal nav walks the last leg.
@ -2662,7 +2716,7 @@ internal sealed class NavigationEngine
}
return;
}
d.PrevDist = dist;
d.ClosestDist = Math.Min(d.ClosestDist, dist);
// Aim point: blend toward the following point near arrival, but less than the
// route does (doorways are narrow).

View file

@ -50,7 +50,7 @@ internal sealed class RadarWallRenderer
private readonly bool[] _inside = new bool[MaxPolyVerts];
private static readonly string ExploredDir =
System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"ExploredDungeons");
System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ExploredDungeons");
public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings)
{

View file

@ -36,6 +36,8 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra attackable — check if target is attackable");
ChatLine("[RynthAi] /ra wielded — show wielded items");
ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)");
ChatLine("[RynthAi] /ra t11 [augs <n|auto>|refresh|item] — T11 loot: wield counters, aug override, parsed item");
ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style");
ChatLine("[RynthAi] /ra mexec <expr> — evaluate meta expression");
ChatLine("[RynthAi] /ra listvars — show session variables");
ChatLine("[RynthAi] /ra listpvars — show persistent variables");
@ -68,6 +70,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)");
ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics");
ChatLine("[RynthAi] /ra pace — what the server is still answering (one action at a time)");
ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop");
ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted");
ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow");
@ -240,7 +243,7 @@ public sealed partial class RynthAiPlugin
return;
}
bool ok = Host.CastSpell(_currentTargetId, spellId);
bool ok = Host.CastSpellFor(_currentTargetId, spellId, "Command", $"spell {spellId} (/ra cast)", asked: true);
ChatLine($"[RynthAi] CastSpell(target=0x{_currentTargetId:X8}, spell={spellId}) => {ok}");
}
@ -1600,8 +1603,12 @@ public sealed partial class RynthAiPlugin
if (inUse) ReloadLootProfileInUse(d.TargetPath);
}
/// <summary>What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache.</summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like)
/// <summary>
/// What a loot rule can be built from: the item's name, class, stack, key properties and
/// T11 reading, from the object cache. <paramref name="like"/> adds its spells;
/// <paramref name="t11"/> asks for an ID when a T11 item's text hasn't arrived.
/// </summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
if (wo == null) return null;
@ -1631,6 +1638,10 @@ public sealed partial class RynthAiPlugin
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
}
// Always read (a cached parse), so the popup knows whether the T11 option applies.
f.T11 = Loot.T11ItemSupport.Get(wo);
// T11 tier, grade and modifiers are appraisal text: ask for it, so the next preview has them.
if (t11 && f.T11.IsT11 && !f.T11.HasText && Host.HasRequestId) Host.RequestId(itemId);
return f;
}
@ -1653,17 +1664,18 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview]: a rule for
/// the selected item, straight into the loot profile in use (the defaults: exact
/// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep).
/// t11 also requires the item's T11 attributes.
/// </summary>
private void HandleLootCommand(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
if (sub != "add")
{
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing.");
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing.");
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor.");
return;
}
@ -1683,6 +1695,7 @@ public sealed partial class RynthAiPlugin
case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break;
case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break;
case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break;
case "t11": req.IncludeT11 = true; break;
case "preview":
case "?": preview = true; break;
default:
@ -1692,7 +1705,7 @@ public sealed partial class RynthAiPlugin
req.KeepCount = n;
break;
}
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview.");
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like, t11 or preview.");
return;
}
}
@ -2148,6 +2161,8 @@ public sealed partial class RynthAiPlugin
private void HandleClearBusyCommand()
{
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
// You asked for it: forget what the pacing waits on too (ActionPacer).
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra clearbusy");
if (Host.HasForceResetBusyCount)
Host.ForceResetBusyCount();
if (Host.HasStopCompletely)
@ -2171,9 +2186,10 @@ public sealed partial class RynthAiPlugin
{
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
ChatLine("[RynthAi] PANIC — full AC state reset");
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra panic");
if (Host.HasCancelAttack) Host.CancelAttack();
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
if (Host.HasChangeCombatMode) Host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true);
if (Host.HasStopCompletely) Host.StopCompletelyBy("Command");
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
// The item-action lock itself is not the busy count: AC refuses every use,
@ -2612,7 +2628,7 @@ public sealed partial class RynthAiPlugin
string playerPart = argStr.Substring(toIdx + 4).Trim();
// Resolve profile path — bare name resolved from ItemGiver dir, .utl extension added if needed
const string itemGiverDir = @"C:\Games\RynthSuite\RynthAi\ItemGiver";
string itemGiverDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
string profilePath = System.IO.Path.IsPathRooted(profileArg)
? profileArg
: System.IO.Path.Combine(itemGiverDir, profileArg);
@ -2873,6 +2889,11 @@ public sealed partial class RynthAiPlugin
return;
}
settings.IsMacroRunning = true;
// The patrol picked its own start (the first waypoint in sight). Starting the macro
// here must not also trigger the macro-start "nearest waypoint" pick on the next
// tick: on a loop that is often a waypoint near the END (it comes back to the start),
// so the bot walked there, back to waypoint 0, and only then on (2026-10-08).
_macroWasRunning = true;
}
settings.CurrentNavPath = string.Empty;
settings.CurrentRoute = route;
@ -2975,7 +2996,7 @@ public sealed partial class RynthAiPlugin
sb.Append("\"routes\":[");
try
{
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
if (System.IO.Directory.Exists(navFolder))
{
var files = System.IO.Directory.GetFiles(navFolder, "*.nav");

View file

@ -1,381 +0,0 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using System.Threading;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.ItemInfo;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra iteminfo — Mag-style item info (ratings, damage, spells, slayer, imbues …) as one line or
/// as pet-roster style lines, printed on demand, on select or on a left/right mouse click;
/// ported from UtilityBelt ub-IT / Mag-Tools ItemInfo. Partial class of RynthAiPlugin.
///
/// /ra iteminfo describe the selected item (IDs it first when needed)
/// /ra iteminfo on|off describe every item you select
/// /ra iteminfo settings open/close the Item Info settings window
/// /ra iteminfo fields list fields and ratings with their on/off state
/// /ra iteminfo field &lt;name&gt; on|off show/hide one field (ratings, slayer, spells, …)
/// /ra iteminfo rating &lt;tag&gt; on|off show/hide one rating (D, CD, CDR, …)
/// /ra iteminfo value on|off append value + burden
/// /ra iteminfo verbose on|off list every spell instead of Mag's filter
/// /ra iteminfo click left|right|off print the selected item after a mouse click
/// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner
/// /ra iteminfo reset restore defaults
/// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi).
/// </summary>
public sealed partial class RynthAiPlugin
{
// One pending describe at a time: the newest request replaces the previous one.
private int _itemInfoPendingId;
private long _itemInfoPendingSince;
// Automatic triggers (select + click) can both fire for one click; the same item inside
// this window prints once.
private const long AutoDedupeMs = 1500;
private int _itemInfoLastAutoId;
private long _itemInfoLastAutoAt;
// Click trigger. A press counts as a click only if it started outside every overlay window,
// was released within ClickMaxHoldMs and moved at most ClickMaxMovePx — so item drags and
// right-button mouse-look never print. The client updates the selection after it handles
// the click, so the selection is read ClickSettleMs after the release, on the tick thread.
private const long ClickMaxHoldMs = 600;
private const float ClickMaxMovePx = 6f;
private const long ClickSettleMs = 150;
private bool _iiClickPrevDown;
private bool _iiClickArmed;
private long _iiClickPressAt;
private Vector2 _iiClickPressPos;
private long _iiClickResolveAt; // TickCount64 to read the selection at; 0 = none (Interlocked)
/// <summary>Character settings when loaded, else null (commands then use defaults / refuse edits).</summary>
private MagItemInfoSettings? ItemInfoSettings => _dashboard?.Settings.ItemInfoSettings;
private void HandleItemInfoCommand(string[] parts)
{
var s = ItemInfoSettings;
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
string arg3 = parts.Length >= 4 ? parts[3] : string.Empty;
string arg4 = parts.Length >= 5 ? parts[4] : string.Empty;
if (sub.Length == 0)
{
PrintSelectedItemInfo();
return;
}
if (s == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
switch (sub)
{
case "settings":
case "gui":
case "window":
s.ShowWindow = !s.ShowWindow;
ChatLine($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}.");
return;
case "value":
if (ParseOnOff(arg3) is bool v) s.ShowValueAndBurden = v;
ChatLine($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}");
return;
case "verbose":
if (ParseOnOff(arg3) is bool all)
s.SpellMode = all ? MagItemInfoSettings.SpellModeAll : MagItemInfoSettings.SpellModeMag;
ChatLine($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}");
return;
case "field":
if (!MagItemInfoCatalog.TryFindField(arg3, out MagItemInfoField field))
{
ChatLine($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool fieldOn) s.SetHidden(field, !fieldOn);
ChatLine($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}");
return;
case "rating":
int r = MagItemInfoCatalog.FindRating(arg3);
if (r < 0)
{
ChatLine($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool ratingOn) s.SetRatingHidden(r, !ratingOn);
var rating = MagItemInfoCatalog.Ratings[r];
ChatLine($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}");
return;
case "fields":
ListItemInfoFields(s);
return;
case "click":
switch (arg3.ToLowerInvariant())
{
case "left": case "l": s.ClickTrigger = MagItemInfoSettings.ClickLeft; break;
case "right": case "r": s.ClickTrigger = MagItemInfoSettings.ClickRight; break;
case "off": case "none": s.ClickTrigger = MagItemInfoSettings.ClickOff; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo click left|right|off");
return;
}
ChatLine($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}");
return;
case "layout":
switch (arg3.ToLowerInvariant())
{
case "pet": case "pets": case "lines": s.Layout = MagItemInfoSettings.LayoutPetLines; break;
case "line": case "mag": case "one": s.Layout = MagItemInfoSettings.LayoutOneLine; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo layout pet|line");
return;
}
ChatLine($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}");
return;
case "reset":
s.ResetToDefaults();
ChatLine("[RynthAi] Item info settings reset to defaults.");
return;
}
if (ParseOnOff(sub) is bool onSelect)
{
s.OnSelect = onSelect;
ChatLine($"[RynthAi] Item info on select: {OnOff(onSelect)}");
return;
}
ChatLine("[RynthAi] Usage: /ra iteminfo [on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
}
private static string OnOff(bool on) => on ? "ON" : "OFF";
/// <summary>"/ra iteminfo fields" — current state of every field and rating.</summary>
private void ListItemInfoFields(MagItemInfoSettings s)
{
var sb = new StringBuilder("[RynthAi] Fields: ");
bool first = true;
foreach (var f in MagItemInfoCatalog.Fields)
{
if (!first) sb.Append(", ");
sb.Append(f.Field).Append(s.IsHidden(f.Field) ? " off" : " on");
first = false;
}
ChatLine(sb.ToString());
sb.Clear().Append("[RynthAi] Ratings: ");
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(ratings[i].Tag).Append(s.IsRatingHidden(i) ? " off" : " on");
}
ChatLine(sb.ToString());
}
/// <summary>/ra iteminfo and the window's "Print to chat" button.</summary>
private void PrintSelectedItemInfo()
{
if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; }
uint selected = Host.GetSelectedItemId();
if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; }
QueueItemInfo(unchecked((int)selected), requestId: true);
}
/// <summary>On-select class filters from the Item Info window.</summary>
private static bool ItemInfoWantsClass(MagItemInfoSettings s, AcObjectClass cls) => cls switch
{
AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb => s.OnSelectWeapons,
AcObjectClass.Armor or AcObjectClass.Clothing => s.OnSelectArmor,
AcObjectClass.Jewelry => s.OnSelectJewelry,
_ => s.OnSelectOther,
};
/// <summary>
/// Describe <paramref name="itemId"/> now if its appraisal is cached, otherwise (optionally)
/// request an ID and print from <see cref="TickItemInfo"/> once it lands or times out.
/// </summary>
internal void QueueItemInfo(int itemId, bool requestId)
{
if (itemId == 0) return;
uint uid = unchecked((uint)itemId);
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(uid))
{
_itemInfoPendingId = 0;
PrintItemInfo(itemId, identified: true);
return;
}
if (requestId && Host.HasRequestId) Host.RequestId(uid);
_itemInfoPendingId = itemId;
_itemInfoPendingSince = Environment.TickCount64;
}
/// <summary>
/// Select / click triggers: <see cref="QueueItemInfo"/> unless the same item was queued
/// automatically within <see cref="AutoDedupeMs"/> (one click can raise both triggers).
/// </summary>
internal void QueueAutoItemInfo(int itemId, bool requestId)
{
long now = Environment.TickCount64;
if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) return;
_itemInfoLastAutoId = itemId;
_itemInfoLastAutoAt = now;
QueueItemInfo(itemId, requestId);
}
/// <summary>
/// Render-thread click watcher (OnRender / OnRenderOverlay, ImGui context current). The ImGui
/// backend sees every mouse message on the game window, including the ones the game handles,
/// so the raw button state is edge-detected here; the selection is resolved in
/// <see cref="TickItemInfo"/>.
/// </summary>
private void DetectItemInfoClick()
{
int trigger = ItemInfoSettings?.ClickTrigger ?? MagItemInfoSettings.ClickOff;
int button = trigger switch
{
MagItemInfoSettings.ClickLeft => 0,
MagItemInfoSettings.ClickRight => 1,
_ => -1,
};
if (button < 0)
{
_iiClickPrevDown = false;
_iiClickArmed = false;
return;
}
ImGuiIOPtr io = ImGui.GetIO();
bool down = io.MouseDown[button];
long now = Environment.TickCount64;
if (down && !_iiClickPrevDown)
{
// A press on an overlay window belongs to the overlay, not to an item in the game.
_iiClickArmed = !io.WantCaptureMouse;
_iiClickPressAt = now;
_iiClickPressPos = io.MousePos;
}
else if (down && _iiClickArmed)
{
bool held = now - _iiClickPressAt > ClickMaxHoldMs;
bool moved = Vector2.DistanceSquared(io.MousePos, _iiClickPressPos) > ClickMaxMovePx * ClickMaxMovePx;
if (held || moved) _iiClickArmed = false; // drag or mouse-look, not a click
}
else if (!down && _iiClickPrevDown && _iiClickArmed)
{
_iiClickArmed = false;
Interlocked.Exchange(ref _iiClickResolveAt, now + ClickSettleMs);
}
_iiClickPrevDown = down;
}
/// <summary>Tick-thread half of the click trigger: describe whatever item the click selected.</summary>
private void ResolveItemInfoClick()
{
long at = Interlocked.Read(ref _iiClickResolveAt);
if (at == 0 || Environment.TickCount64 < at) return;
if (Interlocked.CompareExchange(ref _iiClickResolveAt, 0, at) != at) return;
var s = ItemInfoSettings;
if (s == null || s.ClickTrigger == MagItemInfoSettings.ClickOff || !Host.HasGetSelectedItemId) return;
uint selected = Host.GetSelectedItemId();
if (selected == 0) return;
int id = unchecked((int)selected);
WorldObject? obj = _objectCache?[id];
if (obj == null || !IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) return;
QueueAutoItemInfo(id, requestId: true);
}
/// <summary>Plugin-tick poll for a pending describe (no appraisal-arrived event in the SDK).</summary>
private void TickItemInfo()
{
ResolveItemInfoClick();
int id = _itemInfoPendingId;
if (id == 0) return;
bool ready = Host.HasAppraisalData(unchecked((uint)id));
long timeoutMs = (long)((ItemInfoSettings?.IdTimeoutSec ?? 3f) * 1000f);
bool timedOut = Environment.TickCount64 - _itemInfoPendingSince > timeoutMs;
if (!ready && !timedOut) return;
_itemInfoPendingId = 0;
PrintItemInfo(id, identified: ready);
}
/// <summary>
/// Builds the output lines (no prefix / indent) in the configured layout, or returns null
/// with <paramref name="error"/> set. The one-line layout returns a single line.
/// </summary>
private List<string>? BuildItemInfoLines(int itemId, out string? error)
{
error = null;
WorldObject? wo = _objectCache?[itemId];
if (wo == null) { error = $"Item 0x{(uint)itemId:X8} is not in the object cache."; return null; }
try
{
var s = ItemInfoSettings;
MagItemDescription d = MagItemDescriber.Build(new CacheItemPropertySource(Host, wo), MagItemInfoOptions.From(s));
return (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine
? new List<string> { d.ToOneLine() }
: d.ToPetLines();
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.General, ex, $"item info 0x{(uint)itemId:X8}");
error = $"Item info failed for {wo.Name}: {ex.Message}";
return null;
}
}
/// <summary>
/// Chat output. Pet-style: line 1 carries the prefix in <see cref="MagItemInfoSettings.ChatType"/>,
/// later lines are indented like the pet roster and use <see cref="MagItemInfoSettings.DetailChatType"/>.
/// </summary>
private void PrintItemInfo(int itemId, bool identified)
{
List<string>? lines = BuildItemInfoLines(itemId, out string? error);
if (lines == null || lines.Count == 0) { ChatLine("[RynthAi] " + error); return; }
if (!identified) lines[0] += " (not identified — stats may be incomplete)";
var s = ItemInfoSettings;
string prefix = s?.Prefix ?? "[RynthAi] ";
int headerType = s?.ChatType ?? 1;
int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType;
Host.WriteToChat(prefix + lines[0], headerType);
for (int i = 1; i < lines.Count; i++)
Host.WriteToChat(prefix + " " + lines[i], detailType);
}
/// <summary>Item Info window preview: the selected item's lines, or null when nothing is selected.</summary>
private string? DescribeSelectedItemForPreview()
{
if (!Host.HasGetSelectedItemId) return null;
uint selected = Host.GetSelectedItemId();
if (selected == 0) return null;
int id = unchecked((int)selected);
List<string>? lines = BuildItemInfoLines(id, out string? error);
if (lines == null || lines.Count == 0) return error;
if (Host.HasHasAppraisalData && !Host.HasAppraisalData(selected))
lines[0] += " (not identified yet — Print to chat IDs it)";
// The window adds the prefix to the first line; indent the rest like chat.
return string.Join("\n ", lines);
}
/// <summary>Item Info window "Test" button: sample line in the chosen chat type.</summary>
private void TestItemInfoChatType(int chatType)
{
string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi] ";
Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType);
}
}

View file

@ -0,0 +1,323 @@
using System;
using System.Text.RegularExpressions;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Out of the acid at once. A hotspot (an acid or lava pool, ACE's Hotspot) hurts every couple of
/// seconds while you stand in it and says so: "You suffer 32 damage from acid!". On 2026-10-07
/// Drakkon died twice that way in an hour: the patrol (once after a reload, once after a fight)
/// left him in a pool the hazard list didn't know, and topping up with healing kits held him there
/// - every kit stopped him, the acid matched each kit, and the kits ran his stamina out.
///
/// Now the first hotspot hit, while the macro runs, stops everything (combat, buffs, healing,
/// looting, the route, the meta: OnTick returns here, like the death hold) and walks the character
/// back out along its own footsteps (the positions it just came through, so a path it could walk)
/// to where it stood just before the hit. It hands back once it got there and no hit came
/// for HazardQuietMs. A dungeon cell it was hurt in is a hazard from then on (persisted), so the
/// patrol reroutes around it now and on later visits.
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>The escape clock (ms); host tests replace it.</summary>
internal static Func<long> HazardClock = static () => Environment.TickCount64;
/// <summary>No hit for this long = out of it (hotspots hit about every 2.5-3.5 s).</summary>
internal const long HazardQuietMs = 4000;
/// <summary>An escape that hasn't got out by then gives the tick back (and says so).</summary>
internal const long HazardEscapeMaxMs = 20000;
private const long HazardTrailSampleMs = 250;
private const int HazardTrailSize = 80; // 20 s of positions
private const double HazardArriveMeters = 0.6;
/// <summary>A footstep on the way counts as passed this close (the target needs HazardArriveMeters).</summary>
private const double HazardStepMeters = 1.0;
private const double HazardMinBackMeters = 2.5;
/// <summary>A trail point this long before the first hit is taken as outside the pool.</summary>
private const long HazardBeforeHitMs = 750;
private static readonly Regex HotspotDamageRx = new(
@"^You suffer (\d+) (?:points of )?damage from (?:the )?([A-Za-z][A-Za-z ]*?)[.!]*$",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private readonly (long At, uint Cell, float X, float Y)[] _hazardTrail = new (long, uint, float, float)[HazardTrailSize];
private int _hazardTrailHead;
private int _hazardTrailCount;
private long _hazardTrailLastAt;
private long _hazardLastHitAt;
private long _hazardFirstHitAt;
private long _hazardEscapeSince; // 0 = not escaping
private long _hazardArrivedAt; // 0 = still running to the target
private bool _hazardHasTarget;
private uint _hazardTargetCell;
private float _hazardTargetX, _hazardTargetY;
private long _hazardTargetAt; // the trail time of the target (older = further back)
/// <summary>The footsteps back to the target, newest first; the last one is the target.</summary>
private readonly System.Collections.Generic.List<(uint Cell, float X, float Y)> _hazardPath = new();
private int _hazardPathIdx;
private bool _hazardRunning;
private long _hazardRunBeatAt;
private string _hazardSource = "";
/// <summary>True while the escape owns the character.</summary>
internal bool HazardEscaping => _hazardEscapeSince != 0;
/// <summary>"You suffer 32 damage from acid!" -> 32, "acid". Broadcast text only.</summary>
internal static bool TryParseHotspotDamage(string? text, out int amount, out string source)
{
amount = 0;
source = "";
if (string.IsNullOrEmpty(text)) return false;
Match m = HotspotDamageRx.Match(text.Trim());
if (!m.Success || !int.TryParse(m.Groups[1].Value, out amount)) return false;
source = m.Groups[2].Value.Trim().ToLowerInvariant();
return true;
}
/// <summary>Chat hook: a hotspot hit starts (or pushes on) the escape.</summary>
internal void NoteHotspotChat(string? text, int chatType)
{
if (chatType != 0 || !TryParseHotspotDamage(text, out int amount, out string source)) return;
// Off (Escape Acid and Lava): neither the escape nor the learning - a character that walks
// through acid on purpose doesn't want the patrol rerouted around it either.
if (_dashboard?.Settings is { EscapeHazards: false }) return;
long now = HazardClock();
bool fresh = _hazardLastHitAt == 0 || now - _hazardLastHitAt > HazardQuietMs;
if (fresh) _hazardFirstHitAt = now;
_hazardLastHitAt = now;
_hazardSource = source;
if (Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _))
_objectCache?.RegisterDamageHazardCell(cell, source);
if (_dashboard?.Settings is not { IsMacroRunning: true }) return;
if (!HazardEscaping)
{
StartHazardEscape(now, amount);
return;
}
// Got to the target and still hurt: the pool reaches further back. Go further.
if (_hazardArrivedAt != 0 || !_hazardHasTarget)
{
_hazardArrivedAt = 0;
if (!PickHazardTarget(now, olderThan: _hazardHasTarget ? _hazardTargetAt : _hazardFirstHitAt - HazardBeforeHitMs + 1))
Log("[RynthAi] Hazard: still taking damage and no older spot to run back to; running on.");
}
}
/// <summary>Every tick: where the character stood (not while escaping, nor dead).</summary>
internal void RecordHazardTrail()
{
if (HazardEscaping) return;
long now = HazardClock();
if (now - _hazardTrailLastAt < HazardTrailSampleMs) return;
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out _, out _, out _, out _, out _) || cell == 0)
return;
_hazardTrailLastAt = now;
_hazardTrail[_hazardTrailHead] = (now, cell, x, y);
_hazardTrailHead = (_hazardTrailHead + 1) % HazardTrailSize;
if (_hazardTrailCount < HazardTrailSize) _hazardTrailCount++;
}
private void StartHazardEscape(long now, int amount)
{
_hazardEscapeSince = now;
_hazardArrivedAt = 0;
_hazardRunning = false;
PickHazardTarget(now, olderThan: _hazardFirstHitAt - HazardBeforeHitMs + 1);
Log($"[RynthAi] Hazard: took {amount} {_hazardSource} damage - stopping everything and moving out"
+ (_hazardHasTarget ? $" (back to ({_hazardTargetX:0.0}, {_hazardTargetY:0.0}))." : " (no earlier spot known: running back the way it faces)."));
try { Host.WriteToChat($"[RynthAi] Standing in {_hazardSource} - stopping everything to move out.", 1); } catch { }
try { if (Host.HasCancelAttack) Host.CancelAttack(); } catch { }
_combatManager?.ReleaseHeldTurn();
_navigationEngine?.Stop();
try { StopCorpseMovement(); } catch { }
}
/// <summary>
/// The newest trail point older than <paramref name="olderThan"/>, in this landblock, at least
/// HazardMinBackMeters away, preferring one outside a known hazard cell. False = none; then
/// the escape runs straight back from where it faces.
/// </summary>
private bool PickHazardTarget(long now, long olderThan)
{
_hazardHasTarget = false;
if (!Host.TryGetPlayerPose(out uint cell, out float px, out float py, out _, out float qw, out _, out _, out float qz))
return false;
int fallback = -1;
for (int k = 1; k <= _hazardTrailCount; k++)
{
int i = (_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize;
var p = _hazardTrail[i];
if (p.At >= olderThan || (p.Cell >> 16) != (cell >> 16)) continue;
double d = Math.Sqrt((p.X - px) * (p.X - px) + (p.Y - py) * (p.Y - py));
if (d < HazardMinBackMeters) continue;
if (_objectCache?.IsHazardCell(p.Cell) == true)
{
if (fallback < 0) fallback = i;
continue;
}
SetHazardTarget(p);
return true;
}
if (fallback >= 0)
{
SetHazardTarget(_hazardTrail[fallback]);
return true;
}
// No trail (fresh login, or it all lies in the pool): 4 m straight back from the facing.
double yawDeg = ((-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI)) % 360.0 + 720.0) % 360.0;
double back = (yawDeg + 180.0) * Math.PI / 180.0;
SetHazardTarget((olderThan - 1, cell, (float)(px + 4.0 * Math.Sin(back)), (float)(py + 4.0 * Math.Cos(back))));
return false;
}
private void SetHazardTarget((long At, uint Cell, float X, float Y) p)
{
_hazardHasTarget = true;
_hazardTargetAt = p.At;
_hazardTargetCell = p.Cell;
_hazardTargetX = p.X;
_hazardTargetY = p.Y;
// The footsteps from now back to the target, newest first, thinned to about 1 m apart:
// the way it came in is a way it can walk out (no straight line through a wall).
_hazardPath.Clear();
_hazardPathIdx = 0;
float lx = float.NaN, ly = float.NaN;
for (int k = 1; k <= _hazardTrailCount; k++)
{
var t = _hazardTrail[(_hazardTrailHead - k + HazardTrailSize) % HazardTrailSize];
if (t.At <= p.At) break;
if ((t.Cell >> 16) != (p.Cell >> 16)) continue;
if (!float.IsNaN(lx) && (t.X - lx) * (t.X - lx) + (t.Y - ly) * (t.Y - ly) < 1.0f) continue;
_hazardPath.Add((t.Cell, t.X, t.Y));
lx = t.X; ly = t.Y;
}
_hazardPath.Add((p.Cell, p.X, p.Y));
}
/// <summary>
/// Called in OnTick right after the death hold. True = the escape owns this tick: nothing else
/// runs (no buffs, healing kits, combat, looting, route or meta).
/// </summary>
internal bool HoldForHazardEscape()
{
if (!HazardEscaping) return false;
long now = HazardClock();
if (_dashboard?.Settings is { EscapeHazards: false })
{
EndHazardEscape("Escape Acid and Lava was turned off");
return false;
}
if (_dashboard?.Settings is not { IsMacroRunning: true })
{
EndHazardEscape("the macro was stopped");
return false;
}
// Died, recalled or portalled meanwhile: the target is somewhere else now.
if (_hazardHasTarget && Host.TryGetPlayerPose(out uint cellNow, out _, out _, out _, out _, out _, out _, out _)
&& (cellNow >> 16) != (_hazardTargetCell >> 16))
{
EndHazardEscape("left the area");
return false;
}
bool quiet = now - _hazardLastHitAt >= HazardQuietMs;
if (now - _hazardEscapeSince > HazardEscapeMaxMs && quiet)
{
EndHazardEscape("no hit for a while");
return false;
}
if (now - _hazardEscapeSince > HazardEscapeMaxMs * 2)
{
EndHazardEscape($"still hurt after {HazardEscapeMaxMs * 2 / 1000} s - giving the tick back");
return false;
}
if (_hazardArrivedAt == 0 && _hazardHasTarget)
RunToHazardTarget(now);
if (_hazardArrivedAt != 0 && quiet)
{
EndHazardEscape("out of it");
return false;
}
return true;
}
private void RunToHazardTarget(long now)
{
if (!Host.TryGetPlayerPose(out _, out float px, out float py, out _, out _, out _, out _, out _))
return;
// Skip to just past the furthest footstep already reached (it may have been carried
// along, or started near the end); the last one is the target.
for (int j = _hazardPath.Count - 1; j >= _hazardPathIdx; j--)
{
var r = _hazardPath[j];
double rd = Math.Sqrt((r.X - px) * (r.X - px) + (r.Y - py) * (r.Y - py));
if (rd <= (j == _hazardPath.Count - 1 ? HazardArriveMeters : HazardStepMeters))
{
_hazardPathIdx = j + 1;
break;
}
}
double dx = 0, dy = 0;
if (_hazardPathIdx < _hazardPath.Count)
{
var w = _hazardPath[_hazardPathIdx];
dx = w.X - px; dy = w.Y - py;
}
if (_hazardPathIdx >= _hazardPath.Count)
{
_hazardArrivedAt = now;
StopHazardRun();
return;
}
double desired = Math.Atan2(dx, dy) * (180.0 / Math.PI);
if (desired < 0) desired += 360.0;
bool aligned = _navigationEngine?.ServoToward(desired) ?? TurnDirect(desired);
if (!aligned)
{
if (_hazardRunning) StopHazardRun();
return;
}
if (!_hazardRunning || now - _hazardRunBeatAt >= 500)
{
Host.SetAutoRunBy("Hazard", true);
_hazardRunning = true;
_hazardRunBeatAt = now;
}
}
private bool TurnDirect(double desired)
{
if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Hazard", (float)desired);
return true;
}
private void StopHazardRun()
{
if (!_hazardRunning) return;
_hazardRunning = false;
Host.SetAutoRunBy("Hazard", false);
if (Host.HasStopCompletely) Host.StopCompletelyBy("Hazard");
}
private void EndHazardEscape(string why)
{
StopHazardRun();
Log($"[RynthAi] Hazard: {why} after {(HazardClock() - _hazardEscapeSince) / 1000.0:0.0} s - resuming.");
_hazardEscapeSince = 0;
_hazardArrivedAt = 0;
_hazardHasTarget = false;
_hazardPath.Clear();
_hazardTrailCount = 0; // the old trail runs through the pool
_navigationEngine?.ResumeFromNearestWaypoint();
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.ItemInfo;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra iteminfo [name]: a selected (or named) item's details on one chat line, Mag-Tools
/// style (ItemInfo/ItemInfoText). An item the client hasn't appraised is identified first
/// and printed when the appraisal arrives, or after <see cref="ItemInfoTimeoutMs"/> with
/// what the client has. Partial class of RynthAiPlugin.
///
/// Threads: the command only queues its argument; <see cref="TickItemInfo"/> on the plugin
/// tick does every host read, the ID request and the print. Nothing is drawn.
/// </summary>
public sealed partial class RynthAiPlugin
{
internal const long ItemInfoTimeoutMs = 5000;
/// <summary>Test seam: the clock the ID timeout runs on.</summary>
internal static Func<long> ItemInfoClock = () => Environment.TickCount64;
private readonly ConcurrentQueue<string> _itemInfoRequests = new();
// One item waiting for its appraisal at a time (tick thread only); a newer request replaces it.
private uint _itemInfoPendingId;
private long _itemInfoDeadline;
/// <summary>/ra iteminfo [item name]. Queued for the next tick.</summary>
private void HandleItemInfoCommand(string[] parts)
{
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
if (arg.Equals("help", StringComparison.OrdinalIgnoreCase) || arg == "?")
{
ChatLine("[RynthAi] /ra iteminfo - the selected item's details (identifies it first when needed).");
ChatLine("[RynthAi] /ra iteminfo <name> - the first item in your inventory with that name (else one whose name contains it).");
return;
}
if (_itemInfoRequests.Count < 8) _itemInfoRequests.Enqueue(arg);
}
/// <summary>Plugin tick: starts queued requests, prints an item once its ID lands or times out.</summary>
private void TickItemInfo()
{
while (_itemInfoRequests.TryDequeue(out string? arg))
StartItemInfo(arg);
uint selected = System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, 0);
if (selected != 0)
StartItemInfoFor(selected, quiet: true);
uint pending = _itemInfoPendingId;
if (pending == 0) return;
bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(pending);
if (appraised || ItemInfoClock() >= _itemInfoDeadline)
{
_itemInfoPendingId = 0;
PrintItemInfo(pending, identified: appraised);
}
}
private void StartItemInfo(string arg)
{
uint id;
if (arg.Length == 0)
{
id = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
if (id == 0)
{
ChatLine("[RynthAi] Item info: nothing selected. Select an item, or /ra iteminfo <name>.");
return;
}
}
else
{
id = FindInventoryItemByName(arg);
if (id == 0)
{
ChatLine($"[RynthAi] Item info: no \"{arg}\" in your inventory.");
return;
}
}
StartItemInfoFor(id, quiet: false);
}
/// <summary>
/// Prints <paramref name="id"/> now when it's appraised, else asks for its ID and prints when
/// it lands. <paramref name="quiet"/> (Item Info On Select): no "identifying" chatter.
/// </summary>
private void StartItemInfoFor(uint id, bool quiet)
{
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(id))
{
if (_itemInfoPendingId == id) _itemInfoPendingId = 0;
PrintItemInfo(id, identified: true);
return;
}
if (!quiet && _itemInfoPendingId != 0 && _itemInfoPendingId != id)
ChatLine($"[RynthAi] Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}.");
if (Host.HasRequestId) Host.RequestId(id);
_itemInfoPendingId = id;
_itemInfoDeadline = ItemInfoClock() + ItemInfoTimeoutMs;
if (!quiet) ChatLine($"[RynthAi] Item info: identifying {ObjectNameOr(id)}...");
}
// Item Info On Select: the item the player just selected, for the next tick (0 = none).
private uint _itemInfoSelectId;
/// <summary>
/// Selection change (OnSelectedTargetChange): queues Item Info for an item the player
/// selected. Skips non-items and RynthAi's own selections (the looter, metas).
/// </summary>
private void QueueItemInfoOnSelect(uint id, WorldObject? obj)
{
if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return;
if (obj == null || !IsLootableClass(obj.ObjectClass)) return;
if (SelfSelect.IsOurs(id)) return;
System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, id);
}
/// <summary>
/// An inventory item (carried or worn) whose name is <paramref name="name"/>, ignoring case;
/// else the first whose name contains it. 0 when none.
/// </summary>
private uint FindInventoryItemByName(string name)
{
if (_objectCache == null) return 0;
uint partial = 0;
foreach (WorldObject wo in _objectCache.GetInventory())
{
if (wo.Name.Length == 0) continue;
if (wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id);
if (partial == 0 && wo.Name.Contains(name, StringComparison.OrdinalIgnoreCase)) partial = unchecked((uint)wo.Id);
}
return partial;
}
private string ObjectNameOr(uint id) =>
Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}";
private void PrintItemInfo(uint id, bool identified)
{
var source = new HostItemInfoSource(Host, id);
ChatLine("[RynthAi] " + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified));
}
/// <summary>The live appraisal through the host (tick thread).</summary>
private sealed class HostItemInfoSource : IItemInfoSource
{
private readonly RynthCoreHost _host;
private readonly uint _id;
public HostItemInfoSource(RynthCoreHost host, uint id)
{
_host = host;
_id = id;
Name = host.TryGetObjectName(id, out string n) ? n : string.Empty;
SpellIds = ReadSpells(host, id);
}
public string Name { get; }
public IReadOnlyList<int> SpellIds { get; }
public bool TryInt(uint key, out int value)
{
value = 0;
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, key, out value);
}
public bool TryFloat(uint key, out double value)
{
value = 0;
return _host.TryGetObjectDoubleProperty(_id, key, out value);
}
private static IReadOnlyList<int> ReadSpells(RynthCoreHost host, uint id)
{
if (!host.HasGetObjectSpellIds) return Array.Empty<int>();
var buf = new uint[64];
int n = host.GetObjectSpellIds(id, buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
var list = new List<int>(n);
for (int i = 0; i < n && i < buf.Length; i++) list.Add(unchecked((int)buf[i]));
return list;
}
}
}

View file

@ -21,7 +21,6 @@ public sealed partial class RynthAiPlugin
private Huds.HudIconCache? _hudIcons;
private Translate.ChatTranslator? _translator;
private Translate.TranslateUi? _translateUi;
private LegacyItemInfoUi? _itemInfoUi;
private CreatureData.UbMobSeedStore? _mobSeedStore;
// One-time overlay diagnostics (render thread only).
@ -117,15 +116,6 @@ public sealed partial class RynthAiPlugin
var huds = _huds;
_iltHub.MiniRemoteCommand = mode => "[ILT Hub] " + huds.HandleCommand("remote", mode);
_iltHub.MiniRemoteVisible = () => huds.State.ShowMiniRemote;
EnsureItemInfoUi();
}
/// <summary>Item Info window, created once settings exist.</summary>
private void EnsureItemInfoUi()
{
if (_dashboard == null || _itemInfoUi != null) return;
_itemInfoUi = new LegacyItemInfoUi(_dashboard.Settings);
_itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType);
}
/// <summary>Pump-thread work for the ported features. Safe before login (each call is null-checked).</summary>
@ -160,7 +150,6 @@ public sealed partial class RynthAiPlugin
try { _huds?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); }
_huds = null;
_itemInfoUi = null;
ResetGroundLoot(clearCaches: true);
if (!disposeTranslator) return;
try { _translator?.Dispose(); }
@ -205,9 +194,7 @@ public sealed partial class RynthAiPlugin
ImGui.SetCurrentContext(Host.ImGuiContext);
try
{
DetectItemInfoClick();
_navOverlay?.Render();
_itemInfoUi?.Render();
_iltHub?.Render();
_huds?.Render();
RenderTranslateWindow();
@ -249,14 +236,12 @@ public sealed partial class RynthAiPlugin
ImGui.SetCurrentContext(Host.ImGuiContext);
try
{
DetectItemInfoClick();
int pushedColors = LegacyDashboardRenderer.PushDashboardStyle();
try { _iltHub?.Render(); }
finally { ImGui.PopStyleColor(pushedColors); }
_huds?.Render();
RenderTranslateWindow();
_navOverlay?.Render();
_itemInfoUi?.Render();
}
catch (Exception ex)
{

View file

@ -0,0 +1,68 @@
using System;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// RynthAi's side of the action pacing (Plugins/Shared/ActionPacer.cs, 2026-10-06).
// Every use / use-on RynthAi sends is recorded as the server action it waits on;
// casts and mode changes record themselves (CastSpellFor / ChangeCombatModeFor).
// The managers that only see a busy count (inventory, salvage, mana stones, pets)
// get PacedBusy: the count, plus one while a server action is unanswered.
// ============================================================================
public sealed partial class RynthAiPlugin
{
/// <summary>UseAudit.AfterSend: a use or use-on went out - record it as the action the server is answering.</summary>
private static void RecordUseForPacing(RynthCoreHost host, UseAudit.SentUse use)
{
try
{
// The salvage panel (a UST use) opens on the client; the server answered only 7 of 18
// of them with a UseDone in the 10-05/10-06 logs, so it is not waited on.
if (use.Subsystem == "Salvage" || use.What.Contains("'Ust'", StringComparison.OrdinalIgnoreCase))
return;
PacedKind kind;
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
if (use.TargetId != 0)
{
// Something on a target: on yourself (kit, stone, food) it is an item use; on a
// door/corpse or anything else in the world the server walks there first.
kind = use.TargetId == player
? PacedKind.ItemUse
: ActionPacer.ClassifyUse(host, use.TargetId, use.DoorOrCorpse);
}
else
{
kind = ActionPacer.ClassifyUse(host, use.ObjectId, use.DoorOrCorpse);
}
string who = "RynthAi/" + use.Subsystem + (use.Kind == UseKind.Asked ? " (asked)" : "");
ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore);
}
catch { }
}
/// <summary>
/// The busy count the item managers gate on (inventory, salvage, mana stones, pets): our mirror of
/// AC's count, plus one while a server action is unanswered so they don't start one on top of it.
/// </summary>
private int PacedBusy
{
get
{
int busy = _busyCount;
if (ActionPacer.Enabled
&& (ActionPacer.Current(Host) != null || ActionPacer.GestureHolds(Host, "Items", HealNeed.None, out _)))
busy++; // an unanswered server action, or the character still animating (a pack move of a wielded item, a stone, a summon would start on top)
return busy;
}
}
/// <summary>/ra pace: what the pacing is waiting on, and its counters.</summary>
private void HandlePaceCommand()
{
foreach (string line in ActionPacer.DescribeLines(Host))
ChatLine("[RynthAi] " + line);
ChatLine($"[RynthAi] Busy mirror {_busyCount} (shadow resets only; the client's count is never force-cleared by RynthAi now)");
}
}

View file

@ -131,6 +131,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// Give queue — drained one item per tick with a cooldown (interval comes from settings)
private readonly Queue<(uint itemId, uint targetId, int stackSize)> _pendingGives = new();
private DateTime _lastGiveAt = DateTime.MinValue;
// The give the server hasn't answered yet (0 = none): the next one waits for it.
private uint _giveInFlightId, _giveInFlightTarget;
private int _giveInFlightAmount, _giveInFlightStack, _giveInFlightTries;
private long _giveInFlightAt;
private const long GiveConfirmMs = 3000;
private const int GiveMaxTries = 2;
private RynthCore.Loot.LootProfile? _nativeLootProfile;
private string _nativeLootProfilePath = string.Empty;
private DateTime _nativeLootProfileTime = DateTime.MinValue;
@ -168,11 +174,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module.
ImGuiNativeBinding.Ensure();
_dashboard = new LegacyDashboardRenderer(Host);
_killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true;
_dashboard.KillClock = _killClock;
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
// each, and no automatic door/corpse use while the macro is off.
RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true);
// Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs).
RynthCore.Plugin.Shared.MoveAudit.Reset();
// A door/corpse use the server is still answering holds RynthAi's own moves and turns
// (moving would cancel the server's walk/turn to it; 2026-10-06).
RynthCore.Plugin.Shared.UseAudit.TrackWorldUses = true;
// One server action at a time (Plugins/Shared/ActionPacer.cs, 2026-10-06): every use,
// use-on, cast and combat-mode change waits for the server's answer to the last one.
RynthCore.Plugin.Shared.ActionPacer.Reset();
RynthCore.Plugin.Shared.ActionPacer.Enabled = true;
RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing;
_objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login
// Items we use (or use something on) get re-identified before a meta reads them.
// ObjectUsed is a static event and Shutdown never unsubscribes: when the engine
@ -220,6 +236,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_dashboard = null;
// Don't let the static audit hold this instance once it's gone (a reused module).
RynthCore.Plugin.Shared.UseAudit.MacroOn = static () => false;
RynthCore.Plugin.Shared.UseAudit.AfterSend = null;
RynthCore.Plugin.Shared.ActionPacer.Enabled = false;
RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown");
// Give the heap back. When a changed RynthAi is deployed, the engine loads
// it as a new copy and this one is abandoned for good (a NativeAOT DLL can't
@ -252,6 +271,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
Log("RynthAi: logout — tearing down session.");
try { _dashboard?.SaveSettings(); } catch { }
Loot.T11ItemSupport.Reset();
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
ClearInGameMarker();
TeardownSession();
@ -352,6 +372,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
private void TeardownSession()
{
ObjectChangeTracker.Clear();
// The server drops whatever it was doing for this character at logout.
RynthCore.Plugin.Shared.ActionPacer.Forget("logout");
_navigationEngine?.Stop();
_navigationEngine = null;
// The dungeon cell graph is a static single-landblock cache; nothing may outlive the session.
@ -372,6 +394,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
_combatManager?.Dispose();
_combatManager = null;
// A relog is what clears a server that refuses every use: start the next session clean.
ResetUseRefusalState();
Log($"RynthAi: TeardownSession — RadarWallFlush={tFlushMs} ms, RaycastDispose={tRayMs} ms");
_fellowshipTracker?.Dispose();
_fellowshipTracker = null;
@ -460,10 +484,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_loginCompletedAt = DateTime.Now;
_loginComplete = true;
_killClock.SessionStarted();
_dashboard.OnLoginComplete();
_dashboard.ChatSubmitHandler = HandleRynthChatSubmit;
EnsureTranslator();
EnsureItemInfoUi();
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
{
ChatSubmit = HandleRynthChatSubmit,
@ -578,6 +602,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// other (the collision behind "you can only move or use one item at a
// time" and the object-teardown AV).
_weaponSwapGate ??= new WeaponSwapGate();
// The next swap goes once the server is done with the last one (not a flat 3 s).
_weaponSwapGate.ServerIdle = () => RynthCore.Plugin.Shared.ActionPacer.Enabled && RynthCore.Plugin.Shared.ActionPacer.Current(Host) == null;
_weaponSwapGate.IsWielded = id => RynthCore.Plugin.Shared.ActionPacer.IsWieldedByPlayer(Host, unchecked((uint)id));
_buffManager = new BuffManager(Host, _dashboard.Settings, _spellManager, _vitals);
_inGameMarkerSet = false;
@ -618,6 +645,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
@ -658,6 +686,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager.SetQuestTracker(_questTracker);
if (_buffManager != null) _metaManager.SetBuffManager(_buffManager);
_metaManager.SetCreatureStore(_creatureStore);
_metaManager.SetKillClock(_killClock);
if (_dashboard != null)
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
@ -665,6 +694,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
_inventoryManager = new InventoryManager(Host, _dashboard.Settings, _objectCache);
_manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache);
LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name
_manaStoneManager.IsLootKept = IsKeptByLootProfile;
_petManager = new PetManager(Host, _dashboard.Settings, _objectCache, _combatManager, _charSkills);
_combatManager.SummonOut = () => _petManager?.CurrentSummon();
@ -720,6 +750,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// decides whether nav runs at all. One edge-detect replaces the cascade.
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
private bool _macroWasRunning; // edge: release held turns when the macro stops
// Time since our last kill (KillerNotification only): secondssincelastkill[], the
// No Kills Within Minutes meta condition and the status feed. Counts from login / plugin
// load, then from each macro start, until the first kill.
private readonly KillClock _killClock = new();
internal KillClock Kills => _killClock;
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
private bool _navStopIssued;
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
@ -755,8 +791,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_navStopIssued = true;
_navStoppedFor = owner;
bool ownMovement = RynthCore.Plugin.Shared.MoveAudit.OwnMovementActive; // before nav's own stops clear it
_navigationEngine?.Stop();
if (Host.HasStopCompletely)
// A StopCompletely only when RynthAi itself has the character moving (2026-10-06): with
// nothing of ours moving it is one more movement packet on the server's motion - 116 in 46
// minutes on 10-06, on every change of activity - and it cut off movement another plugin
// (RynthNav, RynthLua) had just started (analysis by Silentkelpie). RynthNav's travel is
// stopped by its own command (TickOwnCorpseTravel). Without the pacing, as before.
if (Host.HasStopCompletely
&& (!RynthCore.Plugin.Shared.ActionPacer.Enabled || ownMovement))
Host.StopCompletelyBy("Arbiter");
// Combat taking the tick invalidates any in-progress door interaction.
@ -867,9 +910,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
break;
case "trace":
case "logs":
case "iteminfo":
// Settings panel buttons (Diagnostics tab, Item Info options); value carries the
// same arguments as "/ra trace|logs|iteminfo ...".
// Settings panel buttons (Diagnostics tab); value carries the same arguments as
// "/ra trace|logs ...".
{
var args = new List<string> { "/ra", action.ToLowerInvariant() };
args.AddRange(value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
@ -878,7 +920,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
case "trace": HandleTraceCommand(parts); break;
case "logs": HandleLogsCommand(parts); break;
case "iteminfo": HandleItemInfoCommand(parts); break;
}
}
break;
@ -905,19 +946,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
["HealAt"] = (0, 100), ["EmergencyHealAt"] = (0, 100),
["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
["StaminaToHealthAt"] = (0, 100), ["StaminaToHealthMinStamina"] = (0, 100), ["RestamAt"] = (0, 100), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100),
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["PetMinMonsters"] = (1, 20),
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (250, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100),
["SpellCastIntervalMs"] = (100, 1500), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
["MinSkillLevelTier1"] = (1, 500), ["MinSkillLevelTier2"] = (1, 500), ["MinSkillLevelTier3"] = (1, 500), ["MinSkillLevelTier4"] = (1, 500),
["MinSkillLevelTier5"] = (1, 500), ["MinSkillLevelTier6"] = (1, 500), ["MinSkillLevelTier7"] = (1, 500), ["MinSkillLevelTier8"] = (1, 500),
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
["CorpseApproachRangeMax"] = (0.5, 50), ["CorpseApproachRangeMin"] = (0.5, 20),
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["NavLabelMode"] = (0, 2), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
["NavOffTrackYards"] = (160, 1000), ["NavMaxDetourAttempts"] = (1, 10),
@ -1435,11 +1476,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// to run only inside the legacy dashboard's Render(), which the engine no
// longer calls, so edits waited for the next login. A flag check when idle.
_dashboard?.TickMonsterReload();
// A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it.
_dashboard?.TickNavFolder();
_questTracker?.Tick();
TickLocalFeatures();
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
DrainGiveQueue();
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
if (_loginComplete) TickItemInfo();
Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1);
_jumper?.Tick();
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
@ -1513,6 +1558,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// finally below still submits the nav markers.
if (HoldForDeath())
return;
// Standing in acid or lava: nothing but getting out (RynthAiPlugin.HazardEscape.cs).
RecordHazardTrail();
if (HoldForHazardEscape())
return;
if (diag) Host.Log("[RynthAi] OnTick: before CheckBusyTimeout");
CheckBusyTimeout();
@ -1565,6 +1614,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (!_macroWasRunning && settings.IsMacroRunning)
_navigationEngine?.ResumeFromNearestWaypoint();
_macroWasRunning = settings.IsMacroRunning;
_killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
{
@ -1667,6 +1717,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatEndedAt = nowMs;
bool wantLoot = HasLootWork(settings, nowMs);
_lastWantLoot = wantLoot;
bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy;
bool routeLoaded = settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0;
@ -1813,7 +1864,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
&& _openedContainerId == 0
&& _targetCorpseId == 0)
{
_inventoryManager.OnHeartbeat(_busyCount);
_inventoryManager.OnHeartbeat(PacedBusy);
}
// Status feed: main-pack empty slots (cache-based, off-thread-safe). Throttled to
@ -1886,7 +1937,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// combine work while a threat is up so it doesn't contend with
// combat over SelectItem; it resumes the moment the threat clears.
if (inventorySettled && !combatThreat)
_salvageManager?.OnTick(_busyCount);
_salvageManager?.OnTick(PacedBusy);
if (diag) Host.Log("[RynthAi] OnTick: before manaStoneManager");
// STEP 4: the salvage gap-fill that used to pin/release
@ -1899,8 +1950,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// decision from scratch every tick.
// Mana stone tapping — runs after salvage, independent of looting state.
_manaStoneManager?.OnHeartbeat(_busyCount);
_petManager?.OnHeartbeat(_busyCount);
_manaStoneManager?.OnHeartbeat(PacedBusy);
_petManager?.OnHeartbeat(PacedBusy);
if (diag) Host.Log("[RynthAi] OnTick: before combatManager");
// Missile crafting runs before combat — blocks everything while active.
@ -2041,18 +2092,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (Host.HasQueryHealth) Host.QueryHealth(currentTargetId);
}
if (_lootInspectMode && currentTargetId != 0)
if (currentTargetId != 0)
{
int sid = unchecked((int)currentTargetId);
WorldObject? obj = _objectCache?[sid];
// Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.)
if (obj != null && IsLootableClass(obj.ObjectClass))
{
if (_lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass))
InspectLootRuleForItem(sid, quiet: true);
var itemInfo = _dashboard?.Settings.ItemInfoSettings;
if (itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass))
QueueAutoItemInfo(sid, requestId: false);
}
QueueItemInfoOnSelect(currentTargetId, obj);
}
}
@ -2078,6 +2125,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (mmEat) eat = 1;
else _dashboard?.PushChatLine(text, chatType);
OnChatLocalFeatures(text, chatType, ref eat);
try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); }
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_petManager?.OnChatWindowText(text);
@ -2087,6 +2135,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_scrollLearner?.OnChat(text);
_metaManager?.HandleChat(text, chatType);
_questTracker?.OnChatLine(text);
// The "/aug" reply carries the T11 wield counters.
try { Loot.T11ItemSupport.OnChat(text); }
catch (Exception ex) { Log("RynthAi: T11 /aug parse failed: " + ex.Message); }
CheckChatForSafetyStops(text);
try { OnOwnCorpseChat(text); } catch { }
}
@ -2098,6 +2149,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
public override void OnKillNotification(string? deathMessage)
{
if (string.IsNullOrEmpty(deathMessage)) return;
_killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone
_combatManager?.OnKillNotification(deathMessage);
_dashboard?.RecordKill(); // feeds the kills/hour session stat
try { _iltHub?.RecordKill(); }
@ -2120,6 +2172,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_objectCache?.OnDeleteObject(objectId);
_combatManager?.OnObjectDeleted(objectId); // D7/D8: free per-id maps + clear cast-wait if it was our target
_scrollLearner?.OnObjectDeleted(objectId); // a read scroll is consumed
Loot.T11ItemSupport.Forget(unchecked((int)objectId));
HandleCorpseObjectDeleted(objectId);
}
catch (Exception ex)
@ -3052,13 +3105,48 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
int count = _pendingGives.Count;
_pendingGives.Clear();
_giveInFlightId = 0;
ChatLine(count > 0
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
: "[RynthAi] Give queue is already empty.");
}
/// <summary>
/// One give at a time, each after the server has taken the last: the item has left the
/// inventory (or its stack shrank, for part of a stack). The queue used to send a give
/// every 150 ms; the server takes one give at a time and answers the rest "too busy",
/// so /ub give handed over one item and dropped the rest (2026-10-08). A give with no
/// answer in GiveConfirmMs is sent once more, then skipped.
/// </summary>
private void DrainGiveQueue()
{
long now = Environment.TickCount64;
if (_giveInFlightId != 0)
{
if (GiveLanded())
{
_giveInFlightId = 0;
_lastGiveAt = DateTime.UtcNow;
if (_pendingGives.Count == 0)
ChatLine("[RynthAi] Give queue complete.");
}
else if (now - _giveInFlightAt < GiveConfirmMs)
return;
else if (_giveInFlightTries < GiveMaxTries)
{
GiveItem(_giveInFlightId, _giveInFlightTarget, _giveInFlightAmount, _giveInFlightStack);
_giveInFlightTries++;
_giveInFlightAt = now;
return;
}
else
{
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
_giveInFlightId = 0;
if (_pendingGives.Count == 0) return;
}
}
if (_pendingGives.Count == 0) return;
int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150;
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
@ -3069,9 +3157,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
int whole = _objectCache?[unchecked((int)itemId)] is WorldObject wo ? Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) : stackSize;
GiveItem(itemId, targetId, stackSize, whole);
_lastGiveAt = DateTime.UtcNow;
_giveInFlightId = itemId;
_giveInFlightTarget = targetId;
_giveInFlightAmount = stackSize;
_giveInFlightStack = whole;
_giveInFlightTries = 1;
_giveInFlightAt = now;
}
if (_pendingGives.Count == 0)
ChatLine("[RynthAi] Give queue complete.");
/// <summary>The in-flight give went through: the item left the inventory, or part of its stack did.</summary>
private bool GiveLanded()
{
if (_objectCache?[unchecked((int)_giveInFlightId)] is not WorldObject wo) return true;
if (!InPlayerInventory(wo.Container)) return true;
return _giveInFlightAmount < _giveInFlightStack
&& Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < _giveInFlightStack;
}
/// <summary>
@ -3120,7 +3220,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "listpvars": HandleListPvarsCommand(); break;
case "listgvars": HandleListGvarsCommand(); break;
case "dumpprops": HandleDumpPropsCommand(parts); break;
case "iteminfo": HandleItemInfoCommand(parts); break;
case "version": HandleVersionCommand(); break;
case "t11": HandleT11Command(parts); break;
case "wielded": HandleWieldedCommand(); break;
case "scan": HandleScanCommand(); break;
case "buildinfo": HandleBuildInfoCommand(); break;
@ -3148,7 +3250,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "miniremote": HandleHudCommand(cmd, parts.Length > 2 ? parts[2] : string.Empty); break;
case "translate":
case "tr": HandleTranslateCommand(parts); break;
case "iteminfo":
case "ii": HandleItemInfoCommand(parts); break;
case "groundloot": HandleGroundLootCommand(parts); break;
case "addnavpt": HandleAddNavPointCommand(); break;
@ -3172,6 +3273,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
case "loot": HandleLootCommand(parts); break;
case "corpseinfo": HandleCorpseInfoCommand(); break;
case "pace": HandlePaceCommand(); break;
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
case "corpseopen": HandleCorpseOpenCommand(); break;
case "owncorpse":

View file

@ -0,0 +1,124 @@
using System;
using System.Globalization;
using System.Linq;
using RynthCore.Loot.T11;
using RynthCore.Plugin.RynthAi.Loot;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
/// <summary>
/// /ra t11 [augs &lt;n|auto&gt; | refresh | item [0xId]]: T11 loot support.
/// No argument shows the wield counters the loot rules use; "augs" sets or clears the
/// item-aug override; "refresh" asks the server for "/aug"; "item" shows how the selected
/// item's T11 text was read and the values its virtual loot keys return.
/// </summary>
private void HandleT11Command(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
switch (sub)
{
case "":
case "status":
PrintT11Status();
break;
case "augs":
SetT11ItemAugOverride(parts.Length >= 4 ? parts[3] : string.Empty);
break;
case "refresh":
if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] This engine can't send chat commands."); break; }
Host.InvokeChatParser("/aug");
ChatLine("[RynthAi] T11: sent /aug - the counters update from its reply.");
break;
case "item":
PrintT11Item(parts.Length >= 4 ? parts[3] : null);
break;
default:
ChatLine("[RynthAi] Usage: /ra t11 [augs <n|auto> | refresh | item [0xId]]");
break;
}
}
/// <summary>The counters the "T11: Can Wield" loot key compares wield gates against.</summary>
private void PrintT11Status()
{
T11PlayerAugs p = T11ItemSupport.Player;
int saved = _dashboard?.Settings.T11ItemAugsOverride ?? -1;
string updated = p.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never";
ChatLine($"[RynthAi] === T11 loot (last /aug read: {updated}) ===");
foreach ((T11Counter counter, string name) in T11Catalog.CounterNames)
{
long? v = p.Get(counter);
string source = counter == T11Counter.ItemAugmentations && saved >= 0 ? " (override)" : string.Empty;
ChatLine($"[RynthAi] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}");
}
if (p.UpdatedUtc == null && saved < 0)
ChatLine("[RynthAi] Unknown counters make \"T11: Can Wield\" -1. Use /ra t11 refresh, or /ra t11 augs <n>.");
}
/// <summary>/ra t11 augs &lt;n|auto&gt;: saves the item-aug override (-1 = read from /aug).</summary>
private void SetT11ItemAugOverride(string arg)
{
if (_dashboard == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; }
int value;
if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1")
value = -1;
else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0)
{
ChatLine("[RynthAi] Usage: /ra t11 augs <n|auto> (n = your item augmentation count)");
return;
}
_dashboard.Settings.T11ItemAugsOverride = value;
_dashboard.SaveSettings();
T11ItemSupport.SyncOverride(value);
ChatLine(value < 0
? "[RynthAi] T11: item augmentations now come from /aug."
: $"[RynthAi] T11: item augmentations fixed at {value:N0} for loot rules.");
}
/// <summary>/ra t11 item [0xId]: the parsed T11 text of an item (selected item by default).</summary>
private void PrintT11Item(string? idArg)
{
uint id = 0;
if (!string.IsNullOrEmpty(idArg))
uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg,
NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id);
if (id == 0 && Host.HasGetSelectedItemId) id = Host.GetSelectedItemId();
if (id == 0) { ChatLine("[RynthAi] T11: select an item first (or pass 0xId)."); return; }
int iid = unchecked((int)id);
WorldObject item = _objectCache?[iid]
?? new WorldObject(iid, Host.TryGetObjectName(id, out string n) ? n : string.Empty) { Cache = _objectCache };
T11ItemInfo info = T11ItemSupport.Get(item);
if (!info.IsT11)
{
bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(id);
ChatLine(appraised
? $"[RynthAi] T11: {item.Name} is not a T11 item."
: $"[RynthAi] T11: {item.Name} isn't appraised yet - ID it and try again.");
return;
}
ChatLine($"[RynthAi] === T11: {item.Name} (0x{id:X8}) ===");
ChatLine($"[RynthAi] Tier ~{info.EstimatedTier}" + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty)
+ (info.ZoneLocked ? ", zone locked" : string.Empty));
foreach (T11WieldGate g in info.WieldGates)
ChatLine($"[RynthAi] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}");
foreach (T11Modifier m in info.Modifiers)
{
string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty;
ChatLine($"[RynthAi] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}");
}
foreach ((string name, double chance) in info.Procs)
ChatLine($"[RynthAi] Cast on strike: {name} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)");
int canWield = item.Values(T11Keys.CanWield, -1);
ChatLine($"[RynthAi] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}"
+ $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%");
string keys = string.Join(", ", T11Keys.Names()
.Where(k => k.Id < T11Keys.ModifierBase)
.Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={item.Values(k.Id, 0)}"));
ChatLine($"[RynthAi] Loot keys: {keys}");
}
}

View file

@ -29,8 +29,6 @@
</ItemGroup>
<ItemGroup>
<!-- Install-folder resolver used by the ILT Hub, diagnostics, and chat translator. -->
<Compile Include="..\..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- UB damage-insights seed schema, shared with the Monster Editor importer. -->
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
@ -39,10 +37,16 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.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. -->
<Compile Include="..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
<!-- Movement calls logged with the subsystem that sent them (stuck-cast diagnosis, 2026-10-05). -->
<Compile Include="..\Shared\MoveAudit.cs" Link="Shared\MoveAudit.cs" />
<!-- One server action at a time, paced on the server's answers (stuck use/cast, 2026-10-06). -->
<Compile Include="..\Shared\ActionPacer.cs" Link="Shared\ActionPacer.cs" />
<!-- Text in the world on the Nav3D buffer (waypoint labels; RynthNav's path markers use it too). -->
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
</ItemGroup>
<ItemGroup>
@ -97,4 +101,9 @@
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
<ItemGroup>
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -45,7 +45,7 @@ namespace RynthCore.Plugin.RynthAi.Trade;
/// </summary>
internal sealed class AutoTradeManager
{
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoTrade";
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoTrade");
public const string ProfileSubfolder = "AutoTrade";
public const string AutoAcceptListFileName = "autoAcceptList.json";
public const uint RequiredApiVersion = 72;

View file

@ -170,7 +170,7 @@ public sealed partial class RynthAiPlugin
{
string n = name.Trim().Trim('"');
if (File.Exists(n)) return n;
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
{
string p = Path.Combine(folder, cand);
@ -236,7 +236,7 @@ public sealed partial class RynthAiPlugin
int sp = args.IndexOf(' ');
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
file = file.Trim('"');
if (!Path.IsPathRooted(file)) file = Path.Combine(@"C:\Games\RynthSuite\RynthAi", file);
if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file);
if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; }
try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); }
catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); }
@ -352,7 +352,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
return;
}
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]);
string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]);
if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav";

View file

@ -34,7 +34,7 @@ namespace RynthCore.Plugin.RynthAi.Vendor;
/// </summary>
internal sealed class AutoVendorManager
{
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor");
public const string ProfileSubfolder = "AutoVendor";
private const long BailMs = 60_000; // UB bailTimer
@ -76,6 +76,7 @@ internal sealed class AutoVendorManager
private long _nextPollAt;
private int _failures;
private readonly HashSet<uint> _sessionSkip = new(); // items the engine refused to sell
private readonly HashSet<string> _sellSkipLogged = new(StringComparer.OrdinalIgnoreCase); // names logged as held back this session
private readonly List<uint> _idQueue = new();
private readonly Dictionary<uint, (int Attempts, long LastAt)> _idState = new();
@ -457,6 +458,7 @@ internal sealed class AutoVendorManager
_profilePath = path;
_failures = 0;
_sessionSkip.Clear();
_sellSkipLogged.Clear();
_bailAt = Now();
_nextActionAt = 0;
_host.Log($"[RynthAi] AutoVendor: {_vendorName} [0x{merchantId:X8}] profile '{path}' ({_profile.Rules.Count} rules)");
@ -853,14 +855,36 @@ internal sealed class AutoVendorManager
SafetyFacts safety = ReadSafety(wo, player);
string? unsafeWhy = AutoVendorPlanner.UnsafeReason(safety, _settings.AutoVendorOnlyFromMainPack);
if (unsafeWhy != null && heldBack == null)
{
if (!_sellSkipLogged.Contains(wo.Name))
{
ProfileVerdict uv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
// "Not identified" is usually just not yet (the IDs are on their way): only a
// certain Sell match is worth a line.
if (uv.Rule?.Action == VTankLootAction.Sell && uv.Certain && _sellSkipLogged.Add(wo.Name))
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{uv.RuleName}'): {unsafeWhy}.");
}
continue;
}
uint type = ItemType(wo);
int stack = StackOf(wo);
bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
int unitValue = stack > 1 ? safety.Value / stack : safety.Value;
if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue))
{
// A Sell rule wanted it and the vendor won't take it: say why, once per name a
// session (peas not sold at Aun Amanaualuan, 2026-10-07, with nothing logged).
if (heldBack == null && !_sellSkipLogged.Contains(wo.Name))
{
ProfileVerdict sv = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
if (sv.Rule?.Action == VTankLootAction.Sell && sv.Certain && _sellSkipLogged.Add(wo.Name))
_host.Log(!v.Buys(type)
? $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): this vendor doesn't buy {AutoVendorPlanner.CategoryName(type)} (item type 0x{type:X}, vendor buys 0x{v.ItemTypes:X})."
: $"[RynthAi] AutoVendor: not selling '{wo.Name}' (rule '{sv.RuleName}'): worth {unitValue:n0} each, this vendor pays for items up to {v.MaxValue:n0}.");
}
continue;
}
ItemFacts f = InventoryFacts(wo, safety.Appraised);
ProfileVerdict verdict = AutoVendorRules.Decide(_profile.Rules, Judge(EvalObject(wo), f, ctx));
@ -876,6 +900,8 @@ internal sealed class AutoVendorManager
{
if (heldBack != null && verdict.Rule?.Action == VTankLootAction.Sell)
heldBack.Add($"{wo.Name} - {sd.Reason}");
else if (heldBack == null && verdict.Rule?.Action == VTankLootAction.Sell && _sellSkipLogged.Add(wo.Name))
_host.Log($"[RynthAi] AutoVendor: not selling '{wo.Name}': {sd.Reason}.");
continue;
}

View file

@ -254,7 +254,9 @@ internal static class AutoVendorPlanner
if (f.IsRare) return "rare";
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
if (f.Attuned != 0) return "attuned";
if (f.Bonded != 0) return "bonded";
// Not Bonded: on ACE it only decides what a death keeps (PropertyInt.Bonded, Player_Death);
// it never stops a sale. Peas, trade notes and salvage bags are bonded so a death keeps
// them, and AutoVendor held them all back (2026-10-07). Quest items are not sellable anyway.
if (f.Retained) return "retained";
if (f.TimesTinkered > 0) return "tinkered";
if (f.Imbued != 0) return "imbued";