Snapshot for release 2026.10.19.1 (internal f0bdcf8)

This commit is contained in:
Tom Bohar 2026-10-19 09:11:22 -04:00
commit 39de36d3af
131 changed files with 11266 additions and 520 deletions

View file

@ -0,0 +1,119 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster attack power (2026-10-12): MonsterRule.AttackPower.
//
// Default the DEFAULT line's choice; on the DEFAULT line, the global
// Melee/Missile Power settings (Auto = 100%, or 80% with Use
// Recklessness and the skill trained)
// High 100% every swing or shot
// Reckless 80%: inside the band where Recklessness adds damage (ACE:
// 10%-90% of the bar, retail wiki: 20%-80%, so 80% is in both)
// Variable a new random power each attack, Variable Power Min..Max
// Reckless + Variable random each attack, inside the Recklessness band (20%-80%)
// and the Variable range
//
// Recklessness only adds damage when the skill is trained or specialized; with it
// untrained a reckless choice falls back to High (or Variable), since a short bar
// would only cost damage. Magic doesn't use attack power.
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.AttackPower"/>.</summary>
public static class AttackPowerModes
{
public const string Default = "Default";
public const string High = "High";
public const string Reckless = "Reckless";
public const string Variable = "Variable";
public const string RecklessVariable = "Reckless + Variable";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, High, Reckless, Variable, RecklessVariable };
/// <summary>The bar fraction a fixed reckless attack uses.</summary>
public const float RecklessPower = 0.8f;
/// <summary>The Recklessness band used for a varied reckless attack (retail wiki: 20%-80%).</summary>
public const int RecklessBandMinPct = 20;
public const int RecklessBandMaxPct = 80;
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed and meta spellings: "RecklessVariable", "reckless+variable".
string squeezed = v.Replace(" ", "").Replace("+", "");
if (squeezed.Equals("RecklessVariable", StringComparison.OrdinalIgnoreCase)) return RecklessVariable;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's, else
/// Default (the global settings). <paramref name="defaultRule"/> may be the same object.
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.AttackPower);
if (own != Default) return own;
return Normalize(defaultRule?.AttackPower);
}
/// <summary>
/// The power bar fraction (0..1) for one attack.
/// <paramref name="globalPct"/> is the global Melee/Missile Power (-1 = Auto);
/// <paramref name="random01"/> returns a value in [0, 1).
/// </summary>
public static float Resolve(string mode, int globalPct, bool useRecklessness, bool recklessTrained,
int variableMinPct, int variableMaxPct, Func<double> random01)
{
switch (Normalize(mode))
{
case High:
return 1.0f;
case Reckless:
return recklessTrained ? RecklessPower : 1.0f;
case Variable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
return Pick(lo, hi, random01);
}
case RecklessVariable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
if (!recklessTrained) return Pick(lo, hi, random01);
int rlo = Math.Max(lo, RecklessBandMinPct);
int rhi = Math.Min(hi, RecklessBandMaxPct);
// The Variable range doesn't overlap the band (e.g. 85-100): the whole band.
if (rlo > rhi) { rlo = RecklessBandMinPct; rhi = RecklessBandMaxPct; }
return Pick(rlo, rhi, random01);
}
default:
if (globalPct < 0)
return useRecklessness && recklessTrained ? RecklessPower : 1.0f;
return Math.Clamp(globalPct, 0, 100) / 100f;
}
}
/// <summary>The Variable range in percent, clamped to 0..100 and put in order.</summary>
public static (int Lo, int Hi) VariableRange(int minPct, int maxPct)
{
int lo = Math.Clamp(minPct, 0, 100), hi = Math.Clamp(maxPct, 0, 100);
return lo <= hi ? (lo, hi) : (hi, lo);
}
private static float Pick(int loPct, int hiPct, Func<double> random01)
{
double r = Math.Clamp(random01(), 0.0, 1.0);
double pct = loPct + (hiPct - loPct) * r;
return (float)(Math.Round(pct) / 100.0);
}
}

View file

@ -24,6 +24,9 @@
// yield (MayRestartMacro), and a death drops the pending recall (the player's
// Stop Macro On Death stands).
// Health back over the line (or 100%) ends the episode. Nothing counts in portal space.
// The failsafe (jump included) is for a character that can heal: it arms only with a heal that went
// out in the last minute, or a heal spell / kit / health potion at hand (HealCapableNow). A melee
// character with nothing to heal with is not jumped or recalled. HpFailsafeRecall defaults to off.
// ============================================================================
using System;
@ -92,6 +95,9 @@ public partial class BuffManager
ResetHpFailsafe();
return;
}
// Only a character that can heal at all: a melee character with no spell, kit or potion
// (resting, or out-healed) has nothing for the failsafe to retry, and a recall there is wrong.
if (!HealCapableNow(now)) { ResetHpFailsafe(); return; }
if (!_fsActive)
{
_fsActive = true;
@ -146,6 +152,59 @@ public partial class BuffManager
StartFailsafeRecall(now, hp, failedSec);
}
// A heal (spell, kit or potion) that actually went out: the failsafe's proof the character can heal.
private DateTime _lastHealSentAt = DateTime.MinValue;
private DateTime _healCapableCheckAt = DateTime.MinValue;
private bool _healCapableCached;
/// <summary>A heal sent this recently proves the character can heal (kit used up since, a script's drain).</summary>
internal const double HealSentProofMs = 60_000;
/// <summary>Every heal that goes out (cast, kit, potion) records itself here, then feeds the latency tracker.</summary>
private void NoteHealSent(string action)
{
_lastHealSentAt = Now;
_healLatency.HealSent(Now, action);
}
/// <summary>
/// Can this character heal at all? A heal went out in the last HealSentProofMs, or one could now: a known
/// Heal Self / Stamina to Health Self with Life Magic trained, a healing kit, or a health potion
/// (Use Potions on and one listed or in the pack). Read at most once a second (it walks the pack).
/// </summary>
private bool HealCapableNow(DateTime now)
{
if (_lastHealSentAt != DateTime.MinValue && (now - _lastHealSentAt).TotalMilliseconds < HealSentProofMs) return true;
if ((now - _healCapableCheckAt).TotalMilliseconds < 1000 && _healCapableCheckAt != DateTime.MinValue) return _healCapableCached;
_healCapableCheckAt = now;
bool capable = false;
try
{
if (IsSkillUsable(AcSkillType.LifeMagic))
{
foreach (string spell in new[] { "Heal Self", "Stamina to Health Self" })
{
if (_spellManager.GetDynamicSelfBuffId(spell, AcSkillType.LifeMagic) != 0
|| _spellManager.GetSelfSpellIdAboveAllowedTier(spell, AcSkillType.LifeMagic) != 0) { capable = true; break; }
}
}
if (!capable && _worldObjectCache != null)
{
if (BestPackHealingKit() != null) capable = true;
else
{
foreach (var r in _settings.ConsumableRules)
if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
&& !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
&& ConsumableLookup.Resolve(_worldObjectCache, r) != null) { capable = true; break; }
}
if (!capable && _settings.UsePotions && HasListedPotion("HealthPotion")) capable = true;
}
}
catch { capable = false; }
_healCapableCached = capable;
return capable;
}
private void ResetHpFailsafe()
{
_fsActive = false;

View file

@ -156,6 +156,20 @@ public partial class BuffManager : IDisposable
// like any cast.
private int _pendingUpgradeSpellId;
// Consecutive SILENT no-shows of an upgrade, per family (the registry never moved / no chat for an
// item spell). An upgrade's no-show is no strike on the family (see the no-show branches), so
// without a bound a cast the server silently drops loops forever: an item enchant whose lower
// record is still on the books after the armor was lost or the weapon swapped (nothing to bind
// to), or a self-buff the server ignores. In a force/batch run that holds _isForceRebuffing, and
// with it buffing's priority over fighting, for good. After UpgradeNoShowThreshold of them the
// UPGRADE alone is parked for UpgradeParkCooldown: the family is not blacklisted or put in
// _buffFailCooldownUntil, and the level it was cast over keeps refreshing as a normal cast.
// Cleared by any confirmed cast of the family (NoteBuffConfirmed) and by Force Rebuff.
private readonly Dictionary<int, int> _upgradeNoShowCounts = new();
private readonly Dictionary<int, DateTime> _upgradeParkedUntil = new();
private const int UpgradeNoShowThreshold = 3;
private static readonly TimeSpan UpgradeParkCooldown = TimeSpan.FromMinutes(5);
// Per-family diagnostic throttle — last reason string we logged. Suppresses
// dup spam when IsBuffActive is polled every tick by NeedsAnyBuff + CheckAndCastSelfBuffs.
private readonly Dictionary<int, string> _lastArmorRecastReason = new();
@ -974,6 +988,20 @@ public partial class BuffManager : IDisposable
public void RequestForceFullRebuff() => System.Threading.Interlocked.Exchange(ref _forceRebuffRequested, 1);
public void RequestCancelBuffing() => System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 1);
// /ra buff skipped runs on AC's chat-command thread; building the list there would write the pump's
// kit and skip fields from a second thread. The command only sets this; the pump builds and reports.
private int _skipReportRequested;
public void RequestSkipReport() => System.Threading.Interlocked.Exchange(ref _skipReportRequested, 1);
private void ReportFilterSkips()
{
BuildDynamicBuffList(); // refreshes the skip list, even with buffing off
string summary = _filterSummary;
_host.WriteToChat(summary.Length == 0
? "[RynthAi] Buff filter: nothing is being skipped."
: $"[RynthAi] Buff filter skips: {summary}", 1);
}
public void ForceFullRebuff()
{
_isForceRebuffing = true;
@ -984,8 +1012,11 @@ public partial class BuffManager : IDisposable
_unsatisfiedStrikes.Clear(); // ditto for the post-batch satisfaction audit
_castIssuedAtByFamily.Clear();
_expiryAtCastByFamily.Clear();
_upgradeNoShowCounts.Clear(); // and a fresh try at parked upgrades
_upgradeParkedUntil.Clear();
_ramBuffTimers.Clear();
_itemSpellTimers.Clear();
EndPendingUpgrade(_pendingSpellId, "a new Force Rebuff");
_pendingSpellId = 0;
_lastCastAttempt = DateTime.MinValue;
SaveBuffTimers();
@ -1005,6 +1036,7 @@ public partial class BuffManager : IDisposable
_isRechargingMana = false;
_isRechargingStamina = false;
_isHealingSelf = false;
EndPendingUpgrade(_pendingSpellId, "buffing cancelled");
_pendingSpellId = 0;
_chain.PassEnd("cancelled", s => _host.Log(s));
_host.WriteToChat("[RynthAi] Sequence cancelled.", 5);
@ -1237,6 +1269,8 @@ public partial class BuffManager : IDisposable
ForceFullRebuff();
if (System.Threading.Interlocked.Exchange(ref _cancelBuffingRequested, 0) != 0)
CancelBuffing();
if (System.Threading.Interlocked.Exchange(ref _skipReportRequested, 0) != 0)
ReportFilterSkips();
// Post-cast diffs for the bufftest experiment run unconditionally — even if the
// user toggled the macro off mid-experiment, we still want to capture and log them.
@ -1347,6 +1381,7 @@ public partial class BuffManager : IDisposable
&& CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s)) && !BusyHoldsHeal())
{
_host.Log($"[BuffDiag] health {_vitals.HealthPct}% under a heal line: released pending buff id={_pendingSpellId} to heal first.");
EndPendingUpgrade(_pendingSpellId, "released to heal");
_pendingSpellId = 0;
_onCastResolved?.Invoke("released to heal");
}
@ -1444,6 +1479,7 @@ public partial class BuffManager : IDisposable
if (isUpgrade)
{
_host.Log($"[BuffDiag] upgrade '{pendingSpell.Name}' (id={_pendingSpellId}, fam={fam}) not in the live registry after {sinceCastMs:0}ms (the lower level is unchanged): no strike, tried again.");
NoteUpgradeNoShow(_pendingSpellId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row
}
else
{
@ -1493,6 +1529,8 @@ public partial class BuffManager : IDisposable
bool confirmedKnown = _spellManager.IsKnownSnapshotWarm && _spellManager.IsKnownSpellId(stuckId);
if (!confirmedKnown && !isUpgrade)
_spellManager.MarkSpellUnresolvable(stuckId);
if (isUpgrade)
NoteUpgradeNoShow(stuckId); // bounded: parks the upgrade (only) after UpgradeNoShowThreshold in a row
// 2026-05-25 — per-family silent-no-show bookkeeping on the
// ARMOR path, mirroring the self-buff path above.
@ -2241,7 +2279,7 @@ public partial class BuffManager : IDisposable
if (_pendingVitalLabel == LabelHealing)
{
_healSpellIds.Add(spellId);
_healLatency.HealSent(Now, what);
NoteHealSent(what);
}
return true;
}
@ -2292,7 +2330,7 @@ public partial class BuffManager : IDisposable
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
_lastPotionAt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, rule.Name);
if (IsHealthPotionType(types)) NoteHealSent(rule.Name);
return true;
}
if (listedOnly) return VitalNo("none listed in Consumables");
@ -2308,7 +2346,7 @@ public partial class BuffManager : IDisposable
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
_lastPotionAt = DateTime.Now;
_lastCastAttempt = DateTime.Now;
if (IsHealthPotionType(types)) _healLatency.HealSent(Now, wo.Name ?? "health potion");
if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion");
return true;
}
return VitalNo("none in the Items list or the pack");
@ -2461,7 +2499,7 @@ public partial class BuffManager : IDisposable
_host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: healing kit on yourself");
_lastCastAttempt = DateTime.Now;
MarkKitUsed();
_healLatency.HealSent(Now, kit.Name ?? "healing kit");
NoteHealSent(kit.Name ?? "healing kit");
return true;
}
@ -3119,7 +3157,8 @@ public partial class BuffManager : IDisposable
// run cast (the priority buffs landed and raised the skill, or a higher spell was
// learned). Never lower: a skill that dropped leaves the run's cast alone.
if (_forceRebuffCastFamilies.Contains(targetSpell.Family))
return !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
return UpgradeParked(targetSpell.Family)
|| !(CastLevelThisRun(targetSpell.Family) is int ran && ran > 0 && GetSpellLevel(targetSpell) > ran);
if (!_isAutoBatchRebuff) return false;
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
}
@ -3142,7 +3181,7 @@ public partial class BuffManager : IDisposable
{
if (_itemSpellTimers.TryGetValue(targetSpell.Family, out ItemSpellRecord? itemTimer))
{
if (itemTimer.SpellLevel < targetLevel)
if (itemTimer.SpellLevel < targetLevel && !UpgradeParked(targetSpell.Family))
{
LogArmorRecast(targetSpell, $"tier-upgrade recordedLvl={itemTimer.SpellLevel} < targetLvl={targetLevel} (recorded='{itemTimer.SpellName}')");
return false;
@ -3184,7 +3223,7 @@ public partial class BuffManager : IDisposable
// login) keeps the cap, so a relog doesn't recast every capped Incantation.
int effectiveTarget = EffectiveTargetLevel(targetSpell);
if (timer.SpellLevel < effectiveTarget)
if (timer.SpellLevel < effectiveTarget && !UpgradeParked(targetSpell.Family))
{
LogPlayerRecast(targetSpell, $"tier-upgrade storedLvl={timer.SpellLevel} < effTarget={effectiveTarget} (nominal={targetLevel}, achievedCap={(_familyAchievedTier.TryGetValue(targetSpell.Family, out int a2) ? a2 : -1)}, stored='{timer.SpellName}')");
return false;
@ -3240,6 +3279,8 @@ public partial class BuffManager : IDisposable
int level = GetSpellLevel(spell);
if (!_familyAttemptedTier.TryGetValue(spell.Family, out int prev) || level > prev)
_familyAttemptedTier[spell.Family] = level;
// A cast of the family landed: the server takes it, so no upgrade no-show streak or park stands.
ClearUpgradeNoShows(spell.Family);
// The pending upgrade (or better) landed.
if (_pendingUpgradeSpellId != 0 && SpellTableStub.GetById(_pendingUpgradeSpellId) is { } up
&& up.Family == spell.Family && level >= GetSpellLevel(up))
@ -3253,8 +3294,9 @@ public partial class BuffManager : IDisposable
/// <summary>
/// The pending upgrade cast <paramref name="spellId"/> did not take (fizzle, refusal, no mana,
/// no-show): it is no longer pending, and it is cast again at the next opportunity. No try cap,
/// and no rest after a fizzle, a client refusal or a no-show; a server mana or component refusal
/// still rests the family as it does for any buff.
/// and no rest after a fizzle or a client refusal; a server mana or component refusal still rests
/// the family as it does for any buff. A SILENT no-show is the exception to "no cap": after
/// UpgradeNoShowThreshold in a row the upgrade (only) is parked (NoteUpgradeNoShow).
/// </summary>
private void EndPendingUpgrade(int spellId, string why)
{
@ -3262,6 +3304,41 @@ public partial class BuffManager : IDisposable
_pendingUpgradeSpellId = 0;
_host.Log($"[Buff] upgrade to {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} did not take ({why}); cast again at the next opportunity.");
}
/// <summary>True while upgrades of <paramref name="family"/> are parked after repeated silent no-shows.</summary>
private bool UpgradeParked(int family)
=> family != 0 && _upgradeParkedUntil.TryGetValue(family, out DateTime until) && DateTime.Now < until;
/// <summary>
/// The pending upgrade <paramref name="spellId"/> was a silent no-show (nothing showed in the
/// registry / no chat). Counts it; at UpgradeNoShowThreshold in a row the family's upgrades are
/// parked for UpgradeParkCooldown (and the count starts over for the next window). Nothing else
/// is touched: no strike, no family park, no blacklist.
/// </summary>
private void NoteUpgradeNoShow(int spellId)
{
int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
if (family == 0) return;
int count = _upgradeNoShowCounts.TryGetValue(family, out int prev) ? prev + 1 : 1;
if (count >= UpgradeNoShowThreshold)
{
_upgradeNoShowCounts.Remove(family);
_upgradeParkedUntil[family] = DateTime.Now + UpgradeParkCooldown;
_host.Log($"[Buff] upgrade of family {family} ({SpellTableStub.GetById(spellId)?.Name}) never showed {count} times in a row: upgrades of it parked {UpgradeParkCooldown.TotalMinutes:0}min " +
"(the level it was cast over still refreshes as a normal cast; the family is not blacklisted).");
}
else
{
_upgradeNoShowCounts[family] = count;
_host.Log($"[Buff] upgrade of family {family} did not show ({count}/{UpgradeNoShowThreshold} before it is parked).");
}
}
private void ClearUpgradeNoShows(int family)
{
_upgradeNoShowCounts.Remove(family);
_upgradeParkedUntil.Remove(family);
}
/// <summary>
/// The level IsBuffActive holds a player buff to: the target spell's level, capped at the
/// highest level that family has landed at, once the target level has been confirmed and
@ -3283,6 +3360,9 @@ public partial class BuffManager : IDisposable
/// </summary>
private int ActiveLevelBelow(int family, int newLevel)
{
// Upgrades parked after repeated silent no-shows: a cast of the family now is the normal
// refresh of what is on (no upgrade line, and its no-show is judged like any other buff's).
if (UpgradeParked(family)) return 0;
int on = 0;
if (_isForceRebuffing && _forceRebuffCastFamilies.Contains(family)) on = CastLevelThisRun(family);
else if (_ramBuffTimers.TryGetValue(family, out RamTimerInfo? t)
@ -3902,6 +3982,14 @@ public partial class BuffManager : IDisposable
private DateTime _filterSkipLoggedAt = DateTime.MinValue;
private string _filterSkipLoggedSummary = "";
private const double FilterSkipLogMinSec = 30;
// "skill untrained" is true of nearly every character (an unspecialised melee skill has no mastery to cast),
// so it would make the chat line print at every buff run. It stays in the summary (/ra buff skipped, the
// Buffing page) and the log, and is left out of the chat line.
internal const string SkillUntrainedReason = "skill untrained";
private string _filterChatSummary = "";
private int _filterChatCount;
private DateTime _filterChatLoggedAt = DateTime.MinValue;
private string _filterChatLoggedSummary = "";
private const int SummaryNamesPerReason = 5;
private void SetFilterSkips(List<(string Buff, string Reason)> skips)
@ -3912,6 +4000,9 @@ public partial class BuffManager : IDisposable
if (same) return;
_filterSkips = skips.Count == 0 ? Array.Empty<(string, string)>() : skips;
_filterSummary = BuildSummary(skips);
var notable = skips.FindAll(s => s.Reason != SkillUntrainedReason);
_filterChatCount = notable.Count;
_filterChatSummary = notable.Count == skips.Count ? _filterSummary : BuildSummary(notable);
}
/// <summary>"skill untrained: A, B, C, D, E (+12 more); no melee or missile weapon listed: Blood Drinker, Heart Seeker".</summary>
@ -3946,19 +4037,27 @@ public partial class BuffManager : IDisposable
/// <summary>The skipped buffs grouped by reason, or "".</summary>
public string FilterSkipSummary() => _filterSummary;
// One line per buff run (Force Rebuff, or the automatic batch starting). Same content as the
// last line is held back for FilterSkipLogMinSec; different content prints at once. Reads the
// skips of the BuildDynamicBuffList pass the caller just made.
// One log line and (when something besides untrained skills is skipped) one chat line per buff run
// (Force Rebuff, or the automatic batch starting). Same content as the last line is held back for
// FilterSkipLogMinSec; different content prints at once. Reads the skips of the BuildDynamicBuffList
// pass the caller just made.
private void LogFilterSkips()
{
var now = DateTime.Now;
string summary = _filterSummary;
if (summary.Length == 0) return;
var now = DateTime.Now;
if (summary == _filterSkipLoggedSummary && (now - _filterSkipLoggedAt).TotalSeconds < FilterSkipLogMinSec) return;
_filterSkipLoggedAt = now;
_filterSkipLoggedSummary = summary;
_host.WriteToChat($"[RynthAi] Buff run skips {_filterSkips.Count} buff(s) this character can't use - {summary}", 1);
_host.Log($"[Buff] filter skips: {summary}");
if (summary != _filterSkipLoggedSummary || (now - _filterSkipLoggedAt).TotalSeconds >= FilterSkipLogMinSec)
{
_filterSkipLoggedAt = now;
_filterSkipLoggedSummary = summary;
_host.Log($"[Buff] filter skips: {summary}");
}
string chat = _filterChatSummary;
if (chat.Length == 0) return;
if (chat == _filterChatLoggedSummary && (now - _filterChatLoggedAt).TotalSeconds < FilterSkipLogMinSec) return;
_filterChatLoggedAt = now;
_filterChatLoggedSummary = chat;
_host.WriteToChat($"[RynthAi] Buff run skips {_filterChatCount} buff(s) this character can't use - {chat}", 1);
}
internal List<string> BuildDynamicBuffList()
{
@ -4009,7 +4108,7 @@ public partial class BuffManager : IDisposable
if (!IsSkillUsable(kvp.Key))
{
// Always left out (no skill, no mastery to cast); the setting only decides whether it is reported.
if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, "skill untrained"));
if (filter && !BaseCreatureBuffs.Contains(kvp.Value)) skips.Add((kvp.Value, SkillUntrainedReason));
continue;
}
if (kvp.Value.Contains("Creature Enchantment Mastery"))
@ -5387,9 +5486,13 @@ public partial class BuffManager : IDisposable
{
if ((DateTime.Now - asked.At).TotalSeconds >= WandIdRetrySec)
{
_host.RequestId(uid);
_wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now);
_host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)");
// Counted only when the engine took it: a refused ask (a death or a portal) is not one of the
// WandIdMaxAsks, and the wand is held back and asked about again.
if (_host.RequestId(uid))
{
_wandIdAsked[wo.Id] = (asked.Count + 1, DateTime.Now);
_host.Log($"[WieldGate] identifying 0x{uid:X8} '{wo.Name}' before using it to buff (its wield requirement isn't known yet)");
}
}
return true;
}

View file

@ -0,0 +1,523 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Environment-impact throttle (2026-10-12). Rules and bookkeeping in EnvironmentImpact.cs.
///
/// missile "Your missile attack hit the environment." in Missile mode counts one hit on the
/// target the server's attack is bound to.
/// magic each single-target war/void cast is watched: our projectiles (named like the
/// shape, "Flame Bolt") are claimed as they appear next to the player, followed until
/// they stop or vanish, and the cast counts one hit when every projectile stopped
/// short of the target (ProjectileImpactJudge) and no hit, resist or evade line came
/// back for it. Rings and walls aren't watched: they don't fly at the target.
///
/// At EnvironmentImpactLimit hits within the window the throttle trips: the server's attack is
/// released (a magic cast in flight finishes first) and the chosen response runs: an approach
/// (autorun toward the target, at most EnvironmentApproachMeters, never nearer than
/// EnvironmentMinDistance, bounded in time and by progress), or a new target (this one skipped
/// for EnvironmentSkipSec). Off = no detection at all.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the throttle and the projectile watch; tests replace it.</summary>
internal Func<DateTime> EnvClock { get; set; } = () => DateTime.Now;
internal EnvironmentImpactThrottle EnvThrottle { get; } = new();
/// <summary>The start of the chat line ACE sends the shooter (ProjectileCollisionHelper.OnCollideEnvironment,
/// a Broadcast line). Matched at the line's start only: a player's copy has their name in front.</summary>
internal const string MissileEnvironmentText = "Your missile attack hit the environment";
// A cast's projectiles appear once its windup ends (up to ~2.5 s for a high tier).
private const double CastClaimWindowMs = 4000;
// Our projectile spawns at the caster; farther than this at its first sight it isn't ours.
private const double ClaimRadiusMeters = 8.0;
// Still this long after flying counts as stopped (ACE zeroes its velocity on impact).
private const double StoppedForMs = 250;
private const double StillMeters = 0.05;
// A projectile still flying after this is dropped from the watch (no verdict).
private const double ProjectileMaxFlightMs = 8000;
// After the last projectile stops, a hit/resist/evade line still has this long to arrive.
private const double ImpactEvidenceGraceMs = 1000;
private const int MaxCastWatches = 4;
// An approach that hasn't gained this much ground in ApproachNoProgressMs is blocked.
private const double ApproachProgressMeters = 0.5;
private const double ApproachNoProgressMs = 2500;
private const double ApproachMaxMs = 8000;
private const double ApproachRunRefreshMs = 1000;
private const double ApproachTurnRefreshMs = 300;
private const double ApproachFaceToleranceDeg = 10;
// Think stopped driving the approach (buffing took over, out of range): let go of autorun.
private const double ApproachOrphanMs = 1500;
private enum EnvKind { Missile, Magic }
private sealed class TrackedProjectile
{
public uint Id;
public double StartX, StartY, StartZ;
public double LastX, LastY, LastZ;
public DateTime FirstSeen, LastMoved;
public double Travel;
public bool Resolved, Short;
}
private sealed class CastWatch
{
public int TargetId;
public string SpellName = "";
public DateTime CastAt;
public double CasterX, CasterY, CasterZ;
public bool HasCasterPos;
public readonly List<TrackedProjectile> Projectiles = new();
public DateTime LastImpactAt = DateTime.MinValue;
}
// Creates are queued and claimed by the heartbeat poll (the name lands a moment later).
private readonly ConcurrentQueue<(uint Id, DateTime At)> _envCreated = new();
private readonly List<(uint Id, DateTime At)> _envCandidates = new();
private readonly List<CastWatch> _castWatches = new();
private readonly Dictionary<int, DateTime> _envSkipUntil = new();
private DateTime _envLastEvidenceAt = DateTime.MinValue;
// The trip waiting for Think, and the approach in progress.
private int _envPendingTargetId;
private EnvKind _envPendingKind;
private int _envApproachTargetId;
private EnvKind _envApproachKind;
private double _envApproachGoal, _envApproachBestDist;
private DateTime _envApproachStartedAt, _envApproachProgressAt, _envApproachRunAt, _envApproachTurnAt, _envApproachTickAt;
private bool _envApproachUsedMotions;
/// <summary>True while combat is walking toward a target for its environment hits.</summary>
internal bool EnvironmentApproachActive => _envApproachTargetId != 0;
private EnvironmentResponse ResponseFor(EnvKind kind) => EnvironmentImpactPlanner.Parse(
kind == EnvKind.Missile ? _settings.MissileEnvironmentResponse : _settings.MagicEnvironmentResponse);
// ── Signals ────────────────────────────────────────────────────────────────
/// <summary>A new object. Only queued while the macro runs with magic detection on
/// (the heartbeat poll that drains the queue runs only then). Separate from OnObjectCreated,
/// which feeds the ghost tracker on every create.</summary>
public void OnEnvironmentObjectCreated(uint objectId)
{
if (objectId == 0 || _settings.MagicEnvironmentResponse == 0 || !_settings.IsMacroRunning) return;
_envCreated.Enqueue((objectId, EnvClock()));
}
/// <summary>From OnObjectDeleted: a projectile that vanished has hit something, and a
/// monster id that's gone forgets its hits, approaches and skip.</summary>
private void OnEnvironmentObjectDeleted(uint objectId)
{
int id = (int)objectId;
EnvThrottle.Forget(id);
_envSkipUntil.Remove(id);
if (_castWatches.Count == 0) return;
DateTime now = EnvClock();
foreach (var w in _castWatches)
foreach (var p in w.Projectiles)
if (p.Id == objectId && !p.Resolved) ResolveProjectile(w, p, now);
}
/// <summary>The missile line, from HandleChatForDamage. True when it was that line.</summary>
private bool NoteMissileEnvironmentChat(string text)
{
if (!ChatSource.StartsWithMarker(text, MissileEnvironmentText, StringComparison.OrdinalIgnoreCase)) return false;
if (ResponseFor(EnvKind.Missile) == EnvironmentResponse.Off) return true;
if (CurrentCombatMode != CombatMode.Missile) return true;
int target = _serverAttackTargetId != 0 ? _serverAttackTargetId : activeTargetId;
if (target != 0) RecordEnvironmentImpact(target, EnvKind.Missile, "missile hit the environment");
return true;
}
/// <summary>Any sign an attack reached a monster (hit, resist, evade, a health drop):
/// a cast with one of these after it didn't only hit the environment.</summary>
private void NoteEnvironmentEvidence() => _envLastEvidenceAt = EnvClock();
/// <summary>A single-target cast just went out (AttackWithMagic): watch its projectiles.</summary>
internal void RegisterCastWatch(int targetId, string spellName)
{
if (ResponseFor(EnvKind.Magic) == EnvironmentResponse.Off || targetId == 0) return;
DateTime now = EnvClock();
var w = new CastWatch { TargetId = targetId, SpellName = spellName, CastAt = now };
if (TryGetPlayerGlobal(out double px, out double py, out double pz))
{
w.CasterX = px; w.CasterY = py; w.CasterZ = pz; w.HasCasterPos = true;
}
if (_castWatches.Count >= MaxCastWatches) _castWatches.RemoveAt(0);
_castWatches.Add(w);
}
/// <summary>Counts one environment hit; at the limit, arms the response for Think.</summary>
private void RecordEnvironmentImpact(int targetId, EnvKind kind, string detail)
{
DateTime now = EnvClock();
int limit = Math.Max(1, _settings.EnvironmentImpactLimit);
int window = Math.Max(1, _settings.EnvironmentImpactWindowSec);
int n = EnvThrottle.Record(targetId, now, window);
string name = _worldFilter[targetId]?.Name ?? "";
_host.Log($"[EnvImpact] {kind.ToString().ToLowerInvariant()}: {detail} — 0x{(uint)targetId:X8} '{name}' {n}/{limit} in {window}s");
if (n < limit || targetId != activeTargetId) return;
if (_envApproachTargetId == targetId) return; // already moving closer to it
_envPendingTargetId = targetId;
_envPendingKind = kind;
}
// ── Heartbeat: projectile watch and the approach's safety net ─────────────
/// <summary>Every heartbeat while the macro runs (pump thread).</summary>
internal void PollEnvironmentImpact()
{
DateTime now = EnvClock();
if (_settings.MagicEnvironmentResponse == 0)
{
while (_envCreated.TryDequeue(out _)) { }
_envCandidates.Clear();
_castWatches.Clear();
}
else
{
while (_envCreated.TryDequeue(out var c)) _envCandidates.Add(c);
ClaimProjectiles(now);
TrackProjectiles(now);
JudgeCastWatches(now);
}
// Think drives the approach; when it stops (another activity, out of range, combat off)
// or the deadline passes, autorun must not be left on.
if (_envApproachTargetId != 0
&& ((now - _envApproachTickAt).TotalMilliseconds > ApproachOrphanMs
|| (now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs + ApproachOrphanMs
|| !_settings.EnableCombat))
EndEnvironmentApproach("combat stopped driving it");
// Same for the re-sync sidestep's movement key: Think releases it after ResyncStepMs,
// but only while it keeps ticking in magic mode.
if (_resyncState == 2 && (TargetClock() - _resyncAt).TotalMilliseconds > ResyncStepMs + ApproachOrphanMs)
AbandonResync("combat stopped driving it");
}
private void ClaimProjectiles(DateTime now)
{
if (_envCandidates.Count == 0) return;
bool havePlayer = TryGetPlayerGlobal(out double px, out double py, out double pz);
for (int i = _envCandidates.Count - 1; i >= 0; i--)
{
var (id, at) = _envCandidates[i];
string name = _worldFilter[(int)id]?.Name ?? "";
if (name.Length == 0 && _host.TryGetObjectName(id, out string n2)) name = n2;
if (name.Length == 0)
{
// The name lands a moment after the create; give it a second.
if ((now - at).TotalMilliseconds > 1000) _envCandidates.RemoveAt(i);
continue;
}
_envCandidates.RemoveAt(i);
if (!IsWatchedProjectileName(name)) continue;
if (!havePlayer || !TryGetObjectGlobal(id, out double x, out double y, out double z)) continue;
if (Dist(px, py, pz, x, y, z) > ClaimRadiusMeters) continue;
// The newest cast still taking projectiles (a blast's several share one cast).
CastWatch? owner = null;
for (int w = _castWatches.Count - 1; w >= 0; w--)
{
double age = (at - _castWatches[w].CastAt).TotalMilliseconds;
if (age >= -50 && age <= CastClaimWindowMs) { owner = _castWatches[w]; break; }
}
if (owner == null) continue;
owner.Projectiles.Add(new TrackedProjectile
{
Id = id, StartX = x, StartY = y, StartZ = z, LastX = x, LastY = y, LastZ = z,
FirstSeen = now, LastMoved = now,
});
}
}
/// <summary>A war/void projectile: the shape names (SpellShapes/VoidSpellShapes), or any
/// name ending in a flying shape (lore-named projectiles of the same shapes).</summary>
internal static bool IsWatchedProjectileName(string name)
{
if (IsSpellProjectileName(name)) return !name.EndsWith(" Ring", StringComparison.OrdinalIgnoreCase);
return name.EndsWith(" Bolt", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Streak", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Arc", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Blast", StringComparison.OrdinalIgnoreCase);
}
private void TrackProjectiles(DateTime now)
{
foreach (var w in _castWatches)
{
foreach (var p in w.Projectiles)
{
if (p.Resolved) continue;
if ((now - p.FirstSeen).TotalMilliseconds > ProjectileMaxFlightMs)
{
p.Resolved = true; // no verdict: treated as not short
continue;
}
if (!TryGetObjectGlobal(p.Id, out double x, out double y, out double z)) continue;
if (Dist(x, y, z, p.LastX, p.LastY, p.LastZ) > StillMeters)
{
p.LastX = x; p.LastY = y; p.LastZ = z;
p.LastMoved = now;
p.Travel = Math.Max(p.Travel, Dist(x, y, z, p.StartX, p.StartY, p.StartZ));
continue;
}
if (p.Travel >= ProjectileImpactJudge.MinTravelMeters
&& (now - p.LastMoved).TotalMilliseconds >= StoppedForMs)
ResolveProjectile(w, p, now);
}
}
}
private void ResolveProjectile(CastWatch w, TrackedProjectile p, DateTime now)
{
p.Resolved = true;
w.LastImpactAt = now;
if (p.Travel < ProjectileImpactJudge.MinTravelMeters) return;
if (!TryGetObjectGlobal((uint)w.TargetId, out double tx, out double ty, out double tz)) return;
double cx = w.CasterX, cy = w.CasterY, cz = w.CasterZ;
if (!w.HasCasterPos) { cx = p.StartX; cy = p.StartY; cz = p.StartZ; }
p.Short = ProjectileImpactJudge.StoppedShort(
Dist(p.LastX, p.LastY, p.LastZ, tx, ty, tz),
Dist(cx, cy, cz, p.LastX, p.LastY, p.LastZ),
Dist(cx, cy, cz, tx, ty, tz));
}
private void JudgeCastWatches(DateTime now)
{
for (int i = _castWatches.Count - 1; i >= 0; i--)
{
var w = _castWatches[i];
double age = (now - w.CastAt).TotalMilliseconds;
if (w.Projectiles.Count == 0)
{
if (age > CastClaimWindowMs + 500) _castWatches.RemoveAt(i); // refused or never seen
continue;
}
// A blast's projectiles all appear together; wait out the claim window only briefly.
bool allResolved = w.Projectiles.TrueForAll(p => p.Resolved);
if (!allResolved) continue;
if ((now - w.LastImpactAt).TotalMilliseconds < ImpactEvidenceGraceMs) continue;
_castWatches.RemoveAt(i);
bool reached = _envLastEvidenceAt >= w.CastAt;
bool allShort = w.Projectiles.TrueForAll(p => p.Short);
if (!reached && allShort)
RecordEnvironmentImpact(w.TargetId, EnvKind.Magic,
$"'{w.SpellName}' stopped short of the target ({w.Projectiles.Count} projectile{(w.Projectiles.Count == 1 ? "" : "s")})");
}
}
// ── Think: the response ───────────────────────────────────────────────────
/// <summary>
/// In ThinkCore once the target is valid and in reach. True = this tick belongs to the
/// response (an approach under way, or the target just switched): no attack.
/// </summary>
internal bool RunEnvironmentImpact(WorldObject targetObj, double currentDist)
{
DateTime now = EnvClock();
if (_envApproachTargetId != 0)
{
if (_envApproachTargetId == activeTargetId)
return ContinueEnvironmentApproach(targetObj, currentDist, now);
EndEnvironmentApproach("the target changed");
}
if (_envPendingTargetId == 0) return false;
if (_envPendingTargetId != activeTargetId) { _envPendingTargetId = 0; return false; }
EnvKind kind = _envPendingKind;
// The cast in flight finishes first: turning or running now would cancel it.
if (kind == EnvKind.Magic && IsCastInFlight()) return true;
// A re-sync sidestep already holding a movement key finishes first: running or turning
// over it would send two movement states at once.
if (_resyncState == 2) return true;
int id = activeTargetId;
_envPendingTargetId = 0;
EnvThrottle.ResetHits(id);
EnvironmentResponse response = ResponseFor(kind);
int minDist = Math.Max(1, _settings.EnvironmentMinDistance);
EnvironmentAction action = EnvironmentImpactPlanner.Decide(response, EnvThrottle.Approaches(id),
currentDist, minDist, HasAlternateTarget(id));
string who = $"0x{(uint)id:X8} '{targetObj.Name}' at {currentDist:0.0}m";
string why = kind == EnvKind.Missile ? "missiles" : "spells";
switch (action)
{
case EnvironmentAction.NewTarget:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
int skip = Math.Max(1, _settings.EnvironmentSkipSec);
_envSkipUntil[id] = now.AddSeconds(skip);
_host.Log($"[EnvImpact] {why} keep hitting the environment: leaving {who}, skipping it {skip}s ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("a new target");
ForgetScanned(id);
DropTarget("environment hits: new target");
return true;
}
case EnvironmentAction.Approach:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
double goal = EnvironmentImpactPlanner.ApproachGoal(currentDist, _settings.EnvironmentApproachMeters, minDist);
EnvThrottle.NoteApproach(id);
_envApproachTargetId = id;
_envApproachKind = kind;
_envApproachGoal = goal;
_envApproachBestDist = currentDist;
_envApproachStartedAt = _envApproachProgressAt = _envApproachTickAt = now;
_envApproachRunAt = _envApproachTurnAt = DateTime.MinValue;
_envApproachUsedMotions = false;
_host.Log($"[EnvImpact] {why} keep hitting the environment: moving closer to {who}, stopping at {goal:0.0}m ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("moving closer");
return ContinueEnvironmentApproach(targetObj, currentDist, now);
}
default:
_host.Log($"[EnvImpact] {why} keep hitting the environment on {who}, but it's the only monster in reach and already close: attacking on");
return false;
}
}
/// <summary>
/// The throttle acted on misses the magic re-sync (TickResyncStep) was also counting. The
/// misses are explained (a wall in the way), so the re-sync's count starts over, and a
/// sidestep that is wanted but not yet started is dropped. Moving closer is itself real
/// movement, which re-syncs the server's copy of our position anyway.
/// </summary>
private void SupersedeResync(string by)
{
_magicMissesSinceHit = 0;
if (_resyncState != 1) return;
_resyncState = 0;
_host.Log($"[EnvImpact] re-sync sidestep dropped: {by} answers the misses");
}
/// <summary>Stops a re-sync sidestep where it is, letting go of its movement key if held.</summary>
private void AbandonResync(string why)
{
if (_resyncState == 0) return;
if (_resyncState == 2) _host.SetMotionBy("Combat/Resync", _resyncMotion, false);
_resyncState = 0;
_host.Log($"[CombatCast] re-sync sidestep stopped: {why}");
}
private bool ContinueEnvironmentApproach(WorldObject targetObj, double currentDist, DateTime now)
{
_envApproachTickAt = now;
if (currentDist <= _envApproachGoal)
{
EndEnvironmentApproach($"reached {currentDist:0.0}m");
return false;
}
if ((now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs)
{
EndEnvironmentApproach($"timed out at {currentDist:0.0}m");
return false;
}
if (currentDist < _envApproachBestDist - ApproachProgressMeters)
{
_envApproachBestDist = currentDist;
_envApproachProgressAt = now;
}
else if ((now - _envApproachProgressAt).TotalMilliseconds > ApproachNoProgressMs)
{
EndEnvironmentApproach($"no progress (blocked?) at {currentDist:0.0}m");
return false;
}
// Face the target, then run. A held call (the pacer, a use) is simply tried next tick.
if ((now - _envApproachTurnAt).TotalMilliseconds >= ApproachTurnRefreshMs
&& TryGetHeadingTo(activeTargetId, out double desiredDeg, out double err)
&& err > ApproachFaceToleranceDeg)
{
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Approach", (float)desiredDeg)) _envApproachTurnAt = now;
}
else
{
FaceTarget(activeTargetId);
_envApproachUsedMotions = true;
_envApproachTurnAt = now;
}
}
if ((now - _envApproachRunAt).TotalMilliseconds >= ApproachRunRefreshMs
&& _host.SetAutoRunBy("Combat/Approach", true))
_envApproachRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "env-approach"; // D4 record-only
return true;
}
/// <summary>Stops an approach in progress (autorun off). Safe to call when none is.</summary>
private void EndEnvironmentApproach(string why)
{
if (_envApproachTargetId == 0) return;
int id = _envApproachTargetId;
_envApproachTargetId = 0;
if (_envApproachRunAt != DateTime.MinValue) _host.SetAutoRunBy("Combat/Approach", false);
if (_envApproachUsedMotions) ClearCombatTurnMotions();
_host.Log($"[EnvImpact] {_envApproachKind.ToString().ToLowerInvariant()} approach to 0x{(uint)id:X8} ended: {why}");
}
/// <summary>True while <paramref name="id"/> is being skipped for its environment hits.</summary>
private bool IsEnvironmentSkipped(int id)
{
if (_envSkipUntil.Count == 0 || !_envSkipUntil.TryGetValue(id, out DateTime until)) return false;
if (EnvClock() < until) return true;
_envSkipUntil.Remove(id);
return false;
}
/// <summary>Clears every environment-impact state (macro stop, new character).</summary>
private void ResetEnvironmentImpact(string why)
{
EndEnvironmentApproach(why);
AbandonResync(why);
_envPendingTargetId = 0;
_castWatches.Clear();
_envCandidates.Clear();
while (_envCreated.TryDequeue(out _)) { }
EnvThrottle.Clear();
_envSkipUntil.Clear();
}
// ── Positions (global metres: landblock x/y * 192 + the in-block offset) ──
private bool TryGetObjectGlobal(uint id, out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetObjectPosition(id, out uint cell, out float lx, out float ly, out float lz)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private bool TryGetPlayerGlobal(out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz,
out _, out _, out _, out _)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private static double Dist(double ax, double ay, double az, double bx, double by, double bz)
{
double dx = ax - bx, dy = ay - by, dz = az - bz;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}

View file

@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared; // TurnToHeadingBy / SetAutoRunBy
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Kite / pull-away (2026-10-16). Rules in KiteModes.cs; distance in LegacyUiSettings.KitePullMeters.
///
/// When the effective monster rule is PullAway, combat tags the mob (one hit window), then
/// autoruns away from its lock-spot origin until the mob has been dragged that many metres
/// clear of where it stood, then stops and kills it. Default and per-mob via MonsterRule.Kite.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the kite state machine; tests replace it.</summary>
internal Func<DateTime> KiteClock { get; set; } = () => DateTime.Now;
// Face-away + autorun cadence (mirrors EnvironmentApproach).
private const double KiteTurnRefreshMs = 300;
private const double KiteRunRefreshMs = 1000;
// Think stopped driving the kite (buffing took over): let go of autorun.
private const double KiteOrphanMs = 1500;
// Tag window: allow attacks so aggro sticks before we turn and run.
private const double KiteTagMaxMs = 2500;
// A pull that never gets far enough (blocked, mob leashed) gives up and fights in place.
private const double KiteMaxMs = 20000;
// Don't outrun the chase: stop autorun when farther than this from the mob.
private const double KiteCatchUpSlackMeters = 1.5;
// Progress toward the pull goal; no gain in this long ⇒ blocked / leashed.
private const double KiteProgressMeters = 0.75;
private const double KiteNoProgressMs = 4000;
private enum KitePhase { None, Tag, Flee, Done }
private int _kiteTargetId;
private KitePhase _kitePhase = KitePhase.None;
private double _kiteOriginX, _kiteOriginY, _kiteOriginZ;
private bool _kiteHasOrigin;
private double _kiteBestPull;
private DateTime _kiteStartedAt, _kiteProgressAt, _kiteRunAt, _kiteTurnAt, _kiteTickAt;
private bool _kiteUsedMotions;
// Targets already pulled this engagement (object id): do not re-kite mid-fight.
private readonly HashSet<int> _kiteDoneIds = new();
/// <summary>True while combat is tagging or running a pull-away for the locked target.</summary>
internal bool KiteActive => _kitePhase is KitePhase.Tag or KitePhase.Flee;
/// <summary>
/// In ThinkCore once the target is valid. True = this tick belongs to the kite (flee under
/// way): no attack. Tag phase returns false so the first hit(s) can land.
/// </summary>
internal bool RunKite(WorldObject targetObj, double currentDist)
{
DateTime now = KiteClock();
int id = activeTargetId;
if (id == 0) { EndKite("no target"); return false; }
// Already pulled this object id for this engagement: fight in place.
if (_kiteDoneIds.Contains(id))
{
if (_kiteTargetId == id) EndKite("already pulled");
return false;
}
var rule = GetRuleForTarget(targetObj);
if (!KiteModes.WantsPullAway(rule, DefaultMonsterRule()))
{
if (_kiteTargetId == id) EndKite("rule Off");
return false;
}
// Start (or retarget) a pull for this lock.
if (_kiteTargetId != id || _kitePhase == KitePhase.None)
{
if (_kiteTargetId != 0 && _kiteTargetId != id)
EndKite("the target changed");
BeginKite(id, targetObj, now);
}
_kiteTickAt = now;
double pullMeters = Math.Max(3.0, _settings.KitePullMeters);
if (_kitePhase == KitePhase.Tag)
{
bool tagged = _lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _kiteStartedAt;
bool tagTimedOut = (now - _kiteStartedAt).TotalMilliseconds >= KiteTagMaxMs;
if (!_settings.KiteTagFirst || tagged || tagTimedOut)
{
_kitePhase = KitePhase.Flee;
_kiteBestPull = PullDistance(id);
_kiteProgressAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
string why = !_settings.KiteTagFirst ? "tag skipped"
: tagged ? "tagged"
: "tag timed out";
_host.Log($"[Kite] pull-away on 0x{(uint)id:X8} '{targetObj.Name}': fleeing ({why}), goal {pullMeters:0}m from origin");
EndEnvironmentApproach("kite pull-away");
}
else
{
LastCombatSkipReason = "kite-tag";
return false; // let Think attack once so aggro sticks
}
}
if (_kitePhase != KitePhase.Flee) return false;
double pulled = PullDistance(id);
if (pulled >= pullMeters)
{
FinishKite(id, $"pulled {pulled:0.0}m");
return false;
}
if ((now - _kiteStartedAt).TotalMilliseconds > KiteMaxMs)
{
FinishKite(id, $"timed out at {pulled:0.0}m");
return false;
}
if (pulled > _kiteBestPull + KiteProgressMeters)
{
_kiteBestPull = pulled;
_kiteProgressAt = now;
}
else if ((now - _kiteProgressAt).TotalMilliseconds > KiteNoProgressMs)
{
FinishKite(id, $"no progress (blocked/leashed?) at {pulled:0.0}m");
return false;
}
// Don't outrun the chase past disengage: wait for the mob to catch up.
double catchUp = Math.Max(1.0, DisengageDistance - KiteCatchUpSlackMeters);
bool waiting = currentDist > catchUp;
// Face away from the mob while fleeing; face it while waiting for catch-up.
if ((now - _kiteTurnAt).TotalMilliseconds >= KiteTurnRefreshMs
&& TryGetHeadingTo(id, out double towardDeg, out _))
{
double faceDeg = waiting ? towardDeg : (towardDeg + 180.0) % 360.0;
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Kite", (float)faceDeg)) _kiteTurnAt = now;
}
else
{
// No heading snap: FaceTarget only faces toward the mob (useful while waiting).
if (waiting) { FaceTarget(id); _kiteUsedMotions = true; }
_kiteTurnAt = now;
}
}
if (waiting)
{
if (_kiteRunAt != DateTime.MinValue)
{
_host.SetAutoRunBy("Combat/Kite", false);
_kiteRunAt = DateTime.MinValue;
}
LastCombatSkipReason = "kite-wait";
_stallWatch.Hold(now);
return true;
}
if ((now - _kiteRunAt).TotalMilliseconds >= KiteRunRefreshMs
&& _host.SetAutoRunBy("Combat/Kite", true))
_kiteRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "kite-flee";
return true;
}
private void BeginKite(int id, WorldObject targetObj, DateTime now)
{
_kiteTargetId = id;
_kitePhase = _settings.KiteTagFirst ? KitePhase.Tag : KitePhase.Flee;
_kiteHasOrigin = TryGetObjectGlobal((uint)id, out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
if (!_kiteHasOrigin)
_kiteHasOrigin = TryGetPlayerGlobal(out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
_kiteBestPull = 0;
_kiteStartedAt = _kiteProgressAt = _kiteTickAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
_kiteUsedMotions = false;
string phase = _kitePhase == KitePhase.Tag ? "tag then flee" : "flee";
_host.Log($"[Kite] pull-away start 0x{(uint)id:X8} '{targetObj.Name}' ({phase}, {_settings.KitePullMeters}m)");
if (_kitePhase == KitePhase.Flee)
EndEnvironmentApproach("kite pull-away");
}
/// <summary>How far the mob has been dragged from its lock-spot origin (metres).</summary>
private double PullDistance(int id)
{
if (!_kiteHasOrigin) return 0;
if (!TryGetObjectGlobal((uint)id, out double x, out double y, out double z))
return _kiteBestPull;
return Dist(x, y, z, _kiteOriginX, _kiteOriginY, _kiteOriginZ);
}
/// <summary>Pull succeeded or gave up: remember the id and fight in place.</summary>
private void FinishKite(int id, string why)
{
_kiteDoneIds.Add(id);
if (_kiteDoneIds.Count > 64) _kiteDoneIds.Clear();
EndKite(why);
_host.Log($"[Kite] pull-away done 0x{(uint)id:X8}: {why} — attacking");
}
/// <summary>Stops a kite in progress (autorun off). Safe to call when none is.</summary>
private void EndKite(string why)
{
if (_kitePhase == KitePhase.None && _kiteTargetId == 0) return;
int id = _kiteTargetId;
bool wasRunning = _kiteRunAt != DateTime.MinValue;
_kiteTargetId = 0;
_kitePhase = KitePhase.None;
_kiteHasOrigin = false;
if (wasRunning) _host.SetAutoRunBy("Combat/Kite", false);
if (_kiteUsedMotions) ClearCombatTurnMotions();
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
if (id != 0)
_host.Log($"[Kite] ended 0x{(uint)id:X8}: {why}");
}
/// <summary>Clears kite state (macro stop, new character).</summary>
private void ResetKite(string why)
{
EndKite(why);
_kiteDoneIds.Clear();
}
/// <summary>
/// Pump-thread orphan watch: Think drives the flee; when it stops (another activity,
/// combat off) autorun must not be left on.
/// </summary>
internal void PollKite()
{
if (_kitePhase == KitePhase.None) return;
DateTime now = KiteClock();
if ((now - _kiteTickAt).TotalMilliseconds > KiteOrphanMs
|| !_settings.EnableCombat
|| !_settings.IsMacroRunning)
EndKite("combat stopped driving it");
}
}

View file

@ -1033,6 +1033,9 @@ public partial class CombatManager : IDisposable
// A ghost (the server doesn't have it for us): skipped until it shows it is real.
if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; }
// Left for hitting the environment (New target): skipped for EnvironmentSkipSec.
if (IsEnvironmentSkipped(wo.Id)) continue;
// Just killed (KillerNotification) but not yet a corpse — skip so we
// don't re-lock and cast at it during its death animation.
if (_recentlyKilled.ContainsKey(wo.Id)) continue;
@ -1135,6 +1138,7 @@ public partial class CombatManager : IDisposable
_hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
Ghosts.NoteDeleted(id);
OnEnvironmentObjectDeleted(objectId);
if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId)
_awaitingCastResolution = false;
@ -1436,13 +1440,15 @@ public partial class CombatManager : IDisposable
_damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount);
}
/// <summary>A chat line for the damage meter and the stall watchdog.
/// <summary>A chat line for the damage meter, the stall watchdog and the environment throttle.
/// <paramref name="chatType"/> is the line's eChatTypes (-1 = not known).</summary>
public void HandleChatForDamage(string text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return;
// Combat lines come from the server; one in a player's chat type is someone's imitation.
if (RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return;
// An arrow into a wall: the environment-impact throttle's missile signal.
if (NoteMissileEnvironmentChat(text)) return;
// A miss is a swing too (stall watchdog). "You evaded X!" is the monster's miss, not ours.
if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0)
NoteSwingEvidence("miss");
@ -1455,6 +1461,7 @@ public partial class CombatManager : IDisposable
if (critLine) _lastCritChatAt = now;
if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return;
NoteEnvironmentEvidence(); // a cast that hit something didn't only hit the environment
bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS;
// Which monster the line is about. One spell can hurt several (rings, walls, blasts,
@ -1878,12 +1885,214 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
// ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ─────────
// ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred
// to release a lethal ring." The ring can't be melee-evaded — if the character is
// inside its cast radius they die. On that line, when still in range of a Handler,
// cancel the current swing/cast and back-jump away, then resume combat (target kept).
private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring";
private const string HandlerRingChannelStart = "The handler briefly channels";
private const string HandlerNameHint = "Empyrean Handler";
/// <summary>Yards: Handler lethal ring is treated as at least this wide (RingRange when larger).</summary>
internal const double HandlerRingDangerYards = 12.0;
/// <summary>Back-jump charge (ms) — run-back + jump must clear ~ring radius.</summary>
private const int HandlerRingJumpHoldMs = 750;
private const double HandlerRingEvadeCooldownMs = 4_000;
private DateTime _handlerRingEvadeAt = DateTime.MinValue;
private DateTime _handlerRingEvadeUntil = DateTime.MinValue;
private int _handlerRingEvadeId;
private bool _handlerRingJumpStarted;
/// <summary>
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the Handler
/// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused.
/// </summary>
public Func<float, int, bool>? RequestBackJump { get; set; }
/// <summary>True while the wired jumper is mid-turn / charge / settle.</summary>
public Func<bool>? JumpBusy { get; set; }
/// <summary>True while a Handler-ring evade is holding combat (jump or settle).</summary>
public bool RingEvadeActive =>
_handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil;
/// <summary>
/// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the
/// Handler channels its lethal ring and the character is still inside ring range.
/// </summary>
public void HandleChatForRingEvade(string? text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return;
// Gate: only while the macro is running with combat on, and only if the setting allows it.
// Otherwise a Handler line heard while the character is idle or being driven by hand (or by a
// meta) would take over the keyboard for a back-jump.
if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return;
// Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as
// player speech, which would skip every real Handler line — anchor on the unique
// phrase starting the line instead (player copies are "Name says, \"...\").
bool anchored =
RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase)
|| (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase)
&& text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (!anchored)
{
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech
or RynthCore.Plugin.Shared.ChatSource.Tell
or RynthCore.Plugin.Shared.ChatSource.OutgoingTell
or RynthCore.Plugin.Shared.ChatSource.Channel
or RynthCore.Plugin.Shared.ChatSource.ChannelSend
or RynthCore.Plugin.Shared.ChatSource.Allegiance
or RynthCore.Plugin.Shared.ChatSource.Fellowship)
return;
if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return;
if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0)
return;
}
DateTime now = DateTime.Now;
if (_handlerRingEvadeAt != DateTime.MinValue
&& (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs)
return;
if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name))
{
_host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump.");
return;
}
double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
return;
}
// Face the Handler, then Jumper "xs" (back + run) moves the body away from it.
// Facing away + back-jump would leap into the ring.
float faceHandler = 0f;
if (TryGetHeadingTo(handlerId, out double toHandler, out _))
faceHandler = (float)(toHandler % 360.0);
else if (_host.TryGetPlayerHeading(out float curr))
faceHandler = curr;
_handlerRingEvadeAt = now;
_handlerRingEvadeId = handlerId;
_handlerRingJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
try
{
if (_host.HasCancelAttack) _host.CancelAttack();
ReleaseHeldTurn();
}
catch { }
bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true;
if (started)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs.");
}
else
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start.");
}
}
/// <summary>
/// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target
/// so combat re-engages as soon as the jumper settles.
/// </summary>
private bool TickRingEvade()
{
if (_handlerRingEvadeUntil == DateTime.MinValue) return false;
DateTime now = DateTime.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
// Jump never started / failed: clear early.
if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil)
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
return false;
}
if (jumperBusy || now < _handlerRingEvadeUntil)
{
LastCombatSkipReason = "handler-ring-evade";
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
return false;
}
/// <summary>Nearest Empyrean Handler (active target preferred when it is one).</summary>
private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)
{
handlerId = 0; dist = double.MaxValue; name = "";
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
if (me == 0) return false;
int bestId = 0;
double bestDist = double.MaxValue;
string bestName = "";
void Consider(int id, string? nm)
{
if (id == 0 || string.IsNullOrEmpty(nm)) return;
if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return;
double d = _worldFilter.Distance(me, id);
if (d < 0 || d >= bestDist) return;
bestDist = d; bestId = id; bestName = nm;
}
if (activeTargetId != 0)
Consider(activeTargetId, _worldFilter[activeTargetId]?.Name);
foreach (var s in _scannedTargets)
Consider(s.Id, s.Name);
// Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach).
if (bestId == 0)
{
try
{
foreach (WorldObject wo in _worldFilter.GetLandscape())
{
if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue;
Consider(wo.Id, wo.Name);
}
}
catch { }
}
if (bestId == 0) return false;
handlerId = bestId; dist = bestDist; name = bestName;
return true;
}
public void ReportDamageOnTarget(int targetId)
{
_magicMissesSinceHit = 0; // something we cast landed: the server's position is fine
// Damage / health change on the cast we're judging → that cast HIT.
if (targetId == _pendingJudgeTargetId)
_damageSincePendingCast = true;
NoteEnvironmentEvidence();
// Immediate positive feedback on the engaged target clears the streak.
if (targetId == _lastAttackedTargetId)
_consecutiveCastMisses = 0;
@ -1904,6 +2113,7 @@ public partial class CombatManager : IDisposable
int i = text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase);
if (i < 0) i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase);
if (i <= 0) return;
NoteEnvironmentEvidence(); // the spell or swing reached a monster
string who = text.Substring(0, i).Trim();
if (who.StartsWith("The ", StringComparison.Ordinal)) who = who.Substring(4);
if (who.Length == 0) return;
@ -2225,6 +2435,9 @@ public partial class CombatManager : IDisposable
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]");
activeTargetId = 0;
_lockedTargetId = 0;
EndKite("target dropped");
EndEnvironmentApproach("target dropped");
_envPendingTargetId = 0;
// A turn held toward the dropped target must be let go, or the character keeps
// spinning until something else happens to release it.
if (_facingTarget) ClearCombatTurnMotions();
@ -2675,9 +2888,15 @@ public partial class CombatManager : IDisposable
// one busy-count tick; only the first encounter of a wcid pays it.
if (!_fightAppraiseRequested)
{
_fightAppraiseRequested = true;
try { if (_host.HasRequestId) _host.RequestId((uint)_fightTargetId); } catch { }
try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { }
// Done only once the engine took the request (it refuses around a death or a portal; a refused one
// is asked again next tick). No RequestId at all: nothing to wait for.
bool idTaken = true;
try { if (_host.HasRequestId) idTaken = _host.RequestId((uint)_fightTargetId); } catch { }
if (idTaken)
{
_fightAppraiseRequested = true;
try { if (_host.HasQueryHealth) _host.QueryHealth((uint)_fightTargetId); } catch { }
}
}
}
@ -2727,6 +2946,7 @@ public partial class CombatManager : IDisposable
int id = _scannedTargets[i].Id;
if (id == excludeId) continue;
if (_recentlyKilled.ContainsKey(id)) continue;
if (IsEnvironmentSkipped(id)) continue;
return true;
}
return false;
@ -2878,6 +3098,11 @@ public partial class CombatManager : IDisposable
return true;
}
// Empyrean Handler lethal-ring back-jump: hold casts/swings until the jump settles,
// then fall through and re-engage the same target.
if (TickRingEvade())
return true;
double acDistanceLimit = _settings.MonsterRange;
// Hysteresis: a locked target is retained (and kept under attack) out to
// the larger disengage distance, while new targets are still only
@ -2977,7 +3202,7 @@ public partial class CombatManager : IDisposable
ForgetScanned(activeTargetId);
DropTarget("hp=0");
}
else if (target != null &&
else if (target != null && !KiteActive &&
_worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit)
DropTarget("out of range");
// If target == null here it's a transient world-filter miss — keep the lock,
@ -3098,9 +3323,18 @@ public partial class CombatManager : IDisposable
// step-back — instead of dropping to peace and restarting the approach.
double currentDist = _worldFilter.Distance(
_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId);
// Pull-away kite runs before the disengage gate: fleeing intentionally stretches
// range, and the kite itself waits for catch-up rather than idling here.
if (RunKite(targetObj, currentDist))
return true;
if (currentDist > disengageLimit)
return true;
// Environment-impact throttle: too many missiles/spells into walls short of this target
// stop the attack and move closer or switch target (CombatManager.EnvironmentImpact.cs).
if (RunEnvironmentImpact(targetObj, currentDist))
return true;
// Melee/missile stall safety net (see CombatStallWatchdog). Holds the attack while
// one of its steps is settling.
if (RunStallWatchdog(targetObj, currentDist))
@ -3929,13 +4163,23 @@ public partial class CombatManager : IDisposable
{
_wasMacroRunning = false;
ClearCombatTurnMotions();
ResetEnvironmentImpact("macro stopped");
ResetKite("macro stopped");
}
return;
}
_wasMacroRunning = true;
NotePriorityZeroRules();
LogCombatStateIfChanged();
// Environment-impact throttle: follow our spell projectiles, judge finished casts, and
// let go of an approach Think stopped driving.
try { PollEnvironmentImpact(); }
catch (Exception ex) { _host.Log($"[EnvImpact] poll crashed: {ex.Message}"); }
try { PollKite(); }
catch (Exception ex) { _host.Log($"[Kite] poll crashed: {ex.Message}"); }
// A combat mode change ends the server's attack (HandleActionChangeCombatMode →
// HandleActionCancelAttack), so out of Melee/Missile there is nothing bound to release.
if (_serverAttackTargetId != 0)
@ -4016,6 +4260,8 @@ public partial class CombatManager : IDisposable
{
if (_scannedTargets.Count == 0) return;
if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs
// Pull-away in progress: keep the incumbent until the kite ends (do not switch mid-flee).
if (KiteActive && _lockedTargetId != 0) return;
// Boost Loot Priority: the next target waits for the last kill's corpse. Without this the
// next lock went out a few ms after each kill, 1-3 s before ACE creates the corpse, so the
// arbiter always saw combat engaged and corpses were looted in batches (2026-10-14).
@ -4236,6 +4482,35 @@ public partial class CombatManager : IDisposable
return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs;
}
private List<MonsterRule>? _priorityZeroNoticeRules;
private string _priorityZeroNoticeKey = "";
/// <summary>
/// Priority 0 on a monster rule now means "never attacked or tracked" (before, it was a lowest
/// priority that still fought back). A profile written under the old meaning would silently stop
/// fighting those monsters, so the first time a rule list holds any, one log line and one chat
/// notice say what it does now (again only if the set of Priority 0 rules changes, e.g. another
/// profile loads). Behavior is not changed.
/// </summary>
internal void NotePriorityZeroRules()
{
var rules = _settings.MonsterRules;
if (ReferenceEquals(rules, _priorityZeroNoticeRules)) return;
_priorityZeroNoticeRules = rules;
List<string>? zero = null;
foreach (var rule in rules)
if (rule.Priority <= 0) (zero ??= new List<string>()).Add(string.IsNullOrWhiteSpace(rule.Name) ? "(unnamed)" : rule.Name);
if (zero == null) { _priorityZeroNoticeKey = ""; return; }
string key = string.Join("|", zero).ToLowerInvariant();
if (key == _priorityZeroNoticeKey) return;
_priorityZeroNoticeKey = key;
string names = zero.Count <= 5 ? string.Join(", ", zero) : string.Join(", ", zero.GetRange(0, 5)) + $" and {zero.Count - 5} more";
string line = $"[RynthAi] Monsters: Priority 0 now means 'never attacked or tracked', even if the monster attacks you " +
$"(rows with Priority 0: {names}). Raise the row's Priority to fight it.";
_host.Log(line);
_host.WriteToChat(line, 2);
}
/// <summary>True when the monster rule for <paramref name="id"/> says Priority 0 (never attacked).</summary>
internal bool IsIgnored(int id) => id != ForcedTargetId && PriorityOf(id) <= 0;
@ -6101,17 +6376,26 @@ public partial class CombatManager : IDisposable
return false;
}
float power;
// Power: the monster rule's Attack Power (High / Reckless / Variable / Reckless +
// Variable), else the global Melee/Missile Power (AttackPowerPlanner.cs).
int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower;
if (powerPct < 0)
bool recklessTrained = _charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2;
// No rule asking for a power (every rule on Default, as saved before this existed):
// the rule lookup is skipped, the global setting applies exactly as it always did.
WorldObject? powerTarget = null;
string powerMode = AttackPowerModes.Default;
if (AnyAttackPowerRule())
{
power = 1.0f;
if (_settings.UseRecklessness && (_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2))
power = 0.8f;
powerTarget = _worldFilter[activeTargetId];
powerMode = AttackPowerModes.Effective(GetRuleForTarget(powerTarget), DefaultMonsterRule());
}
else
float power = AttackPowerModes.Resolve(powerMode, powerPct, _settings.UseRecklessness, recklessTrained,
_settings.VariablePowerMin, _settings.VariablePowerMax, PowerRandom);
if (powerMode != AttackPowerModes.Default && _powerLoggedTargetId != activeTargetId)
{
power = powerPct / 100f;
_powerLoggedTargetId = activeTargetId;
_host.Log($"[AttackPower] 0x{targetId:X8} '{powerTarget?.Name}': {powerMode}" +
(recklessTrained ? "" : " (Recklessness untrained: no reckless band)") + $", first attack at {power * 100:0}%");
}
int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
@ -6173,10 +6457,25 @@ public partial class CombatManager : IDisposable
if (matches) return r;
}
return _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
return DefaultMonsterRule();
}
/// <summary>The Monsters tab's DEFAULT line (the catch-all rule), or null.</summary>
private MonsterRule? DefaultMonsterRule() => _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
/// <summary>True when some monster rule has an Attack Power other than Default.</summary>
private bool AnyAttackPowerRule()
{
foreach (MonsterRule r in _settings.MonsterRules)
if (AttackPowerModes.Normalize(r.AttackPower) != AttackPowerModes.Default) return true;
return false;
}
/// <summary>Random source for Variable attack power, [0, 1); tests replace it.</summary>
internal Func<double> PowerRandom { get; set; } = Random.Shared.NextDouble;
private int _powerLoggedTargetId;
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
@ -6282,11 +6581,8 @@ public partial class CombatManager : IDisposable
}
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
// A rule with no attack shape on means no offensive cast at this monster: a script's choice
// is no exception (it used to be asked first, and cast at a monster the owner turned casting off for).
if (rule != null && PickBaseShape(rule) < 0)
{
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast");
@ -6294,6 +6590,11 @@ public partial class CombatManager : IDisposable
return;
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0;
int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0;
int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing, out int castShape, arcTargetId: activeTargetId);
@ -6353,6 +6654,10 @@ public partial class CombatManager : IDisposable
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
// Environment-impact throttle: follow this cast's projectiles (rings and walls
// don't fly at the target, so they aren't judged).
if (!multiTarget)
RegisterCastWatch(activeTargetId, SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
// Tag this cast's weapon + element + tier so the pushed damage event
// can be attributed to it, count it for casts-to-kill learning, then

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Environment-impact throttle (2026-10-12): pure rules and bookkeeping.
//
// A missile or a war/void projectile that hits a wall, a pillar, the ceiling
// or another object short of the target does no damage, and before this the bot
// kept firing into it until the no-damage blacklist (several settle windows) or
// the no-progress timeout gave up. Now, once a target has taken
// EnvironmentImpactLimit such hits within EnvironmentImpactWindowSec, combat
// stops attacking it and does what the player chose for that kind of combat:
// move closer, pick another target, or move closer once and then pick another.
//
// The signals (CombatManager.EnvironmentImpact.cs):
// missile ACE ProjectileCollisionHelper.OnCollideEnvironment sends the shooter
// "Your missile attack hit the environment." (also when the arrow hits
// an object that isn't its target).
// magic ACE sends nothing (SpellProjectile.OnCollideEnvironment only
// explodes the projectile), so the bot follows its own projectiles and
// judges where they stopped (ProjectileImpactJudge).
//
// Everything here is pure (no host, no clock of its own) so the host tests can
// drive it directly.
// ============================================================================
/// <summary>What combat does once a target has taken too many environment hits.
/// Stored as an int in the settings (MissileEnvironmentResponse / MagicEnvironmentResponse).</summary>
public enum EnvironmentResponse
{
/// <summary>No detection; keep attacking (the behaviour before 2026-10-12).</summary>
Off = 0,
/// <summary>Move toward the target each time; once already close, pick another target.</summary>
MoveCloser = 1,
/// <summary>Skip the target for a while and pick another (moves closer when there is no other).</summary>
NewTarget = 2,
/// <summary>Move closer once; if the shots still hit the environment, pick another target.</summary>
CloserThenNewTarget = 3,
}
/// <summary>The step combat takes for one throttle trip.</summary>
public enum EnvironmentAction { None, Approach, NewTarget }
/// <summary>Choices and the decision for one throttle trip.</summary>
public static class EnvironmentImpactPlanner
{
/// <summary>Combo labels, in <see cref="EnvironmentResponse"/> order (plugin and engine settings panels).</summary>
public static readonly string[] ResponseNames =
{ "Off", "Move closer", "New target", "Move closer, then new target" };
/// <summary>Approaching is pointless within this much of the closest allowed distance.</summary>
public const double ApproachSlackMeters = 0.5;
/// <summary>A saved int as a response; anything out of range is Off.</summary>
public static EnvironmentResponse Parse(int value)
=> value is >= 0 and <= 3 ? (EnvironmentResponse)value : EnvironmentResponse.Off;
/// <summary>The label for a saved value (logs and the settings panels).</summary>
public static string Name(int value) => ResponseNames[(int)Parse(value)];
/// <summary>
/// The step for a throttle trip on a target <paramref name="distance"/> metres away that
/// has already been approached <paramref name="approachesDone"/> times for this reason.
/// Never approaches nearer than <paramref name="minDistance"/>. A new target needs another
/// monster in reach: skipping the only one would leave it free to hit the bot while combat
/// idles, so then the bot moves closer if it still can, or keeps attacking (None).
/// </summary>
public static EnvironmentAction Decide(EnvironmentResponse response, int approachesDone,
double distance, double minDistance, bool hasAlternateTarget)
{
bool canApproach = double.IsFinite(distance) && distance > minDistance + ApproachSlackMeters;
EnvironmentAction approachElseNone = canApproach ? EnvironmentAction.Approach : EnvironmentAction.None;
EnvironmentAction newTargetElse = hasAlternateTarget ? EnvironmentAction.NewTarget : approachElseNone;
return response switch
{
EnvironmentResponse.MoveCloser => canApproach ? EnvironmentAction.Approach : newTargetElse,
EnvironmentResponse.NewTarget => newTargetElse,
EnvironmentResponse.CloserThenNewTarget => approachesDone == 0 && canApproach
? EnvironmentAction.Approach : newTargetElse,
_ => EnvironmentAction.None,
};
}
/// <summary>
/// Where an approach stops: <paramref name="stepMeters"/> nearer than now, never nearer
/// than <paramref name="minDistance"/>.
/// </summary>
public static double ApproachGoal(double distance, double stepMeters, double minDistance)
=> Math.Max(Math.Max(0.5, minDistance), distance - Math.Max(1.0, stepMeters));
}
/// <summary>
/// Environment hits per target inside a sliding window, and how many times each target has
/// been approached for them. Pump thread only.
/// </summary>
public sealed class EnvironmentImpactThrottle
{
private readonly Dictionary<int, List<DateTime>> _hits = new();
private readonly Dictionary<int, int> _approaches = new();
// A long session meets thousands of monsters; ids are forgotten on delete, this is the backstop.
private const int MaxTracked = 256;
/// <summary>Records one hit on <paramref name="targetId"/> and returns the hits within the window.</summary>
public int Record(int targetId, DateTime now, double windowSec)
{
if (targetId == 0) return 0;
if (_hits.Count >= MaxTracked && !_hits.ContainsKey(targetId)) _hits.Clear();
if (!_hits.TryGetValue(targetId, out var list)) _hits[targetId] = list = new List<DateTime>(4);
list.Add(now);
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Hits on <paramref name="targetId"/> within the window (no new hit).</summary>
public int Count(int targetId, DateTime now, double windowSec)
{
if (!_hits.TryGetValue(targetId, out var list)) return 0;
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Starts the count again (after the bot acted on it).</summary>
public void ResetHits(int targetId) => _hits.Remove(targetId);
public int Approaches(int targetId) => _approaches.TryGetValue(targetId, out int n) ? n : 0;
public void NoteApproach(int targetId)
{
if (_approaches.Count >= MaxTracked && !_approaches.ContainsKey(targetId)) _approaches.Clear();
_approaches[targetId] = Approaches(targetId) + 1;
}
/// <summary>The object is gone (deleted): a respawn reusing the id starts clean.</summary>
public void Forget(int targetId)
{
_hits.Remove(targetId);
_approaches.Remove(targetId);
}
public void Clear()
{
_hits.Clear();
_approaches.Clear();
}
private static void Prune(List<DateTime> list, DateTime now, double windowSec)
{
double window = Math.Max(1.0, windowSec);
list.RemoveAll(t => (now - t).TotalSeconds > window);
}
}
/// <summary>
/// Where a spell projectile stopped, against where the target is. A projectile that reaches
/// the target stops at its surface; one that hits the environment stops short of it, toward
/// the caster. Both conditions must hold, so a large monster (its surface a few metres from its
/// centre) isn't read as a wall. The caller also requires that no hit, resist or evade line
/// arrived for the cast: that is the final word for a large monster or an odd stop.
/// </summary>
public static class ProjectileImpactJudge
{
/// <summary>A stop farther than this from the target's centre didn't touch it.</summary>
public const double MissRadiusMeters = 4.0;
/// <summary>A stop at least this much nearer to the caster than the target is "short".</summary>
public const double ShortByMeters = 2.0;
/// <summary>A projectile that flew less than this never really left (or was never ours).</summary>
public const double MinTravelMeters = 1.0;
/// <summary>True when the projectile stopped short of the target and away from it.</summary>
public static bool StoppedShort(double impactToTarget, double casterToImpact, double casterToTarget)
{
if (!double.IsFinite(impactToTarget) || !double.IsFinite(casterToImpact) || !double.IsFinite(casterToTarget))
return false;
return impactToTarget > MissRadiusMeters && casterToImpact + ShortByMeters < casterToTarget;
}
}

View file

@ -309,6 +309,9 @@ public class FellowshipTracker : IDisposable
return IsReadablePointer(fel) ? fel : IntPtr.Zero;
}
/// <summary>Drops the refresh throttle: the next read re-walks the client's member table (RynthOracle's Refresh button).</summary>
public void Invalidate() => _lastRefresh = DateTime.MinValue;
private void RefreshIfNeeded()
{
if ((DateTime.Now - _lastRefresh).TotalMilliseconds < REFRESH_INTERVAL_MS) return;

View file

@ -0,0 +1,79 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster kite / pull-away (2026-10-16): MonsterRule.Kite.
//
// Default the DEFAULT line's choice; on the DEFAULT line, Off (fight in place)
// Off engage and kill where the mob stands
// PullAway after a brief tag, run away until the mob has been pulled
// KitePullMeters from its lock-spot origin, then kill it alone
//
// Resolution matches AttackPowerModes: a rule's own value wins; "Default" falls
// through to the DEFAULT row; blank/unknown is Default (→ Off via the DEFAULT row).
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.Kite"/>.</summary>
public static class KiteModes
{
public const string Default = "Default";
public const string Off = "Off";
public const string PullAway = "PullAway";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, Off, PullAway };
/// <summary>Combo labels (plugin Advanced + engine Monsters/Damage panels).</summary>
public static readonly string[] DisplayNames = { "Default", "Off", "Pull away" };
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed / UI spellings: "Pull away", "pull-away", "Kite".
string squeezed = v.Replace(" ", "").Replace("-", "").Replace("_", "");
if (squeezed.Equals("PullAway", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Kite", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Pull", StringComparison.OrdinalIgnoreCase))
return PullAway;
if (squeezed.Equals("None", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Disabled", StringComparison.OrdinalIgnoreCase))
return Off;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's.
/// On the DEFAULT line, Default resolves to Off (safe: no pull until the player opts in).
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.Kite);
if (own != Default) return own;
// The DEFAULT row itself: Default means Off.
if (rule != null && defaultRule != null
&& ReferenceEquals(rule, defaultRule))
return Off;
if (rule != null && string.Equals(rule.Name, "Default", StringComparison.OrdinalIgnoreCase))
return Off;
string fromDefault = Normalize(defaultRule?.Kite);
return fromDefault == Default ? Off : fromDefault;
}
/// <summary>True when combat should pull this monster before finishing it.</summary>
public static bool WantsPullAway(MonsterRule? rule, MonsterRule? defaultRule)
=> Effective(rule, defaultRule) == PullAway;
/// <summary>Label for logs and tooltips.</summary>
public static string Name(string? value) => Normalize(value) switch
{
PullAway => "Pull away",
Off => "Off",
_ => "Default",
};
}

View file

@ -54,6 +54,17 @@ public class MissileCraftingManager
private const int EQUIP_DELAY_MS = 500;
private const int ERROR_BACKOFF_MS = 60000;
// An ammo wield the server ignores (ammo that doesn't fit the launcher really in hand) came
// round again every AMMO_CHECK_INTERVAL_MS, and each try stopped nav while it waited for the
// answer: Silentkelpie stood still ~3.5 s of every 5 on 2026-10-15. The same item sent more
// than MAX_EQUIP_REPEATS times inside EQUIP_REPEAT_WINDOW_MS backs off instead.
private const int EQUIP_REPEAT_WINDOW_MS = 30000;
private const int MAX_EQUIP_REPEATS = 2;
private const int EQUIP_IGNORED_BACKOFF_MS = 120000;
private int _lastEquipSentId;
private DateTime _lastEquipSentAt = DateTime.MinValue;
private int _equipRepeats;
private int _headBundleId = 0;
private int _shaftBundleId = 0;
private AmmoRecipe? _currentRecipe = null;
@ -145,13 +156,15 @@ public class MissileCraftingManager
_lastAmmoCheck = DateTime.Now;
var inv = GetInventory(forceRefresh: true);
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category))
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out WorldObject? launcher))
return;
_lastWeaponCategory = category;
if (HasWieldedAmmo(inv, category))
return;
_host.Log($"[RynthAi] MissileCraft: no {GetCategoryLabel(category)} wielded with launcher " +
$"0x{launcher!.Id:X8} '{launcher.Name}' (slot {launcher.WieldedLocation}); evaluating");
ChatLog($"No wielded {GetCategoryLabel(category)}s. Evaluating...");
SetState(CraftState.Evaluating);
}
@ -350,6 +363,18 @@ public class MissileCraftingManager
if (targetId != 0)
{
if (!NoteEquipSent(targetId))
{
string name = inv.FirstOrDefault(i => i.Id == targetId)?.Name ?? $"0x{targetId:X8}";
string why = $"The server didn't wield {name} after {MAX_EQUIP_REPEATS} tries; " +
$"leaving the ammo alone for {EQUIP_IGNORED_BACKOFF_MS / 60000} minutes";
_host.Log($"[RynthAi] MissileCraft: {why} (0x{targetId:X8})");
Reset(why);
_equipRepeats = 0;
_lastAmmoCheck = DateTime.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
return;
}
_host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo");
ChatLog($"Equipped ammo (id=0x{targetId:X8})");
Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}");
@ -382,9 +407,9 @@ public class MissileCraftingManager
private List<WorldObject> GetInventory(bool forceRefresh = false)
=> _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new();
private WeaponCategory ResolveWeaponCategory(IEnumerable<WorldObject> inventory)
private WeaponCategory ResolveWeaponCategory(List<WorldObject> inventory)
{
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category))
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category, out _))
{
_lastWeaponCategory = category;
return category;
@ -393,24 +418,29 @@ public class MissileCraftingManager
return _lastWeaponCategory;
}
private bool TryGetWieldedMissileCategory(IEnumerable<WorldObject> inventory, out WeaponCategory category)
private bool TryGetWieldedMissileCategory(List<WorldObject> inventory, out WeaponCategory category,
out WorldObject? launcher)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
// AC files ammo as a missile weapon: wielded quarrels must not pass for the launcher
// (no "crossbow" in the name reads as a bow, and arrows went on at the crossbow).
if (WorldObjectCache.IsAmmo(item) || !IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
continue;
category = GetWeaponCategory(item.Name);
launcher = item;
return true;
}
category = WeaponCategory.Bow;
launcher = null;
return false;
}
private bool HasWieldedAmmo(IEnumerable<WorldObject> inventory, WeaponCategory category)
private bool HasWieldedAmmo(List<WorldObject> inventory, WeaponCategory category)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item))
continue;
@ -422,16 +452,62 @@ public class MissileCraftingManager
return false;
}
/// <summary>
/// The direct scan plus the cache-known items it left out. The scan merges worn gear only when
/// its slot reads above 0, and the slot reads 0 for gear wielded after login (a launcher combat
/// swapped in, and its ammo), so the launcher really in hand was missing from the scan alone.
/// </summary>
private IEnumerable<WorldObject> WornCandidates(List<WorldObject> inventory)
{
foreach (var item in inventory)
yield return item;
if (_objectCache == null)
yield break;
var listed = new HashSet<int>(inventory.Select(i => i.Id));
foreach (var item in _objectCache.GetInventory())
if (listed.Add(item.Id))
yield return item;
}
private bool IsPlayerWielded(WorldObject item)
{
if (item.WieldedLocation <= 0)
// Found inside a pack by the direct scan: AC's container lists never hold worn gear. A
// launcher put away after a swap keeps its old wielder and slot in the client's object
// description, so the slot alone said a stowed bow was in hand while a crossbow was, and
// arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15).
if (item.DirectContainerId != 0)
return false;
uint playerId = _host.GetPlayerId();
if (playerId == 0)
return false;
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
if (item.WieldedLocation > 0)
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
// The slot reads 0 for gear wielded after login; the wielder still names the player.
return _host.HasGetObjectWielderInfo
&& _host.TryGetObjectWielderInfo(unchecked((uint)item.Id), out uint wielder, out _)
&& wielder == playerId;
}
/// <summary>
/// Counts an ammo wield about to go out; false once the same item was already sent
/// <see cref="MAX_EQUIP_REPEATS"/> times inside <see cref="EQUIP_REPEAT_WINDOW_MS"/>.
/// </summary>
private bool NoteEquipSent(int targetId)
{
DateTime now = DateTime.Now;
if (targetId == _lastEquipSentId && (now - _lastEquipSentAt).TotalMilliseconds < EQUIP_REPEAT_WINDOW_MS)
_equipRepeats++;
else
_equipRepeats = 1;
_lastEquipSentId = targetId;
_lastEquipSentAt = now;
return _equipRepeats <= MAX_EQUIP_REPEATS;
}
private static bool LooksLikeMissileWeapon(WorldObject item)

View file

@ -22,7 +22,8 @@ namespace RynthCore.Plugin.RynthAi;
/// Behaviour (per user spec):
/// * Summon only when mobs are near — at least <c>PetMinMonsters</c> scanned,
/// attackable monsters within <c>CustomPetRange</c> — and no pet is currently
/// active. Re-summon when the pet despawns mid-fight.
/// active. Re-summon when the pet despawns mid-fight (lifespan / death), after
/// the essence's retail ~45 s use cooldown (Summoning wiki / ACE PetDevice).
/// * Auto-refill an empty essence from an Encapsulated Spirit in inventory
/// (gated on <c>PetAutoRefill</c>).
///
@ -30,6 +31,12 @@ namespace RynthCore.Plugin.RynthAi;
/// guarded, one in-flight action at a time. Entirely plugin-side; the only AC
/// actions issued are <c>Host.UseObject</c> (summon) and <c>Host.UseObjectOn</c>
/// (refill), both selection-free.
///
/// Stuck/fail (Kelpie 2026-10-16): a Use that the server refused (cooldown, incline,
/// busy) never drops Structure and never spawns a pet. The old path still assumed a
/// pet for 10 s and parked the essence only 30 s — short of the 45 s item cooldown —
/// so the next try timed out again. Failed summons no longer assume a pet; every
/// Use parks the essence for <see cref="DeviceUseCooldownMs"/>.
/// </summary>
internal sealed class PetManager
{
@ -55,6 +62,7 @@ internal sealed class PetManager
// pet is active for at least this long, so we don't re-issue before the new
// pet's CreateObject lands in the cache. Name-detection takes over once it does.
private long _assumePetActiveUntil;
private bool _petSeenSinceSummon; // the pet has shown up in the cache during this assume window
// Devices that just failed (skill too low, timed out, empty with no spirit)
// get parked so we advance to the next configured essence instead of looping.
@ -76,8 +84,14 @@ internal sealed class PetManager
private const long ThinkIntervalMs = 1000;
private const long ActionTimeoutMs = 8000;
/// <summary>Hold after a confirmed summon until the pet lands in the landscape cache (kept at the base's 10 s).</summary>
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
/// <summary>
/// Retail / ACE PetDevice use cooldown (~45 s). Applies after every Use we fire — success
/// or fail — so we do not re-Use while the server still refuses the essence.
/// </summary>
private const long DeviceUseCooldownMs = 45_000;
private const long DeviceFailCooldownMs = 30_000; // a refill that timed out (a summon is parked from IssueSummon)
private const long DeviceNoSpiritCooldownMs = 15_000;
private const long ServerSaidFullTrustMs = 30 * 60_000;
private const long RefillWindowMs = 120_000; // two refills inside this and the
@ -140,7 +154,7 @@ internal sealed class PetManager
{
_summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
_objectCache[_activeDeviceId]?.Name ?? "");
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
AssumePetFor(now, AssumeActiveAfterSummonMs);
GoIdle();
}
}
@ -158,13 +172,27 @@ internal sealed class PetManager
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
if (_activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs;
// A summon that we simply couldn't confirm very likely DID work — assume
// a pet for a bit so we don't immediately re-issue into "already active".
if (_state == PetState.Summoning)
_assumePetActiveUntil = now + AssumeActiveAfterSummonMs;
bool summonConfirmed = _state == PetState.Summoning
&& (SummonLanded() || IsPetActive());
// Host.Log so FakeHost / in-game logs see it; RynthLog for the Pets category file.
string timeoutMsg =
$"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8})"
+ (summonConfirmed
? "; summon confirmed late."
: "; no charge drop / no pet — treating as failed Use.");
_host.Log(timeoutMsg);
RynthLog.Write(LogCat.Pets, timeoutMsg);
// Do NOT restart DeviceUseCooldownMs here — IssueSummon already parked the essence
// from the Use instant. Re-arming from timeout would wait ~53 s and leave gaps
// after a refused Use (Kelpie stuck/fail).
// Only assume a pet when the Use clearly landed; a failed Use must not block
// resummon after the cooldown (false assume + short park left gaps).
if (_state != PetState.Summoning && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs; // refill timeout: park as before
if (summonConfirmed)
AssumePetFor(now, AssumeActiveAfterSummonMs);
else if (_state == PetState.Summoning)
_assumePetActiveUntil = 0;
Reset();
return;
}
@ -186,7 +214,7 @@ internal sealed class PetManager
// "<pet> is already active" — a pet is up but our detection lagged. Back off.
if (text.Contains("is already active", StringComparison.OrdinalIgnoreCase))
{
_assumePetActiveUntil = NowMs + AssumeActiveAfterSummonMs;
AssumePetFor(NowMs, AssumeActiveAfterSummonMs);
GoIdle();
return;
}
@ -196,10 +224,15 @@ internal sealed class PetManager
{
_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)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
// Empty Use does not burn the retail 45 s spawn cooldown the way a real summon
// does; drop the Use park so the next think can refill (or re-try pyreal path).
if (_activeDeviceId != 0)
{
if (AllowSummonOnEmpty?.Invoke() == true)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
else
_deviceCooldownUntil.Remove(_activeDeviceId);
}
GoIdle();
return;
}
@ -223,15 +256,32 @@ internal sealed class PetManager
// ── Decision ───────────────────────────────────────────────────────────────
/// <summary>Treat a pet as out until <paramref name="now"/> + <paramref name="ms"/> (it may not be in the cache yet).</summary>
private void AssumePetFor(long now, long ms)
{
_assumePetActiveUntil = now + ms;
_petSeenSinceSummon = false;
}
private void TryBeginAction(long now)
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
if (IsPetActive())
// If the assume window is still open but the pet is gone (despawn / death), clear it
// so we can wait on the essence cooldown and resummon.
bool petOut = IsPetActive();
if (now < _assumePetActiveUntil)
{
if (petOut) { _petSeenSinceSummon = true; return; }
// The pet came and went (died / lifespan ended): don't wait out the window. A pet that has not
// landed in the cache yet keeps the window, or a second essence would be summoned beside it.
if (!_petSeenSinceSummon) return;
_assumePetActiveUntil = 0;
}
if (petOut)
{
// A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land.
if (YieldPetForCombat != null && MonstersNearby() && YieldPetForCombat())
_assumePetActiveUntil = now + 3000;
AssumePetFor(now, 3000);
return;
}
if (HoldSummons?.Invoke() == true) return;
@ -298,15 +348,18 @@ internal sealed class PetManager
private void IssueSummon(int deviceId, int charges)
{
// Don't fire the essence-use while a cast gesture is animating — AC
// refuses item use mid-gesture, which would burn the 8s timeout and a
// 30s device park for nothing. No state change; caller retries next tick.
// refuses item use mid-gesture, which would burn the 8s timeout and the
// 45 s essence cooldown for nothing. No state change; caller retries next tick.
if (!_host.CanCastNow) return;
long now = NowMs;
_state = PetState.Summoning;
_activeDeviceId = deviceId;
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_actionIssuedAt = now;
// Server starts the PetDevice cooldown on Use, whether the pet spawns or not.
_deviceCooldownUntil[deviceId] = now + DeviceUseCooldownMs;
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}); essence cooldown {DeviceUseCooldownMs / 1000}s.");
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}
@ -455,9 +508,12 @@ internal sealed class PetManager
foreach (var wo in _objectCache.GetLandscape())
{
if (wo == null) continue;
// Corpses keep the pet's name briefly; don't treat them as a live summon.
if (wo.ObjectClass == AcObjectClass.Corpse) continue;
string n = wo.Name;
if (!string.IsNullOrEmpty(n) && n.StartsWith(prefix, StringComparison.Ordinal))
return true;
if (string.IsNullOrEmpty(n) || !n.StartsWith(prefix, StringComparison.Ordinal)) continue;
if (n.Contains("Corpse", StringComparison.OrdinalIgnoreCase)) continue;
return true;
}
return false;
}

View file

@ -74,12 +74,14 @@ internal sealed class WeaponElementTracker
if (id == 0 || IsIdentified(id)) continue;
int n = _requests.TryGetValue(id, out int c) ? c : 0;
if (n >= MaxRequestsPerItem) continue;
bool taken = false;
try { taken = _host.RequestId(unchecked((uint)id)); } catch { }
_lastRequestAt = now; // paces a retry as it paces a request
if (!taken) return 0; // the engine refused (a death or a portal): not counted, asked again after the gap
_requests[id] = n + 1;
_inFlightId = id;
_inFlightAt = now;
_lastRequestAt = now;
RequestsSent++;
try { _host.RequestId(unchecked((uint)id)); } catch { }
return id;
}
return 0;

View file

@ -66,7 +66,7 @@ internal static class WieldRequirements
private static AcSkillType? SkillOf(uint stype)
{
if (stype == 0) return null;
foreach (AcSkillType k in Enum.GetValues(typeof(AcSkillType)))
foreach (AcSkillType k in Enum.GetValues<AcSkillType>())
if (CharacterSkills.AcSkillTypeToSTypeSkill(k) == stype) return k;
return null;
}

View file

@ -406,6 +406,7 @@ internal static unsafe class CombatHookInterface
_table = null;
if (t != null) NativeMemory.Free(t);
CombatHook.Reset();
CombatHook.LastUseDone = null; // the lambda captured the host: don't keep a shut-down instance's host alive
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -48,6 +48,8 @@ public sealed partial class RynthAiPlugin
private int _corpseIdAcceptedThisTick;
private long _corpseIdBudgetAt; // when the budget last started over (a scan tick, or CorpseIdRefusedRetryMs without one)
private const long CorpseIdReaskMs = 3000; // no appraisal data this long after an accepted request: ask once more
private const int CorpseIdMaxReasks = 3; // ...at most this many times per corpse (each accepted ask raises the client's busy count and holds opens)
private readonly Dictionary<int, int> _corpseIdAskCount = new(); // accepted requests per corpse, the first included
private int _busyCount;
private long _busyCountLastIncrementAt;
private long _busyCountBecamePositiveAt; // when count first went 0→positive
@ -399,6 +401,7 @@ public sealed partial class RynthAiPlugin
_corpseIdRequested.Clear();
_corpseIdAskedAt.Clear();
_corpseIdRefusedAt.Clear();
_corpseIdAskCount.Clear();
}
if (_corpseSkipLogged.Count > 200)
_corpseSkipLogged.Clear();
@ -1017,8 +1020,11 @@ public sealed partial class RynthAiPlugin
/// requests, so a refused or dropped one is asked again. A refused one is retried every
/// CorpseIdRefusedRetryMs; an accepted one with no data is asked again every CorpseIdReaskMs, and only for
/// the corpse the bot is targeting or has open (any other corpse in range gets one accepted request, not a
/// stream). At most CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with
/// many uncached corpses in range does not burst. No give-up cap.
/// stream), at most CorpseIdMaxReasks times, and only while the loot mode needs the killer name (My Kills
/// Only, Fellowship Kills). All Corpses still gets the one first request (the radar colours own kills from
/// it) but never a stream of them; Recover My Corpse keeps its own 5 s ask (RequestOwnCorpseId). At most
/// CorpseIdPerTick requests are accepted per scan tick, so a refusal window ending with many uncached
/// corpses in range does not burst.
/// </summary>
private void TryRequestCorpseId(WorldObject corpse, string longDesc)
{
@ -1026,14 +1032,17 @@ public sealed partial class RynthAiPlugin
long idNow = ActionPacer.NowMs();
if (idNow - _corpseIdBudgetAt >= CorpseIdRefusedRetryMs) { _corpseIdAcceptedThisTick = 0; _corpseIdBudgetAt = idNow; } // evaluations outside a scan must not exhaust it for good
bool candidate = corpse.Id == _targetCorpseId || (_openedContainerId != 0 && corpse.Id == _openedContainerId);
int asks = _corpseIdAskCount.TryGetValue(corpse.Id, out int askCount) ? askCount : 0;
bool due = !_corpseIdRequested.Contains(corpse.Id)
|| (candidate && _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs);
|| (candidate && asks <= CorpseIdMaxReasks && CorpseNameNeeded()
&& _corpseIdAskedAt.TryGetValue(corpse.Id, out long askedAt) && idNow - askedAt >= CorpseIdReaskMs);
if (!due || _corpseIdAcceptedThisTick >= CorpseIdPerTick) return;
if (_corpseIdRefusedAt.TryGetValue(corpse.Id, out long refusedAt) && idNow - refusedAt < CorpseIdRefusedRetryMs) return;
if (Host.RequestId(unchecked((uint)corpse.Id)))
{
_corpseIdRequested.Add(corpse.Id);
_corpseIdAskedAt[corpse.Id] = idNow;
_corpseIdAskCount[corpse.Id] = asks + 1;
_corpseIdRefusedAt.Remove(corpse.Id);
_corpseIdAcceptedThisTick++;
}
@ -1043,6 +1052,9 @@ public sealed partial class RynthAiPlugin
}
}
/// <summary>The loot mode reads the killer name (My Kills Only, Fellowship Kills); All Corpses does not.</summary>
private bool CorpseNameNeeded() => (_dashboard?.Settings?.LootOwnership ?? 0) < 2;
private CorpseLootDecision EvaluateCorpseLootDecision(WorldObject? corpse)
{
var settings = _dashboard?.Settings;
@ -1915,6 +1927,10 @@ public sealed partial class RynthAiPlugin
}
private bool _pickupHeldLogged;
private long _pickupHoldTickAt; // CorpseNowMs of the previous held call; 0 = no hold running
/// <summary>A gap between two held calls longer than this was not one continuous hold (the corpse clock is not paid back for it).</summary>
internal const long PickupHoldMaxGapMs = 500;
/// <summary>
/// True while the server owes an answer to a cast or use (ActionPacer): ACE refuses a pickup
@ -1928,6 +1944,7 @@ public sealed partial class RynthAiPlugin
if (!ActionPacer.Outstanding(Host, out var pending) || pending == null)
{
_pickupHeldLogged = false;
_pickupHoldTickAt = 0;
return false;
}
if (!_pickupHeldLogged)
@ -1935,9 +1952,32 @@ public sealed partial class RynthAiPlugin
_pickupHeldLogged = true;
LootDiag($"[RynthAi] Corpse loot: pickup waits - the server still owes an answer to {ActionPacer.Describe(pending.Kind, pending.Label)} ({pending.Who}).");
}
PauseCorpseClockWhileHeld();
return true;
}
/// <summary>
/// The corpse's timeout clock does not run while a pickup is held for the server's answer to a
/// cast or use, as it does not for the buff / salvage-panel holds (FreezeCorpseTimeout). The hold
/// is bounded by the pacer: an action unanswered past its limit (ActionPacer.CastMaxMs for a
/// cast) stops being outstanding. FreezeCorpseTimeout itself cannot be used here: the
/// open-container branch of TickCorpseOpening resets its frozen age every tick, so this adds the
/// time since the previous held call to the claim time instead. Without it a corpse held for
/// 12 s timed out the moment the cast was answered, and AbandonCurrentCorpse gave the opened
/// corpse the 30-minute completed mark, which skipped its loot.
/// </summary>
private void PauseCorpseClockWhileHeld()
{
long now = CorpseNowMs;
long last = _pickupHoldTickAt;
_pickupHoldTickAt = now;
if (last == 0 || _targetCorpseId == 0 || _corpseTargetSince == 0)
return;
long gap = now - last;
if (gap > 0 && gap <= PickupHoldMaxGapMs)
_corpseTargetSince += gap;
}
private void TickPendingCorpsePickup(LegacyUiSettings settings)
{
if (_objectCache == null || _openedContainerId == 0 || _currentLootItemId == 0)
@ -3396,6 +3436,7 @@ public sealed partial class RynthAiPlugin
_corpseIdRequested.Remove(sid);
_corpseIdAskedAt.Remove(sid);
_corpseIdRefusedAt.Remove(sid);
_corpseIdAskCount.Remove(sid);
_corpseSkipLogged.Remove(sid);
_corpseWaitingSince.Remove(sid);
@ -3552,16 +3593,42 @@ public sealed partial class RynthAiPlugin
/// <summary>A held-back close is sent anyway when no other corpse has been opened this long.</summary>
internal const long DeferredCloseMaxMs = 3000;
/// <summary>Another corpse to loot is in range (the finished one is already marked completed).</summary>
/// <summary>
/// Another corpse to loot is in range (the finished one is already marked completed) and the
/// looter can go to it now: <see cref="CanClaimNextCorpse"/>. A corpse that combat, a full pack, a
/// refusing server or a buff / mana drain hold keeps from being claimed would leave the finished
/// one open for nothing (metas and Lua read the open container meanwhile).
/// </summary>
private bool OtherCorpseToLoot(int doneCorpseId)
{
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null) return false;
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
if (maxMeters <= 0.25) return false;
if (!CanClaimNextCorpse(settings, maxMeters)) return false;
return TryFindNearestCorpse(maxMeters, out WorldObject? next, out _) && next != null && next.Id != doneCorpseId;
}
/// <summary>
/// The holds TickCorpseOpening applies before it claims or opens a corpse, as one answer for
/// "would the next corpse be claimed now": looting blocked by a full pack (your own corpse
/// excepted), the use-refusal back-off, buffing, a mana drain, and combat's priority (the open
/// container no longer shields a claim once the finished corpse is released). What the activity
/// arbiter hands out later is not known here; the deferred close is sent after DeferredCloseMaxMs,
/// or as soon as one of these holds starts (TickDeferredClose). Distance is no reason to close
/// early: a far corpse is used at once and the server walks the character to it.
/// </summary>
private bool CanClaimNextCorpse(LegacyUiSettings settings, double maxMeters)
{
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters)) return false;
if (_useRefusals.HoldsOpens(CorpseNowMs)) return false;
if (string.Equals(settings.BotAction, "Buffing", StringComparison.OrdinalIgnoreCase)) return false;
if (_manaStoneManager?.HoldsLootForDrain() == true) return false;
if (settings.EnableCombat && _combatManager?.HasTargets == true && !settings.BoostLootPriority && !_lootStarveTurn)
return false;
return true;
}
/// <summary>Holds the close of a finished corpse back. Only when the engine can close it later and
/// reports which container the client has open (so the hold can see the server close it).</summary>
private bool DeferClose(int corpseId)
@ -3591,10 +3658,13 @@ public sealed partial class RynthAiPlugin
return;
}
bool stopped = !settings.IsMacroRunning || !settings.EnableLooting || settings.BoostNavPriority;
if (!stopped && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs)
// A hold that began after the close was deferred (a fight, a full pack) ends the wait too.
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
bool blocked = !stopped && maxMeters > 0.25 && !CanClaimNextCorpse(settings, maxMeters);
if (!stopped && !blocked && CorpseNowMs - _closeDeferredAt < DeferredCloseMaxMs)
return;
_closeDeferredFor = 0;
CloseCorpseContainer(id, stopped ? "completed; looting stopped" : "completed; no other corpse opened");
CloseCorpseContainer(id, stopped ? "completed; looting stopped" : blocked ? "completed; the next corpse can't be claimed now" : "completed; no other corpse opened");
}
private void CloseCorpseContainer(int corpseId, string why)

View file

@ -44,6 +44,7 @@ internal static unsafe class HubInterface
t->SessionStats = &SessionStats;
t->SessionReset = &SessionReset;
t->SessionStatsMore = &SessionStatsMore;
t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled;
t->Version = RynthAiHubApiV1.InterfaceVersion;
_table = t;
}
@ -250,6 +251,14 @@ internal static unsafe class HubInterface
catch { return 0; }
}
/// <summary>RynthAi's Vaulted Dungeons setting: RynthILT's keeper runs only while it is on (off by default).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int VaultedDungeonsEnabled()
{
try { return Plugin?.VaultedDungeonsEnabledForIlt == true ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SessionReset()
{

View file

@ -204,9 +204,10 @@ internal sealed class CombatHudTracker
if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return;
if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return;
// Counted only when the engine took it (it refuses around a death or a portal).
if (!_host.RequestId(uid)) return;
_appraiseAttempts++;
_lastAppraiseAt = now;
_host.RequestId(uid);
}
/// <summary>Polls the pet's health, then hands the server's health stream back to the fight target.</summary>

View file

@ -0,0 +1,27 @@
// MiniRemoteHeader.cs - the Mini Remote's [V/H] [Options] [gear] header row: what a click does, and the
// button widths. Pure, so the host tests check both offline.
//
// Options opens RynthAi Settings (Advanced Settings) through RynthCore's "/rc ui open Settings" when the
// host has a chat parser. The Mini Remote's own popup (sections, layout, slot size) opens from the small
// gear button next to it, from a right-click on Options, and from a left-click on Options when there is
// no chat parser to run the command.
namespace RynthCore.Plugin.RynthAi.Huds;
internal static class MiniRemoteHeader
{
/// <summary>[V/H]: one letter, so it doesn't need the width of the word buttons.</summary>
public const float LayoutButtonWidth = 56f;
public const float OptionsButtonWidth = 80f;
/// <summary>The gear button right of Options: square-ish and small.</summary>
public const float GearButtonWidth = 28f;
/// <summary>
/// The engine command a left-click on Options runs, or null when the host can't run chat commands
/// (then the click opens the Mini Remote popup instead).
/// </summary>
public static string? OptionsLeftClickCommand(bool hasChatParser) => hasChatParser ? MovedTabs.Settings : null;
/// <summary>Total width of the header row for the given spacing between its three buttons.</summary>
public static float RowWidth(float itemSpacing) =>
LayoutButtonWidth + OptionsButtonWidth + GearButtonWidth + 2f * itemSpacing;
}

View file

@ -12,7 +12,9 @@
// Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server
// has), then "Server: <name>", i.e. the installed server plugins' windows for the world you're on,
// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a
// server is forced) when none matches. The Options button holds the Mini Remote's own settings.
// server is forced) when none matches. The Options button opens RynthAi Settings (/rc ui open
// Settings); the small gear next to it, or a right-click on Options, holds the Mini Remote's own
// settings (sections, layout, slot size), and so does a click on Options when there is no chat parser.
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Remote sections (each can be hidden from the Options menu):
@ -59,8 +61,7 @@ internal sealed class MiniRemoteHud
/// <summary>Pixels per Ctrl+wheel notch over the slot grid.</summary>
private const float SlotSizeStep = 2f;
/// <summary>Narrowest horizontal-layout column (fits the stat lines and the translate row).</summary>
private const float MinColumnWidth = 190f;
private const float HeaderButtonWidth = 80f;
internal const float MinColumnWidth = 190f;
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
private static readonly Vector4 ColReady = new(0.40f, 0.95f, 0.45f, 1f);
@ -82,6 +83,8 @@ internal sealed class MiniRemoteHud
private bool _onRemoteTab = true;
// The Options button was clicked this frame (the popup opens at window level).
private bool _openOptions;
// The header's Options button was right-clicked this frame: its popup opens, not the remote's menu.
private bool _headerRightClick;
/// <summary>One tab after Remote: a universal one (drawn here) or RynthILT's.</summary>
private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool Ilt);
@ -125,7 +128,7 @@ internal sealed class MiniRemoteHud
// Right-click on the remote opens the Character / server menu, unless a slot's own menu is
// open (the ILT tabs have their own right-click menus).
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: false);
RenderMenu(s);
@ -152,7 +155,7 @@ internal sealed class MiniRemoteHud
// Without tabs (RynthCore's sections show them instead) the remote alone.
float width = RenderBody(s, _hud.Remote(), allowTabs: tabs && !InDrawer);
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: true);
RenderMenu(s);
@ -179,6 +182,7 @@ internal sealed class MiniRemoteHud
private float RenderBody(HudState s, MiniRemoteController? remote, bool allowTabs)
{
_onRemoteTab = true;
_headerRightClick = false;
_tabs.Clear();
if (allowTabs && remote != null)
{
@ -311,17 +315,54 @@ internal sealed class MiniRemoteHud
// ── Layout ──────────────────────────────────────────────────────────────
/// <summary>[V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.</summary>
/// <summary>
/// [V/H], [Options] and a small gear. Fixed widths (MiniRemoteHeader, sized to fit MinColumnWidth)
/// so the auto-resizing window can't grow from them.
/// </summary>
private void RenderHeaderRow(HudState s)
{
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(MiniRemoteHeader.LayoutButtonWidth, 0)))
s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
ImGui.SameLine();
// Opened by RenderOptions: this row sits inside the Remote tab, whose ID the popup must not get.
if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) _openOptions = true;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Mini Remote settings: sections, layout, slot size.\nRight-click the remote for the Character and server windows.");
// Left-click: RynthAi Settings (the engine's "Settings" panel); without a chat parser, and on a
// right-click, the Mini Remote popup (RenderOptions: this row sits inside the Remote tab, whose
// ID the popup must not get, so the popup opens at window level through _openOptions).
if (ImGui.Button("Options##mropts", new Vector2(MiniRemoteHeader.OptionsButtonWidth, 0)))
{
string? command = MiniRemoteHeader.OptionsLeftClickCommand(_hud.Host.HasInvokeChatParser);
if (command != null) _hud.RunEngineCommand(command);
else _openOptions = true;
}
if (ImGui.IsItemHovered())
{
_headerRightClick = true; // the remote's right-click menu stays closed over this button
if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) _openOptions = true;
SafeImGui.SetTooltip(_hud.Host.HasInvokeChatParser
? "Open RynthAi Settings (Advanced Settings).\nRight-click: Mini Remote sections, layout, slot size."
: "Mini Remote settings: sections, layout, slot size.");
}
ImGui.SameLine();
if (ImGui.Button("##mrgear", new Vector2(MiniRemoteHeader.GearButtonWidth, 0))) _openOptions = true;
DrawGear(ImGui.GetItemRectMin(), ImGui.GetItemRectMax());
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Mini Remote sections, layout, slot size");
}
/// <summary>A small gear (ring and eight teeth) centred in the button's rectangle, in the text colour.</summary>
private static void DrawGear(Vector2 min, Vector2 max)
{
var draw = ImGui.GetWindowDrawList();
uint col = ImGui.GetColorU32(ImGuiCol.Text);
Vector2 c = (min + max) * 0.5f;
float r = MathF.Min(max.X - min.X, max.Y - min.Y) * 0.22f;
draw.AddCircle(c, r, col, 12, 1.6f);
for (int i = 0; i < 8; i++)
{
float a = i * MathF.PI / 4f;
var dir = new Vector2(MathF.Cos(a), MathF.Sin(a));
draw.AddLine(c + dir * (r + 0.5f), c + dir * (r + 3f), col, 2f);
}
}
private void RenderVertical(HudState s, MiniRemoteController? remote)

View file

@ -21,6 +21,12 @@ internal static class MovedTabs
/// <summary>RynthCore Options > Diagnostics (the server picker; RynthCore 2026.10.5.54+).</summary>
public const string Diagnostics = "/rc diagnostics";
/// <summary>
/// RynthAi Settings (Advanced Settings): RynthCore's "Settings" panel (SettingsFace.Title), opened
/// by name through "/rc ui open &lt;Panel&gt;" (RynthCoreChatCommands, the generic panel verb).
/// </summary>
public const string Settings = "/rc ui open Settings";
/// <summary>
/// The chat command that opens where tab <paramref name="tab"/> lives now, or null when it is
/// still a Mini Remote tab (or not a tab at all). Case and padding don't matter.
@ -36,6 +42,7 @@ internal static class MovedTabs
{
OracleCharacter => "RynthOracle's Character tab",
Diagnostics => "RynthCore Options > Diagnostics",
Settings => "RynthAi Settings (Advanced Settings)",
_ => command,
};
}

View file

@ -71,6 +71,10 @@ internal static class SectionsManifest
["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."),
["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."),
["games"] = ("games", "Games", 100, "ILT games (RynthILT)."),
// Listed only while RynthILT shows the tab: the Vaulted Dungeons master switch (RynthAi
// Settings > Navigation) is on, on an ILT world.
["vaulted"] = ("nav", "Vaulted Dungeons", 220,
"Keep the character in one Vaulted Dungeon (RynthILT; Settings > Navigation > Vaulted Dungeons)."),
};
/// <summary>The surface name of a tab's view ("section:gear").</summary>

View file

@ -15,6 +15,30 @@ internal sealed class LegacyAdvancedSettingsUi
// Server Features list being edited (committed on Enter / focus loss); null = show the saved list.
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
/// <summary>
/// The environment-impact throttle's shared numbers (one set for missiles and magic), drawn
/// under each response combo. <paramref name="id"/> keeps the two copies' ImGui ids apart.
/// </summary>
private void DrawEnvironmentThrottleKnobs(string id)
{
ImGui.Indent();
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Hits to trip##envlimit{id}", ref _settings.EnvironmentImpactLimit, 1, 10);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Environment hits on one target, within the window, before combat reacts.\nShared by missiles and magic.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Window (s)##envwin{id}", ref _settings.EnvironmentImpactWindowSec, 5, 120);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Move closer by (m)##envstep{id}", ref _settings.EnvironmentApproachMeters, 1, 30);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Closest (m)##envmin{id}", ref _settings.EnvironmentMinDistance, 1, 30);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Never moves nearer than this. Already this close, a new target is picked instead.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Skip target (s)##envskip{id}", ref _settings.EnvironmentSkipSec, 5, 300);
ImGui.Unindent();
}
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private const string NavResumeNearestTip =
"On: starting the macro, loading a Circular or Linear route, and carrying on after a fight, loot, buff or door\n" +
@ -436,9 +460,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Spacing();
ImGui.Text("Give Queue");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 50, 2000);
ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minimum delay between each item sent by /ra givea commands.\nLower = faster but may drop items if the server can't keep up.");
ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first.");
break;
case "Recharge":
@ -532,6 +556,45 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length);
ImGui.Spacing();
ImGui.Text("Variable Power (monster rules)");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("A monster rule's Power column picks per monster: Default (these settings),\n" +
"High (100%), Reckless (80%, needs Recklessness trained), Variable (a new\n" +
"random power each attack in this range), or Reckless + Variable (random,\n" +
"kept inside the Recklessness band 20-80%).");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Min %", ref _settings.VariablePowerMin, 0, 100);
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Max %", ref _settings.VariablePowerMax, 0, 100);
ImGui.Spacing();
ImGui.Text("Missiles Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Missile Response", ref _settings.MissileEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When arrows or bolts keep hitting walls or objects instead of the target\n" +
"(\"Your missile attack hit the environment.\"), stop shooting and:\n" +
" Move closer - run toward the target for a clearer shot\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("missile");
ImGui.Spacing();
ImGui.Text("Pull Away (Kite)");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Pull Distance (m)", ref _settings.KitePullMeters, 3, 100);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When a monster rule's Kite is Pull away (or Default follows the\n" +
"DEFAULT row set to Pull away), tag the mob then run until it has\n" +
"been dragged this many metres from where it stood, then kill it.\n" +
"Set per mob on the Monsters / Damage panels.");
ImGui.Checkbox("Tag Before Fleeing", ref _settings.KiteTagFirst);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Land a hit before running so aggro sticks. Off = flee as soon as locked.");
ImGui.Spacing();
ImGui.Text("Weapon Swaps");
ImGui.SetNextItemWidth(150);
@ -600,7 +663,8 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip(
"At or under Emergency Heal At with heals failing: break the\n" +
"stuck cast with a jump and heal again; if that fails too,\n" +
"recall to the lifestone.");
"recall to the lifestone. Off by default; only a character that\n" +
"can heal (a heal spell, kit or potion) is ever recalled.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
@ -629,6 +693,20 @@ internal sealed class LegacyAdvancedSettingsUi
"The character turns to face the target first. 0 = no walls.");
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
ImGui.Spacing();
ImGui.Text("Spells Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Magic Response", ref _settings.MagicEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("When bolts, streaks, arcs or blasts keep stopping short of the target\n" +
"(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" +
" Move closer - run toward the target for a clearer line\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"Rings and walls aren't judged. The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("magic");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Spell Difficulty (Min Buffed Skill)");
@ -663,6 +741,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3).");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Ring Range", ref _settings.RingRange);
ImGui.Checkbox("Evade Handler Ring", ref _settings.HandlerRingEvade);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Empyrean Handler: when it channels its lethal ring and you are within 12 yards (or Ring Range if larger),\nback-jump away and re-engage. Acts only while the macro is running with combat on.");
ImGui.SetNextItemWidth(120);
ImGui.InputInt("Approach Range", ref _settings.ApproachRange);

View file

@ -69,8 +69,9 @@ internal sealed partial class LegacyDashboardRenderer
// 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 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");
// internal + settable only so the host tests can point LoadSettings at a scratch folder.
internal static string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
internal static 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);
@ -386,27 +387,43 @@ internal sealed partial class LegacyDashboardRenderer
// new character kept the previous character's weapons and consumables,
// and autosave then wrote them into its Default.json.
bool freshProfile = !File.Exists(_settingsFilePath);
bool holdUnreadable = false;
if (freshProfile)
{
CopySettings(new LegacyUiSettings(), _settings);
_lastSavedJson = string.Empty;
}
else if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string loadedJson, out string readError))
{
CopySettings(loaded!, _settings);
_lastSavedJson = loadedJson;
}
else if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _))
{
// The profile didn't read (cut off by a client that died mid-save, say): the copy
// kept by the last good save is used. The broken file is set aside and the backup put
// back as the profile, so the next save doesn't turn the broken file into the new .bak.
CopySettings(fromBak!, _settings);
_lastSavedJson = bakJson;
KeepUnreadableProfile(_settingsFilePath);
try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); }
catch (Exception ex) { _host.Log($"[RynthAi] Settings: putting the backup back as {_settingsFilePath} failed: {ex.Message}"); }
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}); loaded the backup instead.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}); restored the backup copy.", 1);
}
else
{
try
{
string json = File.ReadAllText(_settingsFilePath);
var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (loaded != null)
{
CopySettings(loaded, _settings);
_lastSavedJson = json;
}
}
catch { }
// Neither reads. Before, the defaults kept here were autosaved over the profile at once,
// so one bad read reset the character for good. Now a copy is set aside and nothing is
// written until a setting is actually changed (the baseline is re-taken below).
CopySettings(new LegacyUiSettings(), _settings);
KeepUnreadableProfile(_settingsFilePath);
holdUnreadable = true;
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}) and there's no good backup; using defaults without saving over it.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}). A copy was kept next to it (.unreadable); defaults are in use until you change something.", 1);
}
_packSetup = freshProfile ? PackSetup.FillNew
: _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting;
: holdUnreadable || _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting;
_packSetupStart = 0;
_packLastCount = -1;
@ -461,6 +478,15 @@ internal sealed partial class LegacyDashboardRenderer
// combat system has no fallback weapon/damage selection for unmatched mobs.
_settings.EnsureDefaultRule();
SetupMonsterWatcher();
if (holdUnreadable)
{
// The defaults now in memory (and the monster rules just loaded) are not a change: take
// them as the saved state, so the autosave leaves the unreadable file alone until the
// player changes something.
try { CaptureTransientUiState(); _lastSavedJson = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); }
catch { _lastSavedJson = string.Empty; }
}
}
/// <summary>
@ -505,9 +531,58 @@ internal sealed partial class LegacyDashboardRenderer
DataWriteGuard.TrySave("the settings profile", path, () =>
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, json);
// Written beside it and swapped in, the previous file kept as .bak: File.WriteAllText
// empties the profile first, so a client closed or killed mid-save (relaunching for a
// DXVK change, the launcher's stuck-client kill) left a cut-off file that then loaded
// as defaults.
string tmp = path + "." + Environment.ProcessId + ".tmp";
try
{
File.WriteAllText(tmp, json);
if (File.Exists(path)) File.Replace(tmp, path, path + BackupSuffix, ignoreMetadataErrors: true);
else File.Move(tmp, path);
}
finally
{
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
}
}, out reason, callerShows);
/// <summary>The last good profile kept by each save (profile path + this).</summary>
internal const string BackupSuffix = ".bak";
/// <summary>Reads and parses a settings profile; false (with the reason) when it's missing or doesn't parse.</summary>
private static bool TryReadProfile(string path, out LegacyUiSettings? settings, out string json, out string error)
{
settings = null; json = string.Empty; error = "";
try
{
if (!File.Exists(path)) { error = "missing"; return false; }
json = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(json)) { error = "the file is empty"; return false; }
settings = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (settings == null) { error = "the file holds no settings"; return false; }
return true;
}
catch (Exception ex)
{
error = ex.GetType().Name + ": " + ex.Message;
return false;
}
}
/// <summary>Copies a profile that didn't read to "&lt;name&gt;.unreadable-&lt;time&gt;" so its contents can be recovered.</summary>
private void KeepUnreadableProfile(string path)
{
try
{
if (!File.Exists(path)) return;
string copy = path + ".unreadable-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
File.Copy(path, copy, overwrite: false);
}
catch (Exception ex) { _host.Log($"[RynthAi] Settings: keeping a copy of {path} failed: {ex.Message}"); }
}
private static bool WriteSettingsFile(string path, string json) => WriteSettingsFile(path, json, out _);
/// <summary>After a failed autosave, when CheckAndSave may try again (not every tick).</summary>
@ -983,12 +1058,46 @@ internal sealed partial class LegacyDashboardRenderer
incoming.Insert(0, existingDefault ?? new MonsterRule { Name = "Default" });
}
// An engine without the Power column (before 2026-10-12) sends no AttackPower, which
// would reset every rule to Default: keep each rule's own (same name and expression).
if (json.IndexOf("\"AttackPower\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryAttackPower(_settings.MonsterRules, incoming);
// Same for kite (2026-10-16): an older Monsters panel omits Kite and would wipe PullAway.
if (json.IndexOf("\"Kite\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryKite(_settings.MonsterRules, incoming);
_settings.MonsterRules = incoming;
SaveMonstersFile();
}
catch { }
}
/// <summary>Copies AttackPower from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryAttackPower(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.AttackPower = old.AttackPower;
}
}
/// <summary>Copies Kite from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryKite(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.Kite = old.Kite;
}
}
// ── Settings bridge (engine-side Avalonia SettingsPanel) ─────────────────
public string BuildSettingsJson()
@ -1070,10 +1179,21 @@ internal sealed partial class LegacyDashboardRenderer
UseNativeAttack = s.UseNativeAttack,
SummonPets = s.SummonPets,
PetMinMonsters = s.PetMinMonsters,
// Spell Combat
VariablePowerMin = s.VariablePowerMin,
VariablePowerMax = s.VariablePowerMax,
MissileEnvironmentResponse = s.MissileEnvironmentResponse,
MagicEnvironmentResponse = s.MagicEnvironmentResponse,
EnvironmentImpactLimit = s.EnvironmentImpactLimit,
EnvironmentImpactWindowSec = s.EnvironmentImpactWindowSec,
EnvironmentApproachMeters = s.EnvironmentApproachMeters,
EnvironmentMinDistance = s.EnvironmentMinDistance,
EnvironmentSkipSec = s.EnvironmentSkipSec,
KitePullMeters = s.KitePullMeters,
KiteTagFirst = s.KiteTagFirst,
WeaponSwapSettleMs = s.WeaponSwapSettleMs,
WeaponSwapMinHealthPct = s.WeaponSwapMinHealthPct,
WeaponSwapMinGainPct = s.WeaponSwapMinGainPct,
// Spell Combat
SpellCastIntervalMs = s.SpellCastIntervalMs,
AttackSpellIntervalMs = s.AttackSpellIntervalMs,
CastDispelSelf = s.CastDispelSelf,
@ -1101,6 +1221,7 @@ internal sealed partial class LegacyDashboardRenderer
CorpseApproachRangeMin = s.CorpseApproachRangeMin,
// Navigation
BoostNavPriority = s.BoostNavPriority,
EnableVaultedDungeons = s.EnableVaultedDungeons,
FollowNavMin = s.FollowNavMin,
NavRingThickness = s.NavRingThickness,
NavLineThickness = s.NavLineThickness,
@ -1110,6 +1231,8 @@ internal sealed partial class LegacyDashboardRenderer
NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode),
NavGuideLine = s.NavGuideLine,
NavResumeNearest = s.NavResumeNearest,
TrackBreadcrumbs = s.NavOverlay.TrackBreadcrumbs,
ShowRouteOverlay = s.NavOverlay.ShowRouteMarkers,
OpenDoors = s.OpenDoors,
OpenDoorRange = s.OpenDoorRange,
OpenDoorsOnPathOnly = s.OpenDoorsOnPathOnly,
@ -1311,10 +1434,22 @@ internal sealed partial class LegacyDashboardRenderer
s.UseNativeAttack = p.UseNativeAttack;
s.SummonPets = p.SummonPets;
s.PetMinMonsters = p.PetMinMonsters;
// Spell Combat
// Absent (an engine without these controls) = unchanged.
if (p.VariablePowerMin is int vpMin) s.VariablePowerMin = vpMin;
if (p.VariablePowerMax is int vpMax) s.VariablePowerMax = vpMax;
if (p.MissileEnvironmentResponse is int envMis) s.MissileEnvironmentResponse = envMis;
if (p.MagicEnvironmentResponse is int envMag) s.MagicEnvironmentResponse = envMag;
if (p.EnvironmentImpactLimit is int envLimit) s.EnvironmentImpactLimit = envLimit;
if (p.EnvironmentImpactWindowSec is int envWin) s.EnvironmentImpactWindowSec = envWin;
if (p.EnvironmentApproachMeters is int envStep) s.EnvironmentApproachMeters = envStep;
if (p.EnvironmentMinDistance is int envMinDist) s.EnvironmentMinDistance = envMinDist;
if (p.EnvironmentSkipSec is int envSkip) s.EnvironmentSkipSec = envSkip;
if (p.KitePullMeters is int kitePull) s.KitePullMeters = Math.Clamp(kitePull, 3, 100);
if (p.KiteTagFirst is bool kiteTag) s.KiteTagFirst = kiteTag;
if (p.WeaponSwapSettleMs is int wsSettle) s.WeaponSwapSettleMs = Math.Clamp(wsSettle, 0, 3000);
if (p.WeaponSwapMinHealthPct is int wsHealth) s.WeaponSwapMinHealthPct = Math.Clamp(wsHealth, 0, 100);
if (p.WeaponSwapMinGainPct is int wsGain) s.WeaponSwapMinGainPct = Math.Clamp(wsGain, 0, 200);
// Spell Combat
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
@ -1342,6 +1477,7 @@ internal sealed partial class LegacyDashboardRenderer
s.CorpseApproachRangeMin = p.CorpseApproachRangeMin;
// Navigation
s.BoostNavPriority = p.BoostNavPriority;
if (p.EnableVaultedDungeons is bool vaulted) s.EnableVaultedDungeons = vaulted; // absent = unchanged
s.FollowNavMin = p.FollowNavMin;
s.NavRingThickness = p.NavRingThickness;
s.NavLineThickness = p.NavLineThickness;
@ -1351,6 +1487,8 @@ internal sealed partial class LegacyDashboardRenderer
if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode);
if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine;
if (p.NavResumeNearest is bool resumeNearest) s.NavResumeNearest = resumeNearest; // absent = unchanged
if (p.TrackBreadcrumbs is bool crumbs) s.NavOverlay.TrackBreadcrumbs = crumbs; // absent = unchanged
if (p.ShowRouteOverlay is bool routeOverlay) s.NavOverlay.ShowRouteMarkers = routeOverlay;
s.OpenDoors = p.OpenDoors;
s.OpenDoorRange = p.OpenDoorRange;
if (p.OpenDoorsOnPathOnly is bool doorsOnPath) s.OpenDoorsOnPathOnly = doorsOnPath; // absent = unchanged
@ -1640,18 +1778,30 @@ internal sealed partial class LegacyDashboardRenderer
// Load from new profile file if it exists
if (File.Exists(_settingsFilePath))
{
try
if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string json, out string readError))
{
string json = File.ReadAllText(_settingsFilePath);
var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (loaded != null)
CopySettings(loaded!, _settings);
_settings.SelectedProfile = newProfile;
_lastSavedJson = json;
}
else
{
// Same as at login: the profile that didn't read is set aside (and the backup used
// when there is one) instead of being overwritten by the profile we just left.
KeepUnreadableProfile(_settingsFilePath);
if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _))
{
CopySettings(loaded, _settings);
CopySettings(fromBak!, _settings);
_settings.SelectedProfile = newProfile;
_lastSavedJson = json;
_lastSavedJson = bakJson;
try { File.Copy(_settingsFilePath + BackupSuffix, _settingsFilePath, overwrite: true); } catch { }
_host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); restored its backup copy.", 1);
}
else
{
_host.WriteToChat($"[RynthAi] Profile '{newProfile}' didn't read ({readError}); a copy was kept next to it (.unreadable). Your current settings are in use under that name.", 1);
}
}
catch { }
}
else
{
@ -1816,6 +1966,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3);
dst.TargetLock = tmp.TargetLock;
dst.RingRange = tmp.RingRange;
dst.HandlerRingEvade = tmp.HandlerRingEvade; // a profile saved before this setting loads it as on
dst.ApproachRange = tmp.ApproachRange;
dst.MinRingTargets = tmp.MinRingTargets;
dst.BlastRange = tmp.BlastRange;
@ -1838,6 +1989,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0);
dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0);
dst.BoostNavPriority = tmp.BoostNavPriority;
dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons;
dst.BoostLootPriority = tmp.BoostLootPriority;
dst.OpenDoors = tmp.OpenDoors;
dst.OpenDoorRange = tmp.OpenDoorRange;
@ -1867,6 +2019,17 @@ internal sealed partial class LegacyDashboardRenderer
dst.MeleeAttackPower = tmp.MeleeAttackPower;
dst.MissileAttackPower = tmp.MissileAttackPower;
dst.UseRecklessness = tmp.UseRecklessness;
dst.VariablePowerMin = tmp.VariablePowerMin;
dst.VariablePowerMax = tmp.VariablePowerMax;
dst.MissileEnvironmentResponse = tmp.MissileEnvironmentResponse;
dst.MagicEnvironmentResponse = tmp.MagicEnvironmentResponse;
dst.EnvironmentImpactLimit = tmp.EnvironmentImpactLimit;
dst.EnvironmentImpactWindowSec = tmp.EnvironmentImpactWindowSec;
dst.EnvironmentApproachMeters = tmp.EnvironmentApproachMeters;
dst.EnvironmentMinDistance = tmp.EnvironmentMinDistance;
dst.EnvironmentSkipSec = tmp.EnvironmentSkipSec;
dst.KitePullMeters = Math.Clamp(tmp.KitePullMeters, 3, 100);
dst.KiteTagFirst = tmp.KiteTagFirst;
dst.WeaponSwapSettleMs = Math.Clamp(tmp.WeaponSwapSettleMs, 0, 3000);
dst.WeaponSwapMinHealthPct = Math.Clamp(tmp.WeaponSwapMinHealthPct, 0, 100);
dst.WeaponSwapMinGainPct = Math.Clamp(tmp.WeaponSwapMinGainPct, 0, 200);

View file

@ -207,6 +207,10 @@ public sealed class LegacyUiSettings
// setting loads it as on.
public bool TargetLock = true;
public int RingRange = 5;
// Empyrean Handler lethal ring (CombatManager.HandleChatForRingEvade): when the Handler channels the
// ring and the character is inside its danger radius, back-jump away and re-engage. Only acts while
// the macro is running with combat on. On by default because it is gated that way.
public bool HandlerRingEvade = true;
public int ApproachRange = 4;
public int MinRingTargets = 4;
// Blast like a ring: with BlastRange > 0, a rule with Blast on casts a blast only when
@ -252,6 +256,13 @@ public sealed class LegacyUiSettings
public double CorpseApproachRangeMin = 2.0;
public bool BoostNavPriority;
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the MASTER switch of RynthILT's Vaulted Dungeons
/// keeper (Infinite Leaftide / ACECustom only). Off by default. RynthILT reads it through
/// "RynthAi.Hub" VaultedDungeonsEnabled; while it is off the keeper does nothing (no recalls,
/// no /rc quit, no tab). This is the one place the switch lives.
/// </summary>
public bool EnableVaultedDungeons;
public bool BoostLootPriority;
public bool OpenDoors;
public float OpenDoorRange = 5.0f;
@ -400,7 +411,7 @@ public sealed class LegacyUiSettings
/// </summary>
public List<string> MonsterNameBlacklist { get; set; } = new();
public int GiveQueueIntervalMs = 150;
public int GiveQueueIntervalMs = 0;
/// <summary>
/// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield").
@ -433,7 +444,7 @@ public sealed class LegacyUiSettings
/// breaker runs and the heal is tried again; when that fails too, recall to the lifestone.
/// Off: the breaker still runs, no recall.
/// </summary>
public bool HpFailsafeRecall = true;
public bool HpFailsafeRecall = false;
/// <summary>
/// Minimum delay between offensive (war/void) COMBAT spell casts, in ms.
@ -470,6 +481,41 @@ public sealed class LegacyUiSettings
public bool UseNativeAttack = false;
public bool UseRecklessness;
/// <summary>
/// The range a monster rule's "Variable" attack power picks from, in percent of the bar
/// (a new value every swing or shot). "Reckless + Variable" also stays inside the
/// Recklessness band (20-80%). See AttackPowerPlanner.
/// </summary>
public int VariablePowerMin = 50;
public int VariablePowerMax = 100;
// ── Environment hits (2026-10-12, Combat/EnvironmentImpact.cs) ─────────────
/// <summary>
/// What missile combat does once a target has taken EnvironmentImpactLimit "Your missile
/// attack hit the environment." within EnvironmentImpactWindowSec: an EnvironmentResponse
/// (0 Off, 1 Move closer, 2 New target, 3 Move closer then new target). Off by default.
/// </summary>
public int MissileEnvironmentResponse;
/// <summary>The same for war/void casts whose projectiles stop short of the target. Off by default.</summary>
public int MagicEnvironmentResponse;
/// <summary>Environment hits on one target, within the window, that trip the response.</summary>
public int EnvironmentImpactLimit = 2;
/// <summary>The window (seconds) the hits are counted in.</summary>
public int EnvironmentImpactWindowSec = 20;
/// <summary>How far (metres) each "move closer" goes toward the target.</summary>
public int EnvironmentApproachMeters = 6;
/// <summary>Never approaches nearer than this (metres); already this close, a new target is picked.</summary>
public int EnvironmentMinDistance = 3;
/// <summary>How long (seconds) a target left for its environment hits is skipped.</summary>
public int EnvironmentSkipSec = 30;
/// <summary>
/// Pull-away kite (2026-10-16, Combat/KiteModes.cs): how far (metres) to drag a PullAway
/// monster from its lock-spot origin before stopping to kill it. Per-mob on/off is
/// MonsterRule.Kite (Default follows the DEFAULT row).
/// </summary>
public int KitePullMeters = 20;
/// <summary>Land a hit before fleeing so aggro sticks (Off = run immediately).</summary>
public bool KiteTagFirst = true;
/// <summary>
/// Combat and buffing only ever wield weapons from the Items list. With this on (the
/// default), a character whose Items list has no wand at all may still buff and cast with a
/// caster from its pack (by object class, never by name). Any listed wand turns it off.
@ -819,6 +865,13 @@ public sealed class MonsterRule
/// <summary>Debuffs the player typed in (Damage panel), comma separated: a spell's base
/// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is.</summary>
public string CustomDebuffs { get; set; } = "";
/// <summary>Melee/missile attack power against the monsters this rule covers: one of
/// AttackPowerModes.All. "Default" = the DEFAULT line's choice (on the DEFAULT line: the global
/// Melee/Missile Power settings). Rules saved before 2026-10-12 load as Default.</summary>
public string AttackPower { get; set; } = AttackPowerModes.Default;
/// <summary>Combat pull-away for this rule: one of KiteModes.All. "Default" = the DEFAULT
/// line's choice (on the DEFAULT line: Off). Rules saved before 2026-10-16 load as Default.</summary>
public string Kite { get; set; } = "Default";
}
public sealed class BuffRule
@ -1061,7 +1114,20 @@ public sealed class SettingsBridgePayload
public bool UseNativeAttack { get; set; }
public bool SummonPets { get; set; }
public int PetMinMonsters { get; set; }
// Variable attack power and the environment-impact throttle (2026-10-12). Null = sent by an
// engine without these controls, which leaves the plugin's own values alone.
public int? VariablePowerMin { get; set; }
public int? VariablePowerMax { get; set; }
public int? MissileEnvironmentResponse { get; set; }
public int? MagicEnvironmentResponse { get; set; }
public int? EnvironmentImpactLimit { get; set; }
public int? EnvironmentImpactWindowSec { get; set; }
public int? EnvironmentApproachMeters { get; set; }
public int? EnvironmentMinDistance { get; set; }
public int? EnvironmentSkipSec { get; set; }
// Pull-away kite (2026-10-16). Null = sender without these controls; leave plugin values alone.
public int? KitePullMeters { get; set; }
public bool? KiteTagFirst { get; set; }
// Weapon swaps (only when the sender includes them).
public int? WeaponSwapSettleMs { get; set; }
public int? WeaponSwapMinHealthPct { get; set; }
@ -1101,6 +1167,11 @@ public sealed class SettingsBridgePayload
// Navigation
public bool BoostNavPriority { get; set; }
/// <summary>
/// Options > Navigation > Vaulted Dungeons: the keeper's master switch (off by default). Nullable:
/// an engine that predates the row omits it, and absent = unchanged (never switches it off or on).
/// </summary>
public bool? EnableVaultedDungeons { get; set; }
public float FollowNavMin { get; set; }
public float NavRingThickness { get; set; }
public float NavLineThickness { get; set; }
@ -1111,6 +1182,10 @@ public sealed class SettingsBridgePayload
public int NavLabelMode { get; set; } = -1;
public bool? NavGuideLine { get; set; }
public bool? NavResumeNearest { get; set; }
// NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's "Breadcrumbs" and "Route
// overlay" switches, also on Settings > Navigation. Null (an older engine) = unchanged.
public bool? TrackBreadcrumbs { get; set; }
public bool? ShowRouteOverlay { get; set; }
public bool OpenDoors { get; set; }
public float OpenDoorRange { get; set; }
public bool? OpenDoorsOnPathOnly { get; set; } // absent (an older profile or plugin) = unchanged

View file

@ -12,9 +12,11 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// AutoCram moves non-equipped loose items out of the player's main pack into
/// sub-packs so the main pack stays empty for new loot pickups.
///
/// AutoStack merges two partial stacks of the same item (arrows, components,
/// salvage, pyreals, etc.) by dropping the smaller one onto the larger one's
/// slot — the server auto-merges stackable same-type items at the same slot.
/// AutoStack merges two partial stacks of the same weenie (arrows, components,
/// pyreals, etc.) by dropping the smaller one onto the larger one's slot — the
/// server merges only same-WCID stackables. Groups by WCID (not display name). A
/// pair whose total is over MaxStackSize is still tried: the server fills the
/// target and leaves the rest in the source, which is progress, not a failure.
/// </summary>
public sealed class InventoryManager
{
@ -33,7 +35,7 @@ public sealed class InventoryManager
// engine return is enqueue-accepted, not moved-confirmed (AcMainThreadQueue
// gesture-defers a move up to ~250 ticks ≈ 4-8s), so success and failure are
// indistinguishable at the call site. We confirm on a LATER snapshot.
private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; }
private sealed class Pending { public DateTime EnqueuedAt; public int FromContainer; public int TargetCount; public int SourceCount; }
private sealed class Backoff { public DateTime NextRetry; public int Attempts; public DateTime LastTouched; }
private readonly Dictionary<int, Pending> _cramPending = new(); // item id -> in-flight move
private readonly Dictionary<int, Backoff> _cramBackoff = new(); // item id -> confirmed-fail backoff
@ -259,10 +261,12 @@ public sealed class InventoryManager
if (inPlayerScope) playerItems.Add(item);
}
// Group by name, keep only stackable items with >1 in the same group.
// Group by weenie class id (WCID), not display name. Same-name stacks that are
// different weenies (e.g. Coalesced Mana 42517 vs 42518) cannot merge — the server
// answers "not compatible for stacking" and AutoStack used to retry forever.
var groupList = playerItems
.Where(x => GetMaxStackSize(x) > 1)
.GroupBy(x => x.Name)
.GroupBy(StackGroupKey)
.Where(g => g.Count() > 1)
.ToList();
@ -308,7 +312,9 @@ public sealed class InventoryManager
if (_stackPending.TryGetValue(key, out var sp))
{
bool sourceGone = !inv.Any(x => x.Id == parts[si].Item.Id);
if (sourceGone)
// Past the max the server fills the target and the source survives smaller:
// that is a merge too, not a failure.
if (sourceGone || MergeProgressed(sp.TargetCount, sp.SourceCount, parts[ti].Count, parts[si].Count))
{
_stackPending.Remove(key);
_stackBackoff.Remove(key);
@ -350,7 +356,7 @@ public sealed class InventoryManager
// Enqueue accepted — record PENDING, confirm on a later snapshot. Do NOT
// add the pair-key on success (the old bug that poisoned good merges and
// starved multi-partial consolidation).
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId };
_stackPending[pairKey] = new Pending { EnqueuedAt = DateTime.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count };
return true; // one action per tick
}
@ -400,7 +406,24 @@ public sealed class InventoryManager
foreach (var k in dead) map.Remove(k);
}
// ── Stack-size lookup ─────────────────────────────────────────────────
// ── Stack-size / group-key lookup ─────────────────────────────────────
/// <summary>
/// AutoStack group key: the WCID when known (Decal Type / TryGetObjectWcid), else the name.
/// Name-only is a cold-start fallback; once a WCID is known, same-name stacks of different
/// weenies stay in separate groups.
/// </summary>
internal static string StackGroupKey(int wcid, string? name) => wcid > 0 ? "w:" + wcid : "n:" + (name ?? "");
private static string StackGroupKey(WorldObject item)
=> StackGroupKey(item.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0), item.Name);
/// <summary>
/// True when a merge we sent moved something: the target grew or the source shrank since it was
/// enqueued. Counts are read from the same snapshot, so a refused merge changes neither.
/// </summary>
internal static bool MergeProgressed(int targetBefore, int sourceBefore, int targetNow, int sourceNow)
=> targetBefore > 0 && sourceBefore > 0 && (targetNow > targetBefore || sourceNow < sourceBefore);
private static int GetMaxStackSize(WorldObject item)
{

View file

@ -184,7 +184,9 @@ internal sealed class LootEditorBridge
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
d.IncludeT11 = req.IncludeT11;
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
d.AttributesSupported = true;
// The checklist shows every attribute whatever the match, so the item is always read in full.
LootItemFacts? facts = Items.Facts(id, true, req.IncludeT11 || req.Choices != null);
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;
@ -211,9 +213,11 @@ internal sealed class LootEditorBridge
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
Choices = req.Choices,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire());
d.Match = (int)draft.Match;
d.Action = (int)draft.Action;
d.KeepCount = draft.KeepCount;

View file

@ -962,9 +962,9 @@ internal sealed class ManaStoneManager
if (!_host.HasRequestId) return false;
if (_host.HasHasAppraisalData && _host.HasAppraisalData(unchecked((uint)id))) return false;
if (_stoneIdRequestedAt.TryGetValue(id, out long at) && now - at < StoneIdRetryMs) return false;
if (!_host.RequestId(unchecked((uint)id))) return false; // refused (a death or a portal): asked again next pass, not in 5 minutes
_stoneIdRequestedAt[id] = now;
_host.Log($"[RynthAi] ManaStone: identifying stone 0x{(uint)id:X8} (its charge can't be read).");
_host.RequestId(unchecked((uint)id));
return true;
}
@ -1078,8 +1078,7 @@ internal sealed class ManaStoneManager
if (!requestedThisPass && _host.HasRequestId
&& (!_manaIdRequestedAt.TryGetValue(item.Id, out long at) || nowMs - at > 300_000))
{
_manaIdRequestedAt[item.Id] = nowMs;
_host.RequestId(unchecked((uint)item.Id));
if (_host.RequestId(unchecked((uint)item.Id))) _manaIdRequestedAt[item.Id] = nowMs; // a refused one is asked again next pass
requestedThisPass = true;
}
continue;
@ -1101,9 +1100,11 @@ internal sealed class ManaStoneManager
&& nowMs - _lastGearRefreshAt >= GearRefreshSpacingMs
&& (!_gearReadRefreshedAt.TryGetValue(item.Id, out long readAt) || nowMs - readAt >= GearRefreshMs))
{
_gearReadRefreshedAt[item.Id] = nowMs;
_lastGearRefreshAt = nowMs;
_host.RequestId(unchecked((uint)item.Id));
if (_host.RequestId(unchecked((uint)item.Id))) // a refused one is asked again next pass
{
_gearReadRefreshedAt[item.Id] = nowMs;
_lastGearRefreshAt = nowMs;
}
requestedThisPass = true;
}
}

View file

@ -3631,6 +3631,20 @@ internal sealed class ExpressionEngine
["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0),
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0),
// The range a monster rule's Variable attack power picks from (percent of the bar).
["VariablePowerMin"] = (() => I(s.VariablePowerMin), v => { if (int.TryParse(v, out int i)) s.VariablePowerMin = Math.Clamp(i, 0, 100); }),
["VariablePowerMax"] = (() => I(s.VariablePowerMax), v => { if (int.TryParse(v, out int i)) s.VariablePowerMax = Math.Clamp(i, 0, 100); }),
// Environment hits: 0 Off, 1 Move closer, 2 New target, 3 Move closer then new target.
["MissileEnvironmentResponse"] = (() => I(s.MissileEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MissileEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["MagicEnvironmentResponse"] = (() => I(s.MagicEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MagicEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["EnvironmentImpactLimit"] = (() => I(s.EnvironmentImpactLimit), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactLimit = Math.Clamp(i, 1, 10); }),
["EnvironmentImpactWindowSec"] = (() => I(s.EnvironmentImpactWindowSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactWindowSec = Math.Clamp(i, 5, 120); }),
["EnvironmentApproachMeters"] = (() => I(s.EnvironmentApproachMeters), v => { if (int.TryParse(v, out int i)) s.EnvironmentApproachMeters = Math.Clamp(i, 1, 30); }),
["EnvironmentMinDistance"] = (() => I(s.EnvironmentMinDistance), v => { if (int.TryParse(v, out int i)) s.EnvironmentMinDistance = Math.Clamp(i, 1, 30); }),
["EnvironmentSkipSec"] = (() => I(s.EnvironmentSkipSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentSkipSec = Math.Clamp(i, 5, 300); }),
// Pull-away kite (Combat/KiteModes.cs).
["KitePullMeters"] = (() => I(s.KitePullMeters), v => { if (int.TryParse(v, out int i)) s.KitePullMeters = Math.Clamp(i, 3, 100); }),
["KiteTagFirst"] = (() => B(s.KiteTagFirst), v => s.KiteTagFirst = ToDouble(v) != 0),
["WeaponSwapSettleMs"] = (() => I(s.WeaponSwapSettleMs), v => { if (int.TryParse(v, out int i)) s.WeaponSwapSettleMs = Math.Clamp(i, 0, 3000); }),
["WeaponSwapMinHealthPct"] = (() => I(s.WeaponSwapMinHealthPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinHealthPct = Math.Clamp(i, 0, 100); }),
["WeaponSwapMinGainPct"] = (() => I(s.WeaponSwapMinGainPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinGainPct = Math.Clamp(i, 0, 200); }),

View file

@ -119,6 +119,12 @@ public sealed class PetTabState
public bool KeepCosmeticOut;
/// <summary>Seconds to wait before re-summoning the cosmetic pet after it despawns.</summary>
public int CosmeticRespawnSeconds = 15;
// Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets).
/// <summary>When on, use the selected siphon lens on a nearby creature once it is weak enough.</summary>
public bool AutoCaptureEnabled;
/// <summary>Index into <see cref="PetCaptureRules.Lenses"/> (Flawed to Asheron).</summary>
public int CaptureLensIndex;
}
/// <summary>A user's choice of summon type for one essence (matched by name, case-insensitive).</summary>
@ -250,6 +256,7 @@ internal sealed class MiniRemoteStore
s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2);
s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6);
s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600);
s.Pet.CaptureLensIndex = Math.Clamp(s.Pet.CaptureLensIndex, 0, PetCaptureRules.Lenses.Length - 1);
s.Quests ??= new QuestsTabState();
s.Quests.QuestFilter ??= string.Empty;
s.Quests.QuestFavorites ??= new();

View file

@ -0,0 +1,164 @@
// PetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host).
//
// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when
// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with
// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens
// WCID table in PetGuideController.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated).</summary>
public readonly struct PetCaptureLens
{
public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate)
{
Name = name;
Wcid = wcid;
BypassesHealthGate = bypassesHealthGate;
}
public string Name { get; }
public uint Wcid { get; }
/// <summary>Asheron's (and Debug) lenses skip the 20% / 20 HP gate.</summary>
public bool BypassesHealthGate { get; }
}
/// <summary>
/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal.
/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20
/// (whichever comes first). Asheron's Lens skips that check.
/// </summary>
public static class PetCaptureRules
{
/// <summary>A lens targets the nearest attackable creature within this many meters.</summary>
public const float CaptureRangeM = 5.0f;
/// <summary>Siphon once at or below this fraction of max health…</summary>
public const float CaptureMaxHealthFraction = 0.20f;
/// <summary>…or below this many hit points (the gate is OR with the fraction).</summary>
public const int CaptureMaxHealthPoints = 20;
/// <summary>
/// Lenses the player can pick for auto-capture. Order is the combo index.
/// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate.
/// </summary>
public static readonly PetCaptureLens[] Lenses =
{
new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false),
new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false),
new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false),
new("Resonance Lens", 78780010, bypassesHealthGate: false),
new("Asheron's Lens", 78780012, bypassesHealthGate: true),
};
/// <summary>Combo labels for the Pets tab (same order as <see cref="Lenses"/>).</summary>
public static readonly string[] LensNames =
{
"Flawed", "Pristine", "Perfect", "Resonance", "Asheron's",
};
public static PetCaptureLens LensAt(int index)
{
int i = Math.Clamp(index, 0, Lenses.Length - 1);
return Lenses[i];
}
/// <summary>
/// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens.
/// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max
/// (then only the fraction half of the gate can fire).
/// </summary>
public static bool IsWeakEnough(uint currentHp, uint maxHp)
{
if (currentHp == 0) return false; // dead — server refuses
if (maxHp == 0) return false;
float pct = (float)currentHp / maxHp;
// Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise.
return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints;
}
/// <summary>Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false.</summary>
public static bool IsWeakEnoughRatio(float healthRatio)
{
if (healthRatio <= 0f || healthRatio > 1f) return false;
return healthRatio <= CaptureMaxHealthFraction;
}
/// <summary>True when this lens may be used given the creature's vitals (bypass lenses always, if alive).</summary>
public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp)
{
if (currentHp == 0) return false;
if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0;
return IsWeakEnough(currentHp, maxHp);
}
/// <summary>Distance gate: ACECustom CaptureRangeM.</summary>
public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM;
}
/// <summary>
/// A brake on the auto-capture loop. The Pets tab fires a lens every couple of seconds and only stops
/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of)
/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive
/// tries over all targets; both reset on a recognized success. Pure: the tests drive it.
/// </summary>
public sealed class PetCaptureThrottle
{
/// <summary>Lens uses on one creature, with no success in between, before it is left alone.</summary>
public const int MaxTriesPerTarget = 5;
/// <summary>How long a creature that used up its tries is left alone (ms).</summary>
public const long TargetBlockMs = 120_000;
/// <summary>Lens uses over all creatures with no success before auto-capture switches itself off.</summary>
public const int MaxTriesWithoutSuccess = 15;
private readonly Dictionary<int, int> _tries = new();
private readonly Dictionary<int, long> _blockedUntil = new();
private int _sinceSuccess;
/// <summary>Consecutive lens uses with no recognized success (all targets).</summary>
public int TriesWithoutSuccess => _sinceSuccess;
/// <summary>True when the backstop was hit: the caller should switch auto-capture off.</summary>
public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess;
/// <summary>False while this target is blocked (it used its tries) or the backstop is hit.</summary>
public bool MayAttempt(int targetId, long nowMs)
{
if (Exhausted) return false;
if (_blockedUntil.TryGetValue(targetId, out long until))
{
if (nowMs < until) return false;
_blockedUntil.Remove(targetId); // block served: a fresh set of tries
_tries.Remove(targetId);
}
return true;
}
/// <summary>Seconds left on this target's block, 0 when it is not blocked.</summary>
public long BlockedSecondsLeft(int targetId, long nowMs)
=> _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0;
/// <summary>Count a lens use on this target; blocks it once it reaches <see cref="MaxTriesPerTarget"/>.</summary>
public void RecordAttempt(int targetId, long nowMs)
{
_sinceSuccess++;
int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1;
_tries[targetId] = n;
if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs;
}
/// <summary>A recognized success reply: everything starts over.</summary>
public void RecordSuccess() => Reset();
public void Reset()
{
_tries.Clear();
_blockedUntil.Clear();
_sinceSuccess = 0;
}
}

View file

@ -23,6 +23,9 @@
// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty.
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the
// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's
// Lens skips the health gate). Resonance still needs a prior failed capture on the server.
// * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only).
// * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT
// offers it (an ILT world whose server hasn't reported pet breeding off). Its whole body is
@ -57,6 +60,17 @@ internal sealed class PetsTab
private long _lastHealThink;
private string _healStatus = "idle";
// Auto siphon-lens capture (ACECustom MonsterCapture).
private long _lastCaptureThink;
private long _captureCooldownUntil;
private volatile string _captureStatus = "off";
private const long CaptureThinkMs = 250;
private const long CaptureCooldownMs = 2500;
private const long CaptureFailBackoffMs = 8000;
// Hard cap on lens uses: the loop stops on reply strings we only guess at, so it is also bounded
// per creature and over all creatures (PetCaptureThrottle).
private readonly PetCaptureThrottle _captureThrottle = new();
// Roster snapshot (rebuilt on the pump thread, read by the render thread).
private volatile PetStats[] _pets = Array.Empty<PetStats>();
private long _lastPetScan;
@ -289,6 +303,11 @@ internal sealed class PetsTab
_lastHealThink = nowMs;
TickHealing(nowMs);
}
if (nowMs - _lastCaptureThink >= CaptureThinkMs)
{
_lastCaptureThink = nowMs;
TickCapture(nowMs);
}
if (nowMs - _lastPresenceThink >= 1000)
{
_lastPresenceThink = nowMs;
@ -334,9 +353,51 @@ internal sealed class PetsTab
EndHealCycle(MiniRemoteContext.NowMs, "heal landed");
}
}
// ACECustom MonsterCapture replies — back off after a refuse so we don't burn lenses.
if (S.AutoCaptureEnabled && text.Length > 0)
{
long now = MiniRemoteContext.NowMs;
if (PetCaptureLines.IsSuccess(text))
{
_captureStatus = "captured";
_captureThrottle.RecordSuccess();
_captureCooldownUntil = now + CaptureCooldownMs;
}
else if (ContainsAny(text,
"too strong",
"blind rage",
"cannot be siphoned",
"cannot be captured",
"No creatures nearby",
"already dead",
"already being captured",
"hasn't failed a capture",
"echo has faded",
"Failed to consume"))
{
_captureStatus = "refused: " + Truncate(text, 48);
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades"))
{
_captureStatus = "failed (creature may enrage)";
_captureCooldownUntil = now + CaptureFailBackoffMs;
}
}
return false;
}
private static bool ContainsAny(string text, params string[] parts)
{
foreach (string p in parts)
if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
private static string Truncate(string s, int max)
=> s.Length <= max ? s : s[..(max - 3)] + "...";
public void OnLogout()
{
_heal = HealState.Idle;
@ -345,6 +406,9 @@ internal sealed class PetsTab
_lastSummonEssenceId = 0;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = 0;
_captureCooldownUntil = 0;
_captureStatus = "off";
_captureThrottle.Reset();
}
// ── Healing pet ─────────────────────────────────────────────────────────
@ -415,6 +479,154 @@ internal sealed class PetsTab
// ── Active pet ──────────────────────────────────────────────────────────
// ── Auto siphon capture (ACECustom MonsterCapture) ───────────────────────
/// <summary>
/// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature
/// within 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it).
/// The server picks the nearest creature itself — we only fire when that nearest candidate is
/// already weak enough, so a full-health neighbour closer than the wounded target won't waste a lens.
/// </summary>
private void TickCapture(long now)
{
if (!S.AutoCaptureEnabled)
{
_captureStatus = "off";
return;
}
if (_ctx.Ilt.Loaded && _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture))
{
_captureStatus = "monster capture disabled on this server";
return;
}
if (now < _captureCooldownUntil)
{
long left = (_captureCooldownUntil - now + 999) / 1000;
if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal))
_captureStatus = $"waiting {left}s";
return;
}
if (_ctx.Inventory.IsBusy) { _captureStatus = "busy"; return; }
var lens = PetCaptureRules.LensAt(S.CaptureLensIndex);
var lensItem = _ctx.Inventory.FindByWcid(lens.Wcid);
if (lensItem == null)
{
_captureStatus = $"no {lens.Name} carried";
return;
}
if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp))
{
_captureStatus = "no attackable creature within 5 m";
return;
}
if (!PetCaptureRules.InRange(distM))
{
_captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)";
return;
}
if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp))
{
float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f;
_captureStatus = pct >= 0
? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)"
: $"{target!.Name}: health unknown";
return;
}
if (!_captureThrottle.MayAttempt(target!.Id, now))
{
_captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s";
return;
}
if (!_ctx.Inventory.Use(lensItem))
{
_captureStatus = "UseObject refused";
return;
}
_captureThrottle.RecordAttempt(target.Id, now);
if (_captureThrottle.Exhausted)
{
// Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them.
S.AutoCaptureEnabled = false;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off");
}
float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f;
_captureStatus = $"using {lens.Name} on {target!.Name} ({shown:0}% / {curHp} HP)";
_captureCooldownUntil = now + CaptureCooldownMs;
RynthLog.Write(LogCat.Pets,
$"[Pets] auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}");
}
/// <summary>
/// Nearest attackable landscape creature within capture range, with vitals from the host when
/// available else the cache health ratio (fraction-only gate).
/// </summary>
private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp)
{
best = null;
bestDist = double.MaxValue;
curHp = maxHp = 0;
var cache = _ctx.Inventory.Cache;
if (cache == null) return false;
uint playerId = _ctx.Inventory.PlayerId;
if (playerId == 0) return false;
int pid = unchecked((int)playerId);
string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty;
foreach (var wo in cache.GetLandscape())
{
if (wo == null || wo.Id == pid) continue;
if (wo.ObjectClass != AcObjectClass.Monster) continue;
if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue;
// Skip corpses / non-attackable when the host can tell.
if (_ctx.Host.HasObjectIsAttackable && !_ctx.Host.ObjectIsAttackable(unchecked((uint)wo.Id)))
continue;
double d = cache.Distance(pid, wo.Id);
if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue;
if (!TryReadCreatureVitals(wo.Id, cache, out uint c, out uint m))
continue;
if (c == 0) continue; // dead
best = wo;
bestDist = d;
curHp = c;
maxHp = m;
}
return best != null;
}
/// <summary>
/// Absolute vitals via TryGetTargetVitals when bound; else cache health ratio as a 0–1000 scale
/// so only the fraction half of ACECustom's gate can fire.
/// </summary>
private bool TryReadCreatureVitals(int id, WorldObjectCache cache, out uint cur, out uint max)
{
cur = max = 0;
if (_ctx.Host.HasGetTargetVitals
&& _ctx.Host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _)
&& mh > 0)
{
cur = h;
max = mh;
return true;
}
float ratio = cache.GetHealthRatio(id);
if (ratio < 0f) return false;
// Synthetic scale: ratio 0.20 → 200/1000 so IsWeakEnough's fraction half matches.
max = 1000;
cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000);
return true;
}
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
@ -764,12 +976,49 @@ internal sealed class PetsTab
{
ImGui.Separator();
RenderCharms();
ImGui.Separator();
RenderCapture();
}
ImGui.Separator();
RenderHealing();
_ctx.Ilt.RenderSection(RynthIltHub.SectionPetLogs);
}
/// <summary>ACECustom siphon-lens auto-capture (ILT only): enable + which lens to use.</summary>
private void RenderCapture()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Monster capture");
bool captureOff = _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture);
ImGui.BeginDisabled(captureOff);
bool en = S.AutoCaptureEnabled;
if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en))
{
S.AutoCaptureEnabled = en;
_captureThrottle.Reset();
}
if (ImGui.IsItemHovered())
{
SafeImGui.SetTooltip(
"Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" +
"at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" +
"the health gate. Resonance Lens still needs a prior failed capture on the server.\n" +
"Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" +
"or 15 lens uses in a row with no capture.");
}
ImGui.SameLine();
ImGui.SetNextItemWidth(120);
int lens = Math.Clamp(S.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1);
if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length))
S.CaptureLensIndex = lens;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack.");
ImGui.EndDisabled();
if (captureOff)
SafeImGui.TextDisabled("Monster capture is disabled on this server.");
else
SafeImGui.TextDisabled("Status: " + _captureStatus);
}
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
private void RenderRosterHeader(LegacyUiSettings settings)
{

View file

@ -1785,7 +1785,12 @@ internal sealed class NavigationEngine
return false;
}
_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'");
// A use the engine did not send (UseObject said no) is not a use: false lets the caller ask again.
if (!_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'"))
{
_host.Log($"Nav: UseObject portal '{target}' (0x{bestId:X8}) was not sent - will retry");
return false;
}
// Publish the resolved object so the marker renderer can draw a ring +
// line to the portal's real position (the waypoint coord is a placeholder).
_settings.ActivePortalObjId = (uint)bestId;

View file

@ -243,6 +243,8 @@ public static class VirindiTankProfileImporter
dst.OffhandId = src.OffhandId;
dst.PreferredAmmoItemId = src.PreferredAmmoItemId;
dst.PetDamage = src.PetDamage;
dst.AttackPower = src.AttackPower;
dst.Kite = src.Kite;
}
private static MonsterRule CloneMonsterRule(MonsterRule row) =>
@ -268,6 +270,8 @@ public static class VirindiTankProfileImporter
OffhandId = row.OffhandId,
PreferredAmmoItemId = row.PreferredAmmoItemId,
PetDamage = row.PetDamage,
AttackPower = row.AttackPower,
Kite = row.Kite,
PreferredDamage = row.PreferredDamage,
};

View file

@ -2246,11 +2246,7 @@ public sealed partial class RynthAiPlugin
case "cancel": HandleCancelForceBuff(); break;
case "skipped":
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready."); break; }
_buffManager.BuildDynamicBuffList(); // refresh the skip list
string summary = _buffManager.FilterSkipSummary();
ChatLine(summary.Length == 0
? "[RynthAi] Buff filter: nothing is being skipped."
: $"[RynthAi] Buff filter skips: {summary}");
_buffManager.RequestSkipReport(); // chat commands run on AC's thread; the pump builds the list and answers
break;
default:
ChatLine("[RynthAi] /ra buff force - recast every buff now, whatever time is left");
@ -2602,10 +2598,7 @@ public sealed partial class RynthAiPlugin
if (allItems)
{
foreach (var item in matches)
{
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
}
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack, whatever it reads at send time
ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}");
}
else if (countGiven)
@ -2626,8 +2619,8 @@ public sealed partial class RynthAiPlugin
}
if (gives.Count == 1)
{
GiveItem((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount,
Math.Max(1, gives[0].Item.Values(LongValueKey.StackCount, 1)));
// Through the queue: an NPC that takes one item per give needs the repeat-until-met loop.
EnqueueGive((uint)gives[0].Item.Id, (uint)target.Id, gives[0].Amount);
ChatLine($"[RynthAi] Giving {gives[0].Amount} x '{gives[0].Item.Name}' to {target.Name}");
}
else
@ -2707,8 +2700,7 @@ public sealed partial class RynthAiPlugin
if (IsGiveProfileExempt(item)) continue;
var (action, _) = Loot.LootEvaluator.Classify(nativeProfile, item, null);
if (action != RynthCore.Loot.LootAction.Keep) continue;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack
queued++;
}
}
@ -2723,8 +2715,7 @@ public sealed partial class RynthAiPlugin
foreach (var rule in vtProfile.Rules)
if (VTankLootEvaluator.Match(rule, item, lootCtx)) { matched = rule; break; }
if (matched == null || (matched.Action != VTankLootAction.Keep && matched.Action != VTankLootAction.KeepUpTo)) continue;
int stackSize = Math.Max(1, item.Values(LongValueKey.StackCount, 1));
EnqueueGive((uint)item.Id, (uint)target.Id, stackSize);
EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack
queued++;
}
}

View file

@ -159,6 +159,8 @@ public sealed partial class RynthAiPlugin
internal MiniRemote.MiniRemoteController? MiniRemoteForIlt => _miniRemote;
internal WorldObjectCache? ObjectCacheForIlt => _objectCache;
internal RynthCore.Plugin.Shared.SessionStatsTracker? SessionStatsForIlt => _sessionStats;
/// <summary>The Vaulted Dungeons master switch (Settings > Navigation); false before login.</summary>
internal bool VaultedDungeonsEnabledForIlt => _dashboard?.Settings.EnableVaultedDungeons == true;
/// <summary>Item Info window, created once settings exist.</summary>
private void EnsureItemInfoUi()

View file

@ -58,6 +58,19 @@ public sealed partial class RynthAiPlugin
/// </summary>
private bool _wasPortalingForPacer;
private bool _wasMacroForPacer;
/// <summary>
/// The macro is switched on (off to on, whoever did it): a UseDone that arrived while it was off, a
/// player's own refused action, is not news. Without this the pacer's observer took it for a fresh
/// 'too busy' answer at the first check and held every start for the probe wait (~1.5 s).
/// </summary>
private void NoteMacroForPacer(bool running)
{
if (running && !_wasMacroForPacer) RynthCore.Plugin.Shared.ActionPacer.NoteMacroStart();
_wasMacroForPacer = running;
}
/// <summary>Portal space starts: the server dropped what was open (no breaker on a teleport's gap).</summary>
private void NotePortalForPacer()
{

View file

@ -133,13 +133,54 @@ 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 int _giveInFlightStack, _giveInFlightTries;
private long _giveInFlightAt;
private const long GiveConfirmMs = 3000;
private const int GiveMaxTries = 2;
// Items still to hand over from the in-flight give (a whole stack = its size; each shrink lowers it).
private int _giveInFlightRemaining;
// The in-flight request is a genuine "give all" (amount 0 from the caller): the only kind that may go out as a plain,
// whole-object give when the stack count cannot be read. A re-send of it stays "all".
private bool _giveInFlightAll;
// True once the in-flight give has been sent more than once (a busy re-send or a no-answer re-send):
// an "Item not found!" then means an earlier send already landed.
private bool _giveInFlightResent;
private string _giveInFlightName = string.Empty;
private long _giveLastSendAt = long.MinValue;
// A busy refusal re-sends the same give after this long (up to GiveBusyGiveUpMs in total).
private const long GiveBusyRetryMs = 300;
private long _giveBusyRetryAt; // 0 = not waiting on a busy re-send
// Continuous busy waiting on one give: since when, how many busy answers, when the player was last told.
private long _giveBusySince, _giveBusyNoticeAt;
private int _giveBusyCount;
private const long GiveBusyNoticeMs = 10000;
// Busy waiting on one give is given up after this long in total: the item is skipped and counted.
private const long GiveBusyGiveUpMs = 60000;
// A stackable item whose stack count will not read: which item, since when. After GiveReadFailMs the
// give goes out anyway (an explicit amount, or a plain give for amount 1) so the queue always advances.
private uint _giveReadFailId;
private long _giveReadFailSince;
private const long GiveReadFailMs = 2000;
// Consecutive ticks the in-flight item read as unreadable (no cache entry, Container 0); 2 = gone.
private int _giveGoneStreak;
private int _giveUnclassified; // unclassified chat lines logged for this give (max 5)
// Chat verdict on the in-flight give, set by OnChatWindowText and read on the tick.
private enum GiveChat { None, Busy, Permanent, ItemNotFound }
private int _giveChatVerdict; // a GiveChat, handed from OnChatWindowText to the tick with Interlocked
private string _giveChatLine = string.Empty;
private bool _giveSawAcceptLine;
// A stack that shrank but is still carried goes again before anything else in the queue.
private (uint itemId, uint targetId, int remaining)? _giveRedo;
// Run summary (reset when the queue empties).
private bool _giveRunActive;
private long _giveRunStartAt, _giveRunLastAnswerAt;
private int _giveRunItems;
private readonly List<string> _giveRunSkips = new();
// Test seam: a fake millisecond clock.
private Func<long>? _giveClock;
private long GiveNow() => _giveClock?.Invoke() ?? Environment.TickCount64;
private RynthCore.Loot.LootProfile? _nativeLootProfile;
private string _nativeLootProfilePath = string.Empty;
private DateTime _nativeLootProfileTime = DateTime.MinValue;
@ -261,6 +302,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.UseAudit.WorldUseHold = null;
RynthCore.Plugin.Shared.ActionPacer.Enabled = false;
RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown");
CombatHook.LastUseDone = null; // captured this instance's host (set again at Init)
// 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
@ -450,6 +492,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_playerId = 0;
_loginComplete = false;
_pendingGives.Clear();
ResetGiveState();
// A /ub delay armed before logout must not fire into the next character's session.
_delayedCommands.Clear();
ClearPropertyDump();
@ -699,6 +742,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve
_combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
// Empyrean Handler lethal-ring: face the Handler, run-back jump (Jumper "xs"), re-engage.
// Read _jumper at call time — it is constructed later in this session setup.
_combatManager.RequestBackJump = (faceHeading, ms) => _jumper != null && _jumper.Start("xs", faceHeading, ms);
_combatManager.JumpBusy = () => _jumper?.IsBusy == true;
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
if (_buffManager != null)
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
@ -1015,7 +1062,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60),
["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000),
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (0, 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), ["RestamTo"] = (0, 100), ["GetManaAt"] = (0, 100),
@ -1023,6 +1070,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["VariablePowerMin"] = (0, 100), ["VariablePowerMax"] = (0, 100),
["MissileEnvironmentResponse"] = (0, 3), ["MagicEnvironmentResponse"] = (0, 3),
["EnvironmentImpactLimit"] = (1, 10), ["EnvironmentImpactWindowSec"] = (5, 120),
["EnvironmentApproachMeters"] = (1, 30), ["EnvironmentMinDistance"] = (1, 30), ["EnvironmentSkipSec"] = (5, 300),
["KitePullMeters"] = (3, 100),
["WeaponSwapSettleMs"] = (0, 3000), ["WeaponSwapMinHealthPct"] = (0, 100), ["WeaponSwapMinGainPct"] = (0, 200),
["PetMinMonsters"] = (1, 20),
["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
@ -1126,9 +1178,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
int id = unchecked((int)e.Id);
if (Host.HasRequestId && idRequests < 3
&& (!Host.HasHasAppraisalData || !Host.HasAppraisalData(e.Id))
&& _equipIdRequested.Add(e.Id))
&& !_equipIdRequested.Contains(e.Id))
{
Host.RequestId(e.Id); // appraisal 0xC9 lands in the engine cache; read it next pass
// Remembered only when the engine took it: it refuses around a death or a portal, and a refused
// request marked as done would never be asked again. Appraisal 0xC9 lands in the engine cache;
// read it next pass.
if (Host.RequestId(e.Id)) _equipIdRequested.Add(e.Id);
idRequests++;
}
var a = new EquipAppraisal { Name = e.Name, Id = e.Id, Slot = e.Slot };
@ -1652,7 +1707,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
RynthCore.Plugin.Shared.ActionPacer.NoteFrame();
// Stuck Cast Break, once per tick: the breaker runs for every subsystem's casts.
if (_dashboard?.Settings is { } paceSettings)
{
RynthCore.Plugin.Shared.ActionPacer.StuckCastMs = Math.Max(0, paceSettings.StuckCastBreakMs);
NoteMacroForPacer(paceSettings.IsMacroRunning);
}
NotePortalForPacer();
if (HoldForDeath())
return;
@ -2305,6 +2363,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
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}"); }
try { NoteGiveChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Give chat check failed: {ex.Message}"); }
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_salvageManager?.OnChatWindowText(text);
@ -2312,6 +2371,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager?.TraceCastChat(text, chatType);
_combatManager?.HandleChatForDebuffs(text);
_combatManager?.HandleChatForDamage(text, chatType);
_combatManager?.HandleChatForRingEvade(text, chatType);
_missileCraftingManager?.HandleChat(text);
_scrollLearner?.OnChat(text);
_metaManager?.HandleChat(text, chatType);
@ -2354,7 +2414,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
try { _combatManager?.OnObjectCreated(objectId); } catch { }
_sessionStats?.OnCreateObject(objectId);
try { _objectCache?.OnCreateObject(objectId); }
try
{
_objectCache?.OnCreateObject(objectId);
_combatManager?.OnEnvironmentObjectCreated(objectId); // spell projectiles for the environment-impact throttle
}
catch (Exception ex)
{
Host.Log($"[RynthAi] OnCreateObject EXCEPTION on id=0x{objectId:X8}: {ex.GetType().Name}: {ex.Message}");
@ -3397,75 +3461,353 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
internal void CancelGiveQueue()
{
int count = _pendingGives.Count;
var redo = _giveRedo;
int count = _pendingGives.Count + (redo.HasValue ? 1 : 0);
_pendingGives.Clear();
_giveInFlightId = 0;
ResetGiveState();
ChatLine(count > 0
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
: "[RynthAi] Give queue is already empty.");
}
/// <summary>Drops the in-flight give, the redo slot and the run summary (cancel, logout).</summary>
private void ResetGiveState()
{
_giveInFlightId = 0;
_giveRedo = null;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
_giveBusyCount = 0;
_giveGoneStreak = 0;
_giveReadFailId = 0;
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveRunActive = false;
_giveRunItems = 0;
_giveRunSkips.Clear();
}
/// <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.
/// Classifies a chat line as an answer to the in-flight give. Lowercase substrings: the client
/// renders WeenieError text from its own string table, so only the server's custom strings
/// ("Item not found!", "Target not found!", "Give amount not valid!") are exact.
/// </summary>
private static GiveChat ClassifyGiveChat(string text)
{
string t = text.ToLowerInvariant();
// Busy class first: "<npc> is too busy to accept gifts" must not read as "not accepting gifts".
if (t.Contains("too busy") || t.Contains("is busy right now")) return GiveChat.Busy;
if (t.Contains("item not found")) return GiveChat.ItemNotFound;
if (t.Contains("give amount not valid") || t.Contains("target not found")
|| t.Contains("doesn't want") || t.Contains("does not want")
|| t.Contains("not accepting gifts") || t.Contains("cowers from you"))
return GiveChat.Permanent;
return GiveChat.None;
}
/// <summary>
/// Speech, tells and emotes are other players' words, never the server's answer to a give. The text
/// shape is the real guard. Chat type 17 is the client's Spellcasting type (spell words, ours and
/// other casters': "chat type=17 ... says, "Zojak Ves""), which is never an answer either, so it is
/// skipped too; system notices such as "You give ..." arrive as 0.
/// </summary>
private static bool IsGiveChatSpeech(string text, int chatType)
{
if (chatType == 17) return true;
string t = text.ToLowerInvariant();
return t.Contains(" says, \"") || t.Contains(" tells you, \"") || t.Contains(" asks, \"")
|| t.Contains(" exclaims, \"") || t.Contains(" yells, \"") || t.Contains(" whispers, \"")
|| t.StartsWith("you say, ", StringComparison.Ordinal) || t.StartsWith("you tell ", StringComparison.Ordinal)
|| t.StartsWith("you whisper", StringComparison.Ordinal) || t.StartsWith("you exclaim", StringComparison.Ordinal)
|| t.StartsWith("you yell", StringComparison.Ordinal) || t.StartsWith("you ask", StringComparison.Ordinal);
}
/// <summary>
/// OnChatWindowText: only records the verdict; every send happens in DrainGiveQueue. The engine
/// dispatches chat from ProcessPendingActions and the plugin tick from TickAll, back to back in
/// one driver (EntryPoint.cs:1120-1122, ImGui/EngineFrameController.cs:461-467 in RynthCore-autoid),
/// so this is one thread in practice; the verdict still goes through Interlocked.
/// </summary>
private void NoteGiveChat(string text, int chatType = 0)
{
if (_giveInFlightId == 0) return;
if (IsGiveChatSpeech(text, chatType)) return;
if (text.StartsWith("You give ", StringComparison.Ordinal)) { _giveSawAcceptLine = true; return; }
var kind = ClassifyGiveChat(text);
if (kind == GiveChat.None)
{
// Types 1 (RynthAi's own lines), 7 (magic) and 17 (spell words) are never worth a slot.
if (_giveUnclassified < 10 && chatType != 1 && chatType != 7 && !text.StartsWith("[", StringComparison.Ordinal))
{
_giveUnclassified++;
Host.Log($"[Give] unclassified chat: type={chatType} '{text}'");
}
return;
}
// The first verdict noted for this give stands until the tick takes it.
if (Interlocked.CompareExchange(ref _giveChatVerdict, (int)kind, 0) == 0) _giveChatLine = text;
}
/// <summary>
/// One give at a time, answered before the next goes out (ACE cancels a move chain when a second
/// give arrives, and answers extras "too busy"). An answer is the item leaving the pack or its
/// stack shrinking: an NPC with a Give emote takes ONE item per give, so a shrunk stack goes
/// again at once, in the same tick. Busy refusals re-send after GiveBusyRetryMs, for up to GiveBusyGiveUpMs in total;
/// permanent refusals skip the stack. No answer at all in GiveConfirmMs re-sends, up to
/// GiveMaxTries, then skips. GiveQueueIntervalMs is only a minimum gap between two sends.
/// </summary>
private void DrainGiveQueue()
{
long now = Environment.TickCount64;
long now = GiveNow();
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 (!ResolveGiveInFlight(now)) return;
}
if (_pendingGives.Count == 0) return;
int intervalMs = _dashboard?.Settings.GiveQueueIntervalMs ?? 150;
if ((DateTime.UtcNow - _lastGiveAt).TotalMilliseconds < intervalMs) return;
var redo = _giveRedo;
if (!redo.HasValue && _pendingGives.Count == 0)
{
FinishGiveRun(now);
return;
}
int intervalMs = Math.Max(0, _dashboard?.Settings.GiveQueueIntervalMs ?? 0);
if (intervalMs > 0 && _giveLastSendAt != long.MinValue && now - _giveLastSendAt < intervalMs) return;
var (itemId, targetId, stackSize) = _pendingGives.Dequeue();
// The queued amount is what to hand over; GiveItem gives the whole object when it is
// the whole stack (amount 0) and uses AC's real give action, which an NPC accepts.
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;
uint itemId, targetId;
int amount;
if (redo.HasValue)
{
(itemId, targetId, amount) = redo.Value;
_giveRedo = null;
}
else
(itemId, targetId, amount) = _pendingGives.Dequeue();
if (!_giveRunActive)
{
_giveRunActive = true;
_giveRunStartAt = now;
_giveRunLastAnswerAt = now;
_giveRunItems = 0;
_giveRunSkips.Clear();
}
if (!SendGive(itemId, targetId, amount, 1, resent: false, now))
_giveRedo = (itemId, targetId, amount); // unreadable stack: first in line again next tick
}
/// <summary>The in-flight give went through: the item left the inventory, or part of its stack did.</summary>
private bool GiveLanded()
/// <summary>
/// Settles the in-flight give. Returns true when it is done (landed or skipped) and the tick may
/// send the next give now; false when the tick must stop (still waiting, or a re-send just went out).
/// </summary>
private bool ResolveGiveInFlight(long now)
{
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;
long sinceSend = now - _giveInFlightAt;
string tag = $"0x{_giveInFlightId:X8} '{_giveInFlightName}'";
// 1. Progress: the item left the pack, or its stack shrank. A failed read is "no information":
// the stack count reads -1 (never a clamped 1, which looked like a shrink of 99), and an
// unreadable object (no cache entry, Container 0) must read the same on two ticks in a row.
var wo = _objectCache?[unchecked((int)_giveInFlightId)];
// Where it is: in the pack (the player, or a pack the player carries), with the give target (gone),
// or somewhere we cannot place. A container that is neither the player nor the target and whose own
// container reads 0 is unreadable, not gone.
int cont = wo?.Container ?? 0;
bool readable = wo != null && cont != 0;
bool carried = false;
if (readable)
{
int playerInt = unchecked((int)_playerId);
if (cont == playerInt) carried = true;
else if (cont != unchecked((int)_giveInFlightTarget))
{
int outer = _objectCache?.GetContainerId(cont) ?? 0;
if (outer == 0) readable = false;
else carried = outer == playerInt;
}
}
int stackNow = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1;
bool gone;
if (readable && !carried) { gone = true; _giveGoneStreak = 0; }
else if (readable) { gone = false; _giveGoneStreak = 0; }
else
{
_giveGoneStreak++;
gone = _giveGoneStreak >= 2;
}
if (gone)
{
int given = Math.Max(1, Math.Min(_giveInFlightRemaining, _giveInFlightStack));
Host.Log($"[RynthAi] Give answer: gone {tag} +{given} item(s) after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})");
CompleteGiveStack(given, now);
return true;
}
if (carried && stackNow >= 0 && stackNow < _giveInFlightStack)
{
int delta = _giveInFlightStack - stackNow;
int remaining = _giveInFlightRemaining - delta;
Host.Log($"[RynthAi] Give answer: shrink {tag} {_giveInFlightStack}->{stackNow} after {sinceSend} ms (accept line seen: {_giveSawAcceptLine})");
_giveRunItems += delta;
_giveRunLastAnswerAt = now;
uint shrunkId = _giveInFlightId;
_giveInFlightId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
if (remaining > 0)
_giveRedo = (shrunkId, _giveInFlightTarget, remaining);
return true;
}
// 2. A chat verdict.
var chat = (GiveChat)Interlocked.Exchange(ref _giveChatVerdict, 0);
if (chat == GiveChat.ItemNotFound)
{
// "Item not found" after a re-send means the earlier send landed, but only if the pack agrees:
// gone (or unreadable) counts as given; still carried with the same stack is a plain skip.
if (_giveInFlightResent && !carried)
{
int given = Math.Max(1, _giveInFlightRemaining);
Host.Log($"[RynthAi] Give answer: item-not-found after a re-send, item gone, counted as given {tag} +{given} item(s) after {sinceSend} ms");
CompleteGiveStack(given, now);
return true;
}
Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms");
SkipGiveStack("item not found", tag, now);
return true;
}
if (chat == GiveChat.Permanent)
{
Host.Log($"[RynthAi] Give answer: permanent {tag} '{_giveChatLine}' after {sinceSend} ms");
SkipGiveStack("refused", tag, now);
return true;
}
if (chat == GiveChat.Busy)
{
_giveBusyCount++;
if (_giveBusySince == 0) { _giveBusySince = now; _giveBusyNoticeAt = now; }
if (now - _giveBusySince >= GiveBusyGiveUpMs)
{
// A target that stays busy (a player in a trade) would otherwise be re-sent, and answer
// "too busy" in the player's chat, every GiveBusyRetryMs for ever.
Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} for {now - _giveBusySince} ms; giving up");
string? busyWho = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name;
ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(busyWho) ? "the target" : busyWho)} stayed busy for {(now - _giveBusySince) / 1000} s - skipping 0x{_giveInFlightId:X8}.");
SkipGiveStack("busy too long", tag, now);
return true;
}
if (_giveBusyCount == 1 || _giveBusyCount % 10 == 0)
Host.Log($"[RynthAi] Give answer: busy #{_giveBusyCount} {tag} '{_giveChatLine}' after {sinceSend} ms; re-sending in {GiveBusyRetryMs} ms");
if (now - _giveBusyNoticeAt >= GiveBusyNoticeMs)
{
_giveBusyNoticeAt = now;
string? who = _objectCache?[unchecked((int)_giveInFlightTarget)]?.Name;
ChatLine($"[RynthAi] Give: {(string.IsNullOrEmpty(who) ? "the target" : who)} is busy - still retrying (/ra givea stop to cancel).");
}
_giveBusyRetryAt = now + GiveBusyRetryMs;
}
if (_giveBusyRetryAt != 0)
{
if (now < _giveBusyRetryAt) return false;
_giveBusyRetryAt = 0;
if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries, resent: true, now))
_giveBusyRetryAt = now; // unreadable stack: try again next tick
return false;
}
// 3. No answer at all.
if (sinceSend < GiveConfirmMs) return false;
if (_giveInFlightTries < GiveMaxTries)
{
Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; re-sending");
if (!SendGive(_giveInFlightId, _giveInFlightTarget, _giveInFlightAll ? 0 : _giveInFlightRemaining, _giveInFlightTries + 1, resent: true, now))
{
_giveInFlightTries++; // this was a try even though nothing went out: GiveMaxTries stays a cap on sends
_giveBusyRetryAt = now; // unreadable stack: try again next tick
}
return false;
}
Host.Log($"[RynthAi] Give answer: no-answer {tag} after {sinceSend} ms; giving up");
ChatLine($"[RynthAi] Give: the server didn't take 0x{_giveInFlightId:X8} - skipping it.");
SkipGiveStack("no answer", tag, now);
return true;
}
private void CompleteGiveStack(int items, long now)
{
_giveRunItems += items;
_giveRunLastAnswerAt = now;
_giveInFlightId = 0;
_giveReadFailId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
}
private void SkipGiveStack(string why, string tag, long now)
{
_giveRunSkips.Add($"{tag}: {why}");
Host.Log($"[RynthAi] Give skip: {tag} ({why})");
_giveRunLastAnswerAt = now;
_giveInFlightId = 0;
_giveReadFailId = 0;
_giveBusyRetryAt = 0;
_giveBusySince = 0;
}
/// <summary>
/// Sends one give and records it as the in-flight one. <paramref name="amount"/> is the items still to hand over;
/// 0 (or less) is a genuine "give all", the only request that may go out as a whole-object give when the stack
/// count cannot be read. An explicit amount, 1 included, always goes out as that explicit amount.
/// </summary>
private bool SendGive(uint itemId, uint targetId, int amount, int tries, bool resent, long now)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
int read = wo != null ? wo.Values(LongValueKey.StackCount, -1) : -1;
// A failed read on a stackable item (MaxStackSize above 1) is no information: nothing is sent this
// tick, and the caller tries again next tick. A read that keeps failing for GiveReadFailMs must not
// hold the queue for ever: then the give goes out anyway, as the explicit amount asked for (1 included:
// a "give 1" of a stack that is really 99 must not hand over all 99) or, for a genuine give-all, as a
// plain give, and says so in the log.
bool all = amount <= 0;
if (read < 0 && wo != null && wo.Values(LongValueKey.MaxStackSize, -1) > 1)
{
if (_giveReadFailId != itemId) { _giveReadFailId = itemId; _giveReadFailSince = now; }
if (now - _giveReadFailSince < GiveReadFailMs) return false;
Host.Log($"[RynthAi] Give: stack count of 0x{itemId:X8} '{wo.Name}' unreadable for {now - _giveReadFailSince} ms; sending anyway ({(all ? "plain give" : $"amount {amount}")})");
}
else _giveReadFailId = 0;
// Here a negative read means a non-stackable item, an unknown one, or a stackable whose count stayed
// unreadable: record max(1, amount) as its stack. An explicit amount is sent as that explicit amount
// (an explicit 1 is what the engine sends for a single item anyway); only a give-all goes out whole.
int whole = read >= 0 ? Math.Max(1, read) : Math.Max(1, amount);
string name = wo?.Name ?? string.Empty;
_giveInFlightId = itemId;
_giveInFlightTarget = targetId;
_giveInFlightRemaining = read < 0 ? Math.Max(1, amount) : (amount <= 0 || amount > whole ? whole : amount);
_giveInFlightStack = whole;
_giveInFlightAll = all;
_giveInFlightTries = tries;
_giveInFlightResent = resent;
_giveInFlightName = name;
_giveInFlightAt = now;
_giveLastSendAt = now;
Interlocked.Exchange(ref _giveChatVerdict, 0);
_giveSawAcceptLine = false;
_giveGoneStreak = 0;
if (!resent) { _giveBusyCount = 0; _giveBusySince = 0; _giveUnclassified = 0; }
GiveItem(itemId, targetId, amount, read >= 0 ? whole : (all ? 0 : amount + 1)); // amount + 1: GiveItem must not fold an explicit amount into a whole give
Host.Log($"[RynthAi] Give send: 0x{itemId:X8} '{name}' stack={(read >= 0 ? whole.ToString() : "?")} amount={amount} try={tries}{(resent ? " (re-send)" : string.Empty)}");
return true;
}
private void FinishGiveRun(long now)
{
if (!_giveRunActive) return;
_giveRunActive = false;
long elapsed = Math.Max(0, _giveRunLastAnswerAt - _giveRunStartAt);
string avg = _giveRunItems > 0 ? $"{elapsed / _giveRunItems} ms" : "n/a";
string why = _giveRunSkips.Count == 0 ? string.Empty : $" ({string.Join("; ", _giveRunSkips)})";
string line = $"[RynthAi] Give queue complete: {_giveRunItems} item(s) given, {_giveRunSkips.Count} stack(s) skipped{why}, {elapsed / 1000.0:0.0}s total, {avg} per give.";
Host.Log(line);
ChatLine(line);
_giveRunItems = 0;
_giveRunSkips.Clear();
}
/// <summary>

View file

@ -60,6 +60,8 @@
<Compile Include="..\Shared\ServerCommandPanel.cs" Link="Shared\ServerCommandPanel.cs" />
<!-- Mini Remote session stats: RynthTracker's code, so the two show the same numbers (2026-10-11). -->
<Compile Include="..\Shared\KillCounter.cs" Link="Shared\KillCounter.cs" />
<!-- The pet-capture success replies: the Pets tab's auto-capture and RynthILT's Vaulted Dungeons timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<Compile Include="..\Shared\TrackerSessionStore.cs" Link="Shared\TrackerSessionStore.cs" />
<Compile Include="..\Shared\SessionStats.cs" Link="Shared\SessionStats.cs" />
<Compile Include="..\Shared\SessionStatsTracker.cs" Link="Shared\SessionStatsTracker.cs" />

View file

@ -636,7 +636,7 @@ internal sealed class AutoTradeManager
{
_idState.TryGetValue(id, out var st);
if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue;
_host.RequestId(id);
if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick
_idState[id] = (st.Attempts + 1, now);
_lastIdSentAt = now;
break;

View file

@ -564,7 +564,7 @@ internal sealed class AutoVendorManager
{
_idState.TryGetValue(id, out var st);
if (st.Attempts > 0 && now - st.LastAt < IdResendMs) continue;
_host.RequestId(id);
if (!_host.RequestId(id)) break; // refused (a death or a portal): not an attempt, asked again next tick
_idState[id] = (st.Attempts + 1, now);
_lastIdSentAt = now;
break;

View file

@ -75,7 +75,7 @@ internal sealed class ChatBuffer
if (string.IsNullOrEmpty(text)) return;
string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items
: ChatClassifier.IsRynthOutput(text) ? ChatClassifier.Rynth
: ChatClassifier.ChannelFor(chatType);
: ChatClassifier.ChannelFor(text, chatType);
string? sender = ChatClassifier.SenderFor(text, chatType);
string ts = DateTime.Now.ToString("HH:mm:ss");

View file

@ -34,17 +34,46 @@ internal static class ChatClassifier
// ── Channel classification ─────────────────────────────────────────────
internal static string ChannelFor(int chatType) => (uint)chatType switch
/// <summary>
/// Channel tab for a line. Prefer the text's [General]/[Trade]/… tag when present —
/// ILT (and some ACE builds) deliver those as type 0x1C / 28 instead of 0x08/0x09, which
/// used to dump Trade/General into Other and leave the Channels tab empty.
/// </summary>
internal static string ChannelFor(string? text, int chatType)
{
if (IsChannelTagged(text)) return Channels;
return ChannelForType(chatType);
}
/// <summary>Legacy type-only map (tests / callers without the line text).</summary>
internal static string ChannelFor(int chatType) => ChannelForType(chatType);
internal static string ChannelForType(int chatType) => (uint)chatType switch
{
0x02 or 0x03 or 0x04 or 0x0A or 0x0B
or 0x0C or 0x12 or 0x13 => Chat,
0x08 or 0x09 => Channels,
0x08 or 0x09 or 0x1C => Channels,
0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18
or 0x19 or 0x1F => System,
0x06 or 0x07 or 0x11 or 0x15 or 0x16 => Combat,
_ => Other,
};
/// <summary>True when the line opens with a retail/ILT channel tag ([Trade], [General], …).</summary>
internal static bool IsChannelTagged(string? text)
{
if (string.IsNullOrEmpty(text) || text[0] != '[') return false;
return text.StartsWith("[General]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Trade]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[LFG]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Roleplay]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Society]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Celestial Hand]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Eldrytch Web]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Radiant Blood]", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase);
}
internal static uint ColorFor(string channel) => channel switch
{
Chat => 0xFFE0E0E0,

View file

@ -9,7 +9,7 @@
<RynthPluginServerName>DreamWeave</RynthPluginServerName>
<RynthPluginServerHosts>play.acdreamweave.com</RynthPluginServerHosts>
<RynthPluginServerWorldNames>DreamWeave|Dream Weave</RynthPluginServerWorldNames>
<RynthPluginDescription>DreamWeave only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
<RynthPluginDescription>DreamWeave only: the server card (rules, server features, player commands, links, account setup) in the Mini Remote.</RynthPluginDescription>
</PropertyGroup>
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />

View file

@ -1,4 +1,7 @@
// ServerData.cs - What is known about DreamWeave (RynthDreamWeave). Identity (id, hosts, world names) is in the csproj.
// The features and commands come from the server's public source (ACE-DreamWeave: its README and the
// player-level chat commands under Source/ACE.Server/Command/Handlers). Stock ACE commands and the
// stage-test-shard grants (/myxp, /mylum, ...) are left out.
namespace RynthCore.Plugin.ServerPack;
internal static class ServerData
@ -17,9 +20,57 @@ internal static class ServerData
"Lore driven, built on end-of-retail Throne of Destiny.",
"New class abilities and a new crafting system.",
"Its wiki is kept up to date.",
"Class abilities: trainers sell ability tokens for class ability points (/abilities, /cavoucher).",
"Equipment and weapon mods on armor, clothing and jewelry (/mods).",
"Facets: several builds per character, including a PK facet (/facet).",
"In-game bank for pyreals, luminance, legendary keys, promissory and trade notes (/bank).",
"Account vault (mule) with its own vendor, shared with characters you choose (/mule).",
"Player market: browse, list and buy items (/market).",
"Realms and ephemeral instances (/realm, /exitinst).",
"Drift Network: a hall of linked drift-doors, recalled to with /dn (/tn for the retail Town Network).",
"Threads dungeons (/dd) and treasure-map dig sites (/digsite, /rrtm).",
"PvP arenas (1v1, 2v2, Tugak Brawl free-for-all) and battlegrounds on templates, with ratings (/arena).",
"Leaderboards for DPS, defense, waves, speed, level, bank, stamps, threads and PvP (/top).",
"XP, luminance and custom augmentations (/aug).",
"Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).",
"Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).",
"Web character sheet you can publish (/charsheet).",
},
Commands = new[]
{
new ServerCommand("/bank", "deposit, withdraw, transfer and check banked currency (/b d deposits everything)"),
new ServerCommand("/mule", "summon your account vault's vendor, or manage who can use it"),
new ServerCommand("/market", "browse, list and buy items on the market"),
new ServerCommand("/abilities", "manage your class abilities"),
new ServerCommand("/cavoucher", "buy a class ability token for ability points, or refund an unused one"),
new ServerCommand("/facet", "show your facets; /facet <N> switches build, /facet pk the PK facet"),
new ServerCommand("/mods", "summarize the equipment mods on what you wear"),
new ServerCommand("/aug", "augmentation list: /aug xp, /aug lum or /aug custom"),
new ServerCommand("/dn", "recall to the Drift Network (moving too far interrupts it)"),
new ServerCommand("/tn", "recall to the retail Town Network"),
new ServerCommand("/realm", "which realm and instance you are in"),
new ServerCommand("/exitinst", "leave the current ephemeral instance"),
new ServerCommand("/dd", "Threads dungeon status"),
new ServerCommand("/digsite", "status of the dig site you are at; /digsite bail ends one you dug"),
new ServerCommand("/rrtm", "reroll a treasure map's dig site to the one nearest you"),
new ServerCommand("/arena", "PvP arena: /arena join 1v1|2v2|tugak|bg, templates, status, rating, top"),
new ServerCommand("/top", "leaderboards: dps, defense, wave, speed, level, bank, stamp, thread, 1v1, 2v2, tugak, bg"),
new ServerCommand("/xp", "your experience progress"),
new ServerCommand("/quests", "your quest stamp progress"),
new ServerCommand("/bonus", "every experience bonus you have and the total (/altbonus, /offlinebonus)"),
new ServerCommand("/lph", "luminance per hour since login, or since /lph start"),
new ServerCommand("/pickupspeed", "your pick-up speed bonus, including permanent quest bonuses"),
new ServerCommand("/fasttick", "fast tick on, off, default or status"),
new ServerCommand("/dotdamage", "show or hide your damage-over-time tick messages"),
new ServerCommand("/summondamage", "show or hide a chat line for each hit your pets land"),
new ServerCommand("/summonattackontarget", "pets switch to the monster you last hit (on or off)"),
new ServerCommand("/relaria", "Aun Relaria repeat-kill aura visual: /relaria aura on|off"),
new ServerCommand("/charsheet", "publish a web character sheet (off, rotate)"),
new ServerCommand("/fi", "resend nearby monsters and NPCs (invisible creatures), once a minute"),
},
Discord = "https://discord.gg/p2h3yca4BD",
Wiki = "https://wiki.acdreamweave.com",
Source = "public AC server list (acresources/serverslist), checked 2026-10-13",
Source = "public AC server list (acresources/serverslist), checked 2026-10-13; features and commands from " +
"github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14",
};
}

View file

@ -17,6 +17,11 @@
// refresh doesn't, so it has its own (client-side) spacing.
// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN
// when the Hub asked. Transfers always need a confirmation (UB had none).
// Backstop (SilentKelpie's PR 12, narrowed): the capture queue eats a quiet refresh's reply, but if
// it misses, balance-dump lines arriving within QuietBalanceWindowMs of a quiet refresh are eaten
// here. Only the dump itself (header and "Label: N" lines): other [BANK] lines (errors, bound-coin
// notes), Transferred / Received lines, and balance reads nobody here asked for (a macro's or another
// plugin's /bank, outside the window) are left alone.
using System;
using System.Collections.Generic;
using System.Linq;
@ -57,6 +62,10 @@ internal sealed class IltBanking : IIltFeature
private long _moveUntil;
/// <summary>How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read).</summary>
private const long MoveWindowMs = 12_000;
/// <summary>Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out).</summary>
private long _quietBalanceUntil;
/// <summary>How long after a quiet refresh is queued its leaked dump lines are still eaten here.</summary>
internal const long QuietBalanceWindowMs = 15_000;
// Render-thread form state.
private string _amountText = string.Empty;
@ -124,6 +133,7 @@ internal sealed class IltBanking : IIltFeature
long now = IltHubContext.NowMs;
if (now - _lastBalanceAt < BalanceSpacingMs) return;
_lastBalanceAt = now;
_quietBalanceUntil = quiet ? now + QuietBalanceWindowMs : 0;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/bank",
@ -293,8 +303,9 @@ internal sealed class IltBanking : IIltFeature
{
if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase))
{
ParseBalanceLine(text);
return false; // eating is decided by the capture queue
bool dump = ParseBalanceLine(text);
// Eating is decided by the capture queue; this only backs it up for a quiet refresh's dump.
return EatLeakedDump(dump, IltHubContext.NowMs, _quietBalanceUntil);
}
// A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves.
if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal))
@ -310,27 +321,67 @@ internal sealed class IltBanking : IIltFeature
// ── Parsing ─────────────────────────────────────────────────────────────
private void ParseBalanceLine(string text)
/// <summary>
/// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance
/// line (see <see cref="ParseBalanceLine"/>) and a quiet refresh was queued within the window.
/// </summary>
internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs)
=> isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs;
/// <summary>The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null.</summary>
internal static string? BalanceKeyFor(string label)
{
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) return "PrestigeCoins";
if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) return "WeaklyEnlightenedCoins";
if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) return "EnlightenedCoins";
if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) return "MythicalKeys";
if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) return "LegendaryKeys";
if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) return "Luminance";
if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return "Pyreals";
return null;
}
/// <summary>
/// True when a "[BANK] ..." line is part of the /bank balance dump: the "Your balances are:" header
/// or a "Label: N" line for a known currency. Errors, the bound-coin note and the like are not.
/// </summary>
internal static bool IsBalanceDumpLine(string text)
{
if (!text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) return false;
string body = text.Substring("[BANK]".Length).Trim();
if (body.StartsWith("Your balances", StringComparison.OrdinalIgnoreCase)) return true;
int colon = body.IndexOf(':');
if (colon <= 0) return false;
if (body.Substring(colon + 1).Trim().Length == 0) return true; // a header ending in a colon
return BalanceKeyFor(body.Substring(0, colon).Trim()) != null;
}
/// <summary>Reads a "[BANK] ..." line into the balances. Returns <see cref="IsBalanceDumpLine"/>.</summary>
private bool ParseBalanceLine(string text)
{
if (!IsBalanceDumpLine(text)) return false;
string body = text.Substring("[BANK]".Length).Trim();
int colon = body.IndexOf(':');
if (colon <= 0) return;
if (colon <= 0 || body.Substring(colon + 1).Trim().Length == 0) return true; // a header: nothing to read
string label = body.Substring(0, colon).Trim();
long value = IltParse.ParseLeadingLong(body.Substring(colon + 1));
if (body.Substring(colon + 1).Trim().Length == 0) return; // header "Your balances are:"
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) Apply("PrestigeCoins", ref Bank.PrestigeCoins, value);
else if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value);
else if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value);
else if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) Apply("MythicalKeys", ref Bank.MythicalKeys, value);
else if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) Apply("LegendaryKeys", ref Bank.LegendaryKeys, value);
else if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) Apply("Luminance", ref Bank.Luminance, value);
else if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) Apply("Pyreals", ref Bank.Pyreals, value);
else return;
switch (BalanceKeyFor(label))
{
case "PrestigeCoins": Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); break;
case "WeaklyEnlightenedCoins": Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); break;
case "EnlightenedCoins": Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); break;
case "MythicalKeys": Apply("MythicalKeys", ref Bank.MythicalKeys, value); break;
case "LegendaryKeys": Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); break;
case "Luminance": Apply("Luminance", ref Bank.Luminance, value); break;
case "Pyreals": Apply("Pyreals", ref Bank.Pyreals, value); break;
default: return false;
}
Bank.LastUpdated = DateTime.Now;
_ctx.Options.Set(IltFeature.Bank, IltTri.On);
return true;
}
private void Apply(string key, ref long field, long value)

View file

@ -1,19 +1,34 @@
// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time:
// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time. The rules follow ub-IT
// (Leaftide AetheriaChunkGuard / IsValidCorruptedWep / CorruptedChunkGuard):
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), no kept
// C / CD / CDR rating (gear ints 372 / 374 / 375; on by default), and max level
// (int 319, up to 10 on ILT) under the configured cap (Coalesced always qualifies).
// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179),
// not equipped, not never-chunk, cleave (292) <= 1.
// Peace mode only unless ChunkInCombat; waits for the result line (10 s max).
// never-chunk (bool 9030), not tinkered (171) or imbued (179), never levelled
// (ItemTotalXp quad 4 == 0), no kept C / CD / CDR rating (gear ints 372 / 374 / 375;
// on by default; only a rating at or above the "rating level" keeps, a lower one
// chunks), and max level (int 319, up to 10 on ILT) under the configured cap.
// A levelled Coalesced piece gets the cap too; an unlevelled one (319 = 0 after
// appraisal, normal for Coalesced) is chunkable, as in ub-IT. RynthILT used to keep
// every unlevelled Coalesced piece forever.
// Corrupted — "Corrupted" melee/missile weapons, not equipped, not never-chunk, no tinks (171),
// no imbue (179), loot-gen workmanship (105) > 0, and cleave (292) <= 1, or <= 2 on a
// two-handed weapon that is not a thrust weapon (RynthILT used to cap every weapon
// at 1, so no two-handed corrupted weapon was ever chunked). Optional keep rules
// (Crushing Blow, Biting Strike, Armor Cleaving, slayer, multi-strike, elemental
// bonus, any spell, max damage, spell ids) are all off by default.
// Peace mode only unless ChunkInCombat. With ChunkInCombat on, a busy client in combat mode no
// longer blocks the hammer (a swinging bot is always busy); peace mode still waits for idle.
// Waits for the result line (10 s max); a target that leaves the pack first counts as chunked
// (ILT does not always send a known line). Each item's skip reason is logged when it changes
// and tallied in the status line.
// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...)
// are loot and chunk nothing: the server answers with no result line, so every item timed out
// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15).
// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. Needs the
// AutoCraftingEnabled stamp; 30 min ± 2 min interval, first attempt ~1 min after enable.
// Clap: "/clap all" converts aetheria + trinkets into coins server-side: red (Coalesced level 1-3,
// chunks, powder) with Empyrean Trinkets, blue with Falatacot Trinkets. Auto-clap sends it only
// when a pair is carried. Needs the AutoCraftingEnabled stamp; 30 min ± 2 min interval, first
// attempt ~1 min after enable.
using System;
using System.Collections.Generic;
using System.Linq;
@ -53,6 +68,10 @@ internal sealed class IltChunkClap : IIltFeature
private bool _manualPass;
private volatile string _chunkStatus = "idle";
private int _chunked;
// Last skip reason per item, so each reason is logged once instead of every pass.
private readonly Dictionary<int, string> _lastSkip = new();
// Skip reasons of the current pass (reason -> items), shown in the status line.
private readonly Dictionary<string, int> _passSkips = new();
// Clap state
private long _nextClapAt;
@ -74,59 +93,264 @@ internal sealed class IltChunkClap : IIltFeature
private WorldObject? FindHammer()
=> _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo));
/// <summary>True/false when decidable; null when appraisal is still needed.</summary>
private bool? IsChunkableAetheria(WorldObject wo)
/// <summary>Item kinds the hammer works on (the name and class gate, before any appraisal).</summary>
internal enum ChunkKind { None, Aetheria, Corrupted }
/// <summary>
/// Which chunk rules an item falls under, by class and name only. Aetheria chunks and powder
/// are clap material, not hammer targets. Pure: the tests drive it.
/// </summary>
internal static ChunkKind KindOf(AcObjectClass cls, string name)
{
if (cls == AcObjectClass.Gem)
{
if (name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase)) return ChunkKind.Aetheria;
if (name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase)
&& !name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)
&& !name.Contains("Powder", StringComparison.OrdinalIgnoreCase))
return ChunkKind.Aetheria;
return ChunkKind.None;
}
if (cls is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon
&& name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase))
return ChunkKind.Corrupted;
return ChunkKind.None;
}
/// <summary>An aetheria piece's chunk facts, read after appraisal.</summary>
internal readonly record struct AetheriaFacts(
bool Coalesced, int MaxLevel, bool NeverChunk, long ItemXp, int Tinkers, int Imbue,
int Crit, int CritDamage, int CritDamageResist, string? Unreadable = null);
/// <summary>
/// Why an aetheria piece is kept, or null when it may be chunked (ub-IT AetheriaChunkGuard plus
/// RynthILT's C / CD / CDR keep switches). Pure: the tests drive it.
/// <para>
/// <see cref="AetheriaFacts.Unreadable"/> is set when the item's properties could not be read (the
/// host lacks a reader or the appraisal never arrived). A property that failed to read looks
/// exactly like one the item lacks (level 0, no XP, no tinks), so such a piece is kept: an
/// "unlevelled" Coalesced piece is only chunked when its level was truly read as none.
/// </para>
/// </summary>
internal static string? AetheriaSkip(IltGearState g, in AetheriaFacts f)
{
if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})";
if (f.NeverChunk) return "never-chunk flag";
if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued";
if (f.ItemXp != 0) return "has item XP";
if (KeptForRatings(g, f.Crit, f.CritDamage, f.CritDamageResist)) return "kept for its C / CD / CDR rating";
if (!UnderChunkCap(f.MaxLevel, g.ChunkAetheriaUnderLevel, f.Coalesced))
return f.MaxLevel > 0 ? "level at or above the cap" : "no level read";
return null;
}
/// <summary>Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing.</summary>
private string? AetheriaSkip(WorldObject wo)
{
if (wo.ObjectClass != AcObjectClass.Gem) return false;
bool coalesced = wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase);
if (!coalesced && (!wo.Name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) || wo.Name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)))
return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false;
if (KeptForRatings(G, inv.Int(wo, IltInventory.IntGearCrit), inv.Int(wo, IltInventory.IntGearCritDamage),
inv.Int(wo, IltInventory.IntGearCritDamageResist)))
return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < ClampUnderLevel(G.ChunkAetheriaUnderLevel);
if (inv.IsEquipped(wo)) return "equipped";
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; }
string? gap = inv.ReadGap(wo, quads: true);
var f = new AetheriaFacts(
Coalesced: wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase),
MaxLevel: inv.Int(wo, IltInventory.IntItemMaxLevel),
NeverChunk: inv.Bool(wo, IltInventory.BoolNeverChunk),
ItemXp: inv.Quad(wo, IltInventory.QuadItemTotalXp),
Tinkers: inv.Int(wo, IltInventory.IntNumTimesTinkered),
Imbue: inv.Int(wo, IltInventory.IntImbuedEffect),
Crit: inv.Int(wo, IltInventory.IntGearCrit),
CritDamage: inv.Int(wo, IltInventory.IntGearCritDamage),
CritDamageResist: inv.Int(wo, IltInventory.IntGearCritDamageResist),
Unreadable: gap);
return AetheriaSkip(G, f);
}
/// <summary>The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level).</summary>
internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1);
/// <summary>
/// True when an aetheria's C / CD / CDR rating is one the settings keep (any rating above 0 with
/// its keep switch on). Pure: the tests drive it.
/// True when an aetheria's max level (int 319) is under the cap. A levelled Coalesced piece
/// (ACECustom rolls 1-10; level 6+ can carry a rating) gets the same cap. Level 0 after
/// appraisal: an unlevelled Coalesced piece is chunkable (ub-IT: "ItemMaxLevel 0 after assess
/// is normal"); any other aetheria with no level is never chunked. Pure: the tests drive it.
/// </summary>
internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false)
=> maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0;
/// <summary>Highest rating level the keep threshold accepts.</summary>
internal const int MaxRatingLevel = 50;
/// <summary>The rating keep threshold in range: 1 (any rating keeps) to <see cref="MaxRatingLevel"/>.</summary>
internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel);
/// <summary>
/// True when an aetheria's C / CD / CDR rating is one the settings keep: its keep switch is on and
/// the rating is at or above the rating level (<see cref="IltGearState.KeepAetheriaRatingAtLeast"/>).
/// A rating below that level does not protect the piece, so e.g. a C 1 Coalesced Aetheria chunks
/// with the level at 2 while a C 2 one is kept. Pure: the tests drive it.
/// </summary>
internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist)
=> (g.KeepAetheriaWithCrit && crit > 0)
|| (g.KeepAetheriaWithCritDamage && critDamage > 0)
|| (g.KeepAetheriaWithCritDamageResist && critDamageResist > 0);
private bool? IsChunkableCorrupted(WorldObject wo)
{
if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false;
if (!wo.Name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Int(wo, IltInventory.IntNumTimesTinkered) != 0 || inv.Int(wo, IltInventory.IntImbuedEffect) != 0) return false;
return inv.Int(wo, IltInventory.IntCleaving) <= 1;
int min = ClampRatingLevel(g.KeepAetheriaRatingAtLeast);
return (g.KeepAetheriaWithCrit && crit >= min)
|| (g.KeepAetheriaWithCritDamage && critDamage >= min)
|| (g.KeepAetheriaWithCritDamageResist && critDamageResist >= min);
}
private WorldObject? NextChunkTarget()
private const string Appraising = "appraising";
private const int SkillTwoHandedCombat = 41;
private const int WeaponTypeTwoHanded = 11;
private const int AttackTypeThrust = 2;
/// <summary>A corrupted weapon's chunk facts, read after appraisal.</summary>
internal sealed record CorruptedFacts
{
foreach (var wo in _ctx.Inventory.Items())
public bool NeverChunk { get; init; }
public int Tinkers { get; init; }
public int Imbue { get; init; }
public int Workmanship { get; init; }
public int AttackType { get; init; }
public int Cleaving { get; init; }
public int WieldSkill { get; init; }
public int WeaponType { get; init; }
public double CritFrequency { get; init; }
public double CritMultiplier { get; init; }
public double IgnoreArmor { get; init; }
public int Slayer { get; init; }
public int ElementalBonus { get; init; }
public int MaxDamage { get; init; }
public IReadOnlyList<int> Spells { get; init; } = Array.Empty<int>();
/// <summary>What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable.</summary>
public string? Unreadable { get; init; }
}
/// <summary>
/// The most cleave a chunkable corrupted weapon may have (ub-IT IsValidCorruptedWep): 2 on a
/// two-handed weapon that is not a thrust weapon, 1 on everything else. Pure: the tests drive it.
/// </summary>
internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType)
=> (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1;
/// <summary>
/// Why a corrupted weapon is kept, or null when it may be chunked: ub-IT's hard rules, then its
/// IdleActs keep rules from the settings. Pure: the tests drive it.
/// </summary>
internal static string? CorruptedSkip(IltGearState g, CorruptedFacts f)
{
// A property that failed to read looks like one the weapon lacks (0), which would chunk it.
if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})";
// Hard rules (always on).
if (f.NeverChunk) return "never-chunk flag";
if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued";
if (f.Workmanship <= 0) return "no workmanship";
if (f.Cleaving > MaxChunkCleave(f.WieldSkill, f.WeaponType, f.AttackType)) return "cleave over the limit";
// Keep rules (each off by default).
if (g.KeepCorruptedCrushingBlow && f.CritFrequency > 0) return "kept: Crushing Blow";
if (g.KeepCorruptedBitingStrike && f.CritMultiplier > 0) return "kept: Biting Strike";
if (g.KeepCorruptedArmorCleaving && f.IgnoreArmor > 0) return "kept: Armor Cleaving";
if (g.KeepCorruptedAnySlayer && f.Slayer > 0) return "kept: slayer";
if (g.KeepCorruptedMultiStrike && f.AttackType is 160 or 166 or 486) return "kept: multi-strike";
if (g.KeepCorruptedElementalBonus && f.ElementalBonus > 0) return "kept: elemental bonus";
if (g.KeepCorruptedMaxDamageAtLeast > 0 && f.MaxDamage >= g.KeepCorruptedMaxDamageAtLeast) return "kept: max damage";
if (f.Spells.Count > 0)
{
if (_skip.Contains(wo.Id)) continue;
if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo;
if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo;
if (g.KeepCorruptedAnySpell) return "kept: has a spell";
var deny = ParseSpellIds(g.KeepCorruptedSpellIds);
if (deny.Count > 0 && f.Spells.Any(deny.Contains)) return "kept: listed spell";
}
return null;
}
/// <summary>Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it.</summary>
internal static HashSet<int> ParseSpellIds(string? csv)
{
var ids = new HashSet<int>();
if (string.IsNullOrWhiteSpace(csv)) return ids;
foreach (var part in csv.Split(new[] { ',', ';', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
if (int.TryParse(part, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int id) && id > 0)
ids.Add(id);
return ids;
}
/// <summary>Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing.</summary>
private string? CorruptedSkip(WorldObject wo)
{
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return "equipped";
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; }
bool needDoubles = G.KeepCorruptedCrushingBlow || G.KeepCorruptedBitingStrike || G.KeepCorruptedArmorCleaving;
bool needSpells = G.KeepCorruptedAnySpell || !string.IsNullOrWhiteSpace(G.KeepCorruptedSpellIds);
var f = new CorruptedFacts
{
Unreadable = inv.ReadGap(wo, doubles: needDoubles, spells: needSpells),
NeverChunk = inv.Bool(wo, IltInventory.BoolNeverChunk),
Tinkers = inv.Int(wo, IltInventory.IntNumTimesTinkered),
Imbue = inv.Int(wo, IltInventory.IntImbuedEffect),
Workmanship = inv.Int(wo, IltInventory.IntItemWorkmanship),
AttackType = inv.Int(wo, IltInventory.IntAttackType),
Cleaving = inv.Int(wo, IltInventory.IntCleaving),
WieldSkill = inv.Int(wo, IltInventory.IntWieldSkillType),
WeaponType = inv.Int(wo, IltInventory.IntWeaponType),
CritFrequency = inv.Double(wo, IltInventory.FloatCriticalFrequency),
CritMultiplier = inv.Double(wo, IltInventory.FloatCriticalMultiplier),
IgnoreArmor = inv.Double(wo, IltInventory.FloatIgnoreArmor),
Slayer = inv.Int(wo, IltInventory.IntSlayerCreatureType),
ElementalBonus = inv.Int(wo, IltInventory.IntElementalDamageBonus),
MaxDamage = inv.Int(wo, IltInventory.IntDamage),
// Spells are only read when a spell rule is on (the read copies the item's spell list).
Spells = needSpells ? inv.SpellIds(wo) : Array.Empty<int>(),
};
return CorruptedSkip(G, f);
}
/// <summary>
/// Chunk is allowed while the client is busy only in combat mode with ChunkInCombat on (ub-IT
/// AutoChunkCombatBusyPolicy v2.0.1059: a swinging bot is always busy). Peace mode still waits
/// for idle so the hammer never interrupts another use. Pure: the tests drive it.
/// </summary>
internal static bool AllowsChunkWhileBusy(bool isBusy, bool isPeace, bool chunkInCombat)
=> !isBusy || (!isPeace && chunkInCombat);
private WorldObject? NextChunkTarget()
{
_passSkips.Clear();
foreach (var wo in _ctx.Inventory.Items())
{
if (_skip.Contains(wo.Id)) continue;
string? reason;
switch (KindOf(wo.ObjectClass, wo.Name))
{
case ChunkKind.Aetheria when G.AutoChunkAetheria || _manualPass:
reason = AetheriaSkip(wo);
break;
case ChunkKind.Corrupted when G.AutoChunkCorrupted || _manualPass:
reason = CorruptedSkip(wo);
break;
default:
continue;
}
if (reason == null) { _lastSkip.Remove(wo.Id); return wo; }
NoteSkip(wo, reason);
}
return null;
}
/// <summary>Tallies a skip for the status line and logs it once per item and reason.</summary>
private void NoteSkip(WorldObject wo, string reason)
{
_passSkips[reason] = _passSkips.TryGetValue(reason, out int n) ? n + 1 : 1;
if (reason == Appraising) return;
if (_lastSkip.TryGetValue(wo.Id, out string? last) && last == reason) return;
_lastSkip[wo.Id] = reason;
RynthLog.Write(LogCat.IltGear, $"chunk: keep 0x{(uint)wo.Id:X8} '{wo.Name}': {reason}");
}
/// <summary>"3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips.</summary>
private string PassSkipSummary()
=> string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}"));
/// <summary>Runs one chunk pass now (both item kinds) regardless of the auto toggles.</summary>
public void ChunkNow()
{
@ -143,23 +367,37 @@ internal sealed class IltChunkClap : IIltFeature
if (_waitingOn != 0)
{
if (now - _waitStartedAt < ChunkResultWaitMs) return;
_skip.Add(_waitingOn); // no result line — don't hammer the same item forever
RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)_waitingOn:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass");
int id = _waitingOn;
switch (WaitOutcome(now - _waitStartedAt, _ctx.Inventory.Items().Any(wo => wo.Id == id)))
{
case ChunkWait.Waiting:
return;
case ChunkWait.Gone:
_chunked++;
RynthLog.Write(LogCat.IltGear, $"chunk: 0x{(uint)id:X8} left the pack with no result line; counted as chunked");
break;
case ChunkWait.TimedOut:
_skip.Add(id); // still carried and no result line: don't hammer the same item forever
RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)id:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass");
break;
}
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
_lastChunkAt = now;
if (!G.ChunkInCombat && !_ctx.Inventory.InPeaceMode) { _chunkStatus = "waiting for peace mode"; return; }
if (_ctx.Inventory.IsBusy) return;
bool peace = _ctx.Inventory.InPeaceMode;
if (!G.ChunkInCombat && !peace) { _chunkStatus = "waiting for peace mode"; return; }
if (!AllowsChunkWhileBusy(_ctx.Inventory.IsBusy, peace, G.ChunkInCombat)) { _chunkStatus = "waiting for idle"; return; }
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
string kept = PassSkipSummary();
_chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible")
+ (kept.Length > 0 ? $"; not chunked: {kept}" : "")
+ (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : "");
_manualPass = false;
return;
@ -174,21 +412,64 @@ internal sealed class IltChunkClap : IIltFeature
// ── Clap ────────────────────────────────────────────────────────────────
internal enum ClapPart { None, Red, Blue, Empyrean, Falatacot }
/// <summary>
/// Which side of /clap an item feeds (ACECustom PlayerCommands.HandleClap): red material (Red
/// Coalesced Aetheria, chunks, powder) pairs with Ancient Empyrean Trinkets, blue with Ancient
/// Falatacot Trinkets. Coalesced counts only unrevealed and at level 1-3; level 0 (not read yet)
/// counts, and the server has the last word. With no WCID yet, the chunk and trinket names
/// decide. Pure: the tests drive it.
/// </summary>
internal static ClapPart ClapPartOf(uint wcid, string name, int maxLevel)
{
bool lowCoalesced = name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase) && maxLevel <= 3;
switch (wcid)
{
case IltInventory.WcidRedCoalescedAetheria: return lowCoalesced ? ClapPart.Red : ClapPart.None;
case IltInventory.WcidBlueCoalescedAetheria: return lowCoalesced ? ClapPart.Blue : ClapPart.None;
case IltInventory.WcidRedAetheriaChunk:
case IltInventory.WcidRedAetheriaPowder: return ClapPart.Red;
case IltInventory.WcidBlueAetheriaChunk:
case IltInventory.WcidBlueAetheriaPowder: return ClapPart.Blue;
case IltInventory.WcidEmpyreanTrinket: return ClapPart.Empyrean;
case IltInventory.WcidFalatacotTrinket: return ClapPart.Falatacot;
case 0: break;
default: return ClapPart.None;
}
if (name.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Red;
if (name.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Blue;
if (name.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Empyrean;
if (name.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Falatacot;
return ClapPart.None;
}
/// <summary>
/// True when /clap has a pair to work with: red material and an Empyrean Trinket, or blue
/// material and a Falatacot Trinket. One side alone gets "You don't have any aetheria materials".
/// Pure: the tests drive it.
/// </summary>
internal static bool CanClap(IEnumerable<ClapPart> parts)
{
bool red = false, blue = false, empyrean = false, falatacot = false;
foreach (var part in parts)
{
switch (part)
{
case ClapPart.Red: red = true; break;
case ClapPart.Blue: blue = true; break;
case ClapPart.Empyrean: empyrean = true; break;
case ClapPart.Falatacot: falatacot = true; break;
}
}
return (red && empyrean) || (blue && falatacot);
}
private bool HasClapMaterials()
{
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
uint w = inv.Wcid(wo);
if ((w == IltInventory.WcidRedAetheriaChunk || w == IltInventory.WcidBlueAetheriaChunk)
&& inv.Int(wo, IltInventory.IntItemMaxLevel) <= 3)
return true;
string n = wo.Name;
if (n.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase) || n.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase) || n.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
return CanClap(inv.Items().Where(wo => !inv.IsEquipped(wo))
.Select(wo => ClapPartOf(inv.Wcid(wo), wo.Name, inv.Int(wo, IltInventory.IntItemMaxLevel))));
}
/// <summary>Sends "/clap all" through the capture queue (reply stays visible).</summary>
@ -197,7 +478,7 @@ internal sealed class IltChunkClap : IIltFeature
RynthLog.Trace(LogCat.IltGear, $"ClapNow(manual={manual})");
if (_ctx.Options.IsOff(IltFeature.Clap)) { _clapStatus = "/clap is not available (server or AutoCraftingEnabled stamp)"; return; }
if (_ctx.Capture.IsPending("/clap all")) return;
if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria materials carried"; return; }
if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria and trinket pair carried (red + Empyrean, blue + Falatacot)"; return; }
_clapStatus = "sending /clap all...";
_ctx.Capture.Enqueue(new IltChatRequest
{
@ -245,6 +526,21 @@ internal sealed class IltChunkClap : IIltFeature
internal enum ChunkResult { None, Busy, Done, Refused }
/// <summary>Where a chunk in flight stands when no chat line has ended the wait.</summary>
internal enum ChunkWait { Waiting, Gone, TimedOut }
/// <summary>
/// The wait for a chunk with no result line yet. The hammer destroys the target, so a target
/// that has left the pack was chunked: ILT does not always send a line the classifier knows
/// (Silentkelpie 2026-10-18: a Red Aetheria Chunk arrived and UseDone had no error, yet the
/// item was still filed as skipped after 10 s). Still carried after the wait = timed out.
/// Pure: the tests drive it.
/// </summary>
internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried)
=> !targetStillCarried ? ChunkWait.Gone
: elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut
: ChunkWait.Waiting;
/// <summary>
/// What a chat line says about the chunk in flight. ILT names the item and the tool ("You
/// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted
@ -288,6 +584,7 @@ internal sealed class IltChunkClap : IIltFeature
{
_waitingOn = 0;
_skip.Clear();
_lastSkip.Clear();
_manualPass = false;
_clapWasEnabled = false;
}
@ -306,7 +603,7 @@ internal sealed class IltChunkClap : IIltFeature
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.");
SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.\nA levelled Coalesced Aetheria gets the cap too; an unlevelled one (level 0 after appraisal) is chunked, as in ub-IT.");
bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist;
ImGui.TextUnformatted("Never chunk aetheria with:");
ImGui.SameLine();
@ -318,6 +615,39 @@ internal sealed class IltChunkClap : IIltFeature
ImGui.SameLine();
if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist).");
int ratingAt = G.KeepAetheriaRatingAtLeast;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Keep when the rating is at least##keeprating", ref ratingAt)) G.KeepAetheriaRatingAtLeast = ClampRatingLevel(ratingAt);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Rating level for the C / CD / CDR switches above (Coalesced Aetheria and revealed aetheria).\n"
+ "At or above this level: kept. Below it: the rating does not protect the piece, so it chunks\n"
+ "if the level cap and the other rules allow. 1 = any rating keeps.");
if (ImGui.TreeNode("Corrupted weapon keep rules##corrkeep"))
{
// ub-IT IdleActs > Corr Chunk: each matching rule keeps the weapon.
bool cb = G.KeepCorruptedCrushingBlow, bs = G.KeepCorruptedBitingStrike, acl = G.KeepCorruptedArmorCleaving;
bool sl = G.KeepCorruptedAnySlayer, ms = G.KeepCorruptedMultiStrike, el = G.KeepCorruptedElementalBonus, sp = G.KeepCorruptedAnySpell;
if (ImGui.Checkbox("Crushing Blow##ck", ref cb)) G.KeepCorruptedCrushingBlow = cb;
ImGui.SameLine();
if (ImGui.Checkbox("Biting Strike##ck", ref bs)) G.KeepCorruptedBitingStrike = bs;
ImGui.SameLine();
if (ImGui.Checkbox("Armor Cleaving##ck", ref acl)) G.KeepCorruptedArmorCleaving = acl;
if (ImGui.Checkbox("Any slayer##ck", ref sl)) G.KeepCorruptedAnySlayer = sl;
ImGui.SameLine();
if (ImGui.Checkbox("Multi-strike##ck", ref ms)) G.KeepCorruptedMultiStrike = ms;
ImGui.SameLine();
if (ImGui.Checkbox("Elemental bonus##ck", ref el)) G.KeepCorruptedElementalBonus = el;
if (ImGui.Checkbox("Any spell##ck", ref sp)) G.KeepCorruptedAnySpell = sp;
int maxDmg = G.KeepCorruptedMaxDamageAtLeast;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Keep max damage at least (0 = off)##ck", ref maxDmg)) G.KeepCorruptedMaxDamageAtLeast = Math.Max(0, maxDmg);
string ids = G.KeepCorruptedSpellIds ?? "";
ImGui.SetNextItemWidth(220);
if (ImGui.InputText("Keep spell ids##ck", ref ids, 512)) G.KeepCorruptedSpellIds = ids;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Comma or space separated spell ids: a corrupted weapon carrying any of them is kept.");
SafeImGui.TextDisabled("Always kept: tinkered, imbued, no workmanship, cleave over 1 (2 on two-handed, non-thrust).");
ImGui.TreePop();
}
if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items",
"Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.",
ChunkNow, "Chunk");

View file

@ -111,7 +111,7 @@ internal static class IltFeatureCatalog
new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked),
new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked),
new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab",
"Siphon lenses capture a creature's look into a pet essence (lens drops from kills are a separate server switch).", "monster_capture"),
"Siphon lenses capture a creature\'s look into a pet essence (<=20% health or under 20 HP; Asheron\'s Lens skips the gate). Auto-capture is the checkbox on the Pets roster.", "monster_capture"),
new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding",
"Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"),
new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding",

View file

@ -64,6 +64,8 @@ internal sealed class IltHubController
public IltCharms CharmsTab { get; }
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
public IltGuardian Guardian { get; }
/// <summary>Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind RynthAi's master switch, off by default.</summary>
public IltVaultedDungeons VaultedDungeons { get; }
/// <param name="writesBlocked">True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked).</param>
/// <param name="legacyFolder">The character's RynthAi folder while that copy is unfinished (read-only fallback).</param>
@ -92,7 +94,8 @@ internal sealed class IltHubController
Charms = new IltCharmTracker(_ctx);
CharmsTab = new IltCharms(_ctx, Charms);
Guardian = new IltGuardian(_ctx, QuestBonus);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, Guardian });
VaultedDungeons = new IltVaultedDungeons(_ctx);
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
Rates.MovingMoney = () => Banking.MovingMoney;
@ -192,6 +195,8 @@ internal sealed class IltHubController
IltSection.Character => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
// Content, not a server feature bit: an ILT world and the master switch (RynthAi's setting).
IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(),
_ => Available,
};
@ -320,6 +325,14 @@ internal sealed class IltHubController
}
}
/// <summary>The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only.</summary>
public void OnKillNotification()
{
if (!_ctx.Options.IsIltLikeWorld) return;
try { VaultedDungeons.OnKillNotification(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); }
}
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text)
{
@ -346,6 +359,7 @@ internal sealed class IltHubController
IltProgression => LogCat.IltProgression,
IltGear or IltCharms => LogCat.IltGear,
IltGames => LogCat.IltGames,
IltVaultedDungeons => LogCat.IltHub,
_ => LogCat.IltHub,
};
@ -390,7 +404,11 @@ internal sealed class IltHubController
if (r.Lines.Count == 0) return;
switch (key)
{
case IltFeature.Aug: Progression.ApplyAugLines(r.Lines); break;
case IltFeature.Aug:
Progression.ApplyAugLines(r.Lines);
// Probe's OnComplete is not RequestAugs' — drain a queued Refresh current / empty retry.
Progression.AfterExternalAugCapture();
break;
case IltFeature.Pets: PetLogs.ApplyRoster(false, r.Lines); break;
case IltFeature.Shinies: PetLogs.ApplyRoster(true, r.Lines); break;
case IltFeature.Qb: QuestBonus.ApplyQbProbe(r.Lines); break;
@ -456,7 +474,7 @@ internal sealed class IltHubController
{
// Quests and Pets are RynthAi's tabs: not ours to open.
if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false;
_ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|vaulted|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)");
break;
}
OpenSection(section, args.Length > 2 ? args[2] : "toggle");
@ -494,7 +512,8 @@ internal sealed class IltHubController
break;
default:
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)");
_ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: Settings > Navigation > Vaulted Dungeons)");
_ctx.Chat("[Mini Remote] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)");
@ -580,6 +599,13 @@ internal sealed class IltHubController
OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode);
return;
}
if (section == IltSection.VaultedDungeons && !SectionAvailable(section))
{
_ctx.Chat(_ctx.Options.IsIltLikeWorld
? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in Settings > Navigation (the master switch, off by default)."
: "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only).");
return;
}
string reply = _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), mode);
if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase))
reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on.";

View file

@ -204,7 +204,7 @@ public sealed class IltGearState
public bool ChunkInCombat;
public int ChunkIntervalMs = 2000;
/// <summary>
/// Only chunk aetheria whose max level is below this (Coalesced always chunks). Infinite Leaftide
/// Only chunk aetheria whose max level is below this (Coalesced Aetheria too). Infinite Leaftide
/// aetheria goes up to level <see cref="IltInventory.AetheriaMaxLevel"/>, so the cap runs to one past it.
/// </summary>
public int ChunkAetheriaUnderLevel = 4;
@ -214,6 +214,32 @@ public sealed class IltGearState
public bool KeepAetheriaWithCritDamage = true;
/// <summary>Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375).</summary>
public bool KeepAetheriaWithCritDamageResist = true;
/// <summary>
/// Rating level for the C / CD / CDR keep switches: a rating at or above this keeps the piece,
/// a lower one does not protect it (it chunks if the other rules allow). 1 = any rating keeps.
/// </summary>
public int KeepAetheriaRatingAtLeast = 1;
// Corrupted-weapon keep rules (ub-IT IdleActs > Corr Chunk). All off by default, as in ub-IT:
// the hard rules (unmodified, workmanship, cleaving, never-chunk) always apply on top.
/// <summary>Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 &gt; 0).</summary>
public bool KeepCorruptedCrushingBlow;
/// <summary>Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 &gt; 0).</summary>
public bool KeepCorruptedBitingStrike;
/// <summary>Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 &gt; 0).</summary>
public bool KeepCorruptedArmorCleaving;
/// <summary>Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 &gt; 0).</summary>
public bool KeepCorruptedAnySlayer;
/// <summary>Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486).</summary>
public bool KeepCorruptedMultiStrike;
/// <summary>Never chunk a corrupted weapon with an elemental damage bonus (int 204 &gt; 0).</summary>
public bool KeepCorruptedElementalBonus;
/// <summary>Never chunk a corrupted weapon with any spell on it.</summary>
public bool KeepCorruptedAnySpell;
/// <summary>Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off.</summary>
public int KeepCorruptedMaxDamageAtLeast;
/// <summary>Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them.</summary>
public string KeepCorruptedSpellIds = "";
// Auto-clap (/clap all)
public bool AutoClap;

View file

@ -70,6 +70,7 @@ internal sealed class IltHubUi
case IltSection.Gear: _hub.Gear.Render(); break;
case IltSection.Charms: _hub.CharmsTab.Render(); break;
case IltSection.Games: _hub.Games.Render(); break;
case IltSection.VaultedDungeons: _hub.VaultedDungeons.Render(); break;
default:
// A saved tab id from before the move: say where the section lives now.
if (IltSections.MovedCommand(section) is string moved)

View file

@ -36,8 +36,18 @@ internal sealed class IltInventory
public const uint WcidSummonRefillCharm = 78780030;
public const uint WcidUniversalMasteryCharm = 78780031;
public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 };
public const uint WcidRedAetheriaChunk = 42636;
public const uint WcidBlueAetheriaChunk = 42635;
// Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once
// revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones.
public const uint WcidBlueCoalescedAetheria = 42635;
public const uint WcidRedCoalescedAetheria = 42636;
public const uint WcidYellowCoalescedAetheria = 42637;
public const uint WcidRedAetheriaChunk = 310147;
public const uint WcidBlueAetheriaChunk = 310149;
public const uint WcidYellowAetheriaChunk = 310150;
public const uint WcidRedAetheriaPowder = 42644;
public const uint WcidBlueAetheriaPowder = 300019;
public const uint WcidEmpyreanTrinket = 34276;
public const uint WcidFalatacotTrinket = 34277;
// ── Property ids used by several features ───────────────────────────────
public const uint IntStackSize = 12;
@ -48,6 +58,27 @@ internal sealed class IltInventory
public const uint IntNumTimesTinkered = 171;
public const uint IntImbuedEffect = 179;
public const uint IntCleaving = 292;
// Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard).
/// <summary>ACE PropertyInt.Damage — a weapon's max damage.</summary>
public const uint IntDamage = 44;
/// <summary>ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks.</summary>
public const uint IntAttackType = 47;
/// <summary>ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons).</summary>
public const uint IntItemWorkmanship = 105;
/// <summary>ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons.</summary>
public const uint IntWieldSkillType = 159;
/// <summary>ACE PropertyInt.SlayerCreatureType.</summary>
public const uint IntSlayerCreatureType = 166;
/// <summary>ACE PropertyInt.ElementalDamageBonus.</summary>
public const uint IntElementalDamageBonus = 204;
/// <summary>ACE PropertyInt.WeaponType — 11 = TwoHanded.</summary>
public const uint IntWeaponType = 353;
/// <summary>ACE PropertyFloat.CriticalMultiplier — Biting Strike.</summary>
public const uint FloatCriticalMultiplier = 136;
/// <summary>ACE PropertyFloat.CriticalFrequency — Crushing Blow.</summary>
public const uint FloatCriticalFrequency = 147;
/// <summary>ACE PropertyFloat.IgnoreArmor — Armor Cleaving.</summary>
public const uint FloatIgnoreArmor = 155;
public const uint IntItemMaxLevel = 319;
/// <summary>Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5).</summary>
public const int AetheriaMaxLevel = 10;
@ -176,6 +207,22 @@ internal sealed class IltInventory
public long Quad(WorldObject wo, uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0;
/// <summary>A float (PropertyFloat) value; 0 when the host cannot read it or the item has none.</summary>
public double Double(WorldObject wo, uint stype)
=> _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0;
/// <summary>The spell ids on an item (empty when none or the host cannot read them).</summary>
public IReadOnlyList<int> SpellIds(WorldObject wo)
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
var buf = new uint[64];
int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
var ids = new int[Math.Min(n, buf.Length)];
for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]);
return ids;
}
public string Str(WorldObject wo, uint stype)
=> _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty;
@ -191,6 +238,25 @@ internal sealed class IltInventory
public bool HasAppraisal(WorldObject wo)
=> !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id));
/// <summary>
/// Why an item's property reads cannot be trusted (null = they can). Every property read here
/// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk
/// rule that acts on a 0 must first know the read was real: the host must expose the readers
/// and confirm the item's appraisal arrived. <paramref name="quads"/> adds the 64-bit reads
/// (item XP), <paramref name="doubles"/> the float reads and <paramref name="spells"/> the
/// spell list, for the rules that use them.
/// </summary>
public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false)
{
if (!_host.HasGetObjectIntProperty) return "int properties";
if (!_host.HasGetObjectBoolProperty) return "bool properties";
if (quads && !_host.HasGetObjectQuadProperty) return "item XP";
if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties";
if (spells && !_host.HasGetObjectSpellIds) return "spells";
if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal";
return null;
}
/// <summary>Requests appraisal data, throttled per object. Returns true if a request was sent.</summary>
public bool RequestAppraisal(WorldObject wo)
{

View file

@ -48,6 +48,8 @@ internal static class LogEvents
public const string IltCommand = "IltHub.Command";
public const string IltConfirmation = "IltHub.Confirmation";
public const string IltLogout = "IltHub.Logout";
/// <summary>/aug ApplyAugLines outcome (Progress Refresh current / login probe).</summary>
public const string IltAugLoad = "IltHub.AugLoad";
/// <summary>Events written as a normal log line; the rest only while their category is traced.</summary>
internal static readonly Dictionary<string, (LogCat Cat, bool Info)> Catalog = new(StringComparer.Ordinal)
@ -61,6 +63,7 @@ internal static class LogEvents
[IltCommand] = (LogCat.IltHub, false),
[IltConfirmation] = (LogCat.IltHub, false),
[IltLogout] = (LogCat.IltHub, false),
[IltAugLoad] = (LogCat.IltProgression, true),
};
}

View file

@ -18,7 +18,7 @@ internal static class IltParse
/// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2".
/// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys.
/// </summary>
public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*([\d,]+)", Opt);
public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", Opt);
/// <summary>"/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".</summary>
public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);
@ -46,6 +46,22 @@ internal static class IltParse
/// <summary>"/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!".</summary>
public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt);
private static readonly Regex GroupedInt = new(@"^\d{1,3}(?:[,.\s']\d{3})+|^\d+", RegexOptions.CultureInvariant);
/// <summary>
/// The level in an AugLine value: digits grouped by a comma, period, space or apostrophe
/// ("4,300", "4.300", "4 300", "4'300") read as one number; "2 (adds 5)" as 2; "1.5" as 1. 0 when absent.
/// </summary>
public static long ParseAugValue(string text)
{
if (string.IsNullOrEmpty(text)) return 0;
var m = GroupedInt.Match(text.Trim());
if (!m.Success) return 0;
var digits = new System.Text.StringBuilder(m.Value.Length);
foreach (char c in m.Value) if (char.IsDigit(c)) digits.Append(c);
return long.TryParse(digits.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0;
}
/// <summary>Strips commas and parses the leading integer; 0 when absent.</summary>
public static long ParseLeadingLong(string text)
{

View file

@ -65,6 +65,8 @@ internal sealed class IltProgression : IIltFeature
private bool _augAutoTried;
/// <summary>Second Refresh current while /aug is already queued or in flight (UB coalesces the same way).</summary>
private bool _augRefreshAgain;
/// <summary>One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race).</summary>
private bool _augProbeRetryDone;
/// <summary>Passive /aug window: accept AugLine chat until this tick (like T11's report parser).</summary>
private long _augPassiveUntilMs;
@ -113,7 +115,8 @@ internal sealed class IltProgression : IIltFeature
_augStatus = "/aug is off for this world";
return;
}
// Coalesce: a click during an in-flight /aug runs again when that capture finishes (UB).
// Coalesce: a click during an in-flight /aug (login probe or a prior Refresh) runs again
// when that capture finishes — including via AfterExternalAugCapture for the probe.
if (_ctx.Capture.IsPending("/aug"))
{
_augRefreshAgain = true;
@ -121,15 +124,16 @@ internal sealed class IltProgression : IIltFeature
return;
}
_augStatus = "loading...";
_augPassiveUntilMs = IltHubContext.NowMs + 20_000; // also accept lines if capture finishes early
_augPassiveUntilMs = IltHubContext.NowMs + 30_000; // also accept lines if capture finishes early
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
// Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines.
ArmsIdle = t => IltParse.AugLine.IsMatch(t),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
IdleEndMs = 2500,
// Login + chat-hold backlog can push Creature: past the old 15s first-line window.
FirstLineTimeoutMs = 30_000,
Eat = true,
OnComplete = r =>
{
@ -148,15 +152,36 @@ internal sealed class IltProgression : IIltFeature
if (have == 0)
_augStatus = "timed out waiting for /aug level lines";
}
if (_augRefreshAgain)
{
_augRefreshAgain = false;
RequestAugs();
}
DrainAugRefreshAgain();
},
});
}
/// <summary>
/// Login probe finished its "/aug" capture (or another path applied lines). Drains a queued
/// Refresh current and, if the probe left Current empty, retries once.
/// </summary>
public void AfterExternalAugCapture()
{
if (DrainAugRefreshAgain()) return;
int have;
lock (_augLevels) have = _augLevels.Count;
if (have > 0 || _augProbeRetryDone || _ctx.Options.IsOff(IltFeature.Aug)) return;
if (_ctx.Capture.IsPending("/aug")) return;
_augProbeRetryDone = true;
RynthLog.Event(LogEvents.IltAugLoad, "aug probe left Current empty — retrying /aug once");
RequestAugs();
}
/// <summary>Runs a coalesced Refresh current if one was queued. Returns true when it did.</summary>
private bool DrainAugRefreshAgain()
{
if (!_augRefreshAgain) return false;
_augRefreshAgain = false;
RequestAugs();
return true;
}
/// <summary>Parses "/aug" output (also fed from the login probe and passive chat).</summary>
public void ApplyAugLines(List<string> lines)
{
@ -166,8 +191,26 @@ internal sealed class IltProgression : IIltFeature
{
if (TryApplyAugLine(l)) n++;
}
_augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines done: {_augStatus} (raw lines={lines.Count})");
if (n > 0)
{
_augStatus = $"{n} aug types @ {DateTime.Now:t}";
_augPassiveUntilMs = IltHubContext.NowMs + 8_000;
}
else
{
bool sawBanner = false;
foreach (string l in lines)
{
if (l.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase))
{ sawBanner = true; break; }
}
_augStatus = sawBanner
? "no level lines yet (banner only — waiting / retry)"
: "no aug lines in reply";
// Keep the passive reader open so late Creature: lines still fill Current.
if (sawBanner) _augPassiveUntilMs = IltHubContext.NowMs + 15_000;
}
RynthLog.Event(LogEvents.IltAugLoad, $"ApplyAugLines: {_augStatus} (raw={lines.Count})");
}
/// <summary>Applies one "/aug" Type: N line. Returns true when a known planner key was updated.</summary>
@ -182,7 +225,7 @@ internal sealed class IltProgression : IIltFeature
foreach (var (k, _) in IltAugCosts.Labels)
if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; }
if (!known) return false;
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseAugValue(m.Groups[2].Value);
return true;
}
@ -249,6 +292,7 @@ internal sealed class IltProgression : IIltFeature
lock (_augLevels) _augLevels.Clear();
_augAutoTried = false;
_augRefreshAgain = false;
_augProbeRetryDone = false;
_augPassiveUntilMs = 0;
_augStatus = "not loaded";
}

View file

@ -1,7 +1,7 @@
// IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel.
// Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13.
//
// Banking, Gear, Charms and Games are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar
// Banking, Gear, Charms, Games and Vaulted Dungeons are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar
// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub
// GetTabs / RenderTab); "/ra hub open <section>" picks one, and with RynthCore's sections rail
// RynthAi lists them as "section:<tab>" views (Inventory). Guardian is a RynthCore ILT panel
@ -29,6 +29,11 @@ internal enum IltSection
Banking,
Gear,
Games,
/// <summary>
/// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only,
/// and only while RynthAi's "Vaulted Dungeons" master switch (Settings > Navigation) is on.
/// </summary>
VaultedDungeons,
/// <summary>Registry charms (acquired / status / tier / server) and the Guardian Hand.</summary>
Charms,
// Keep Guardian last.
@ -40,7 +45,7 @@ internal static class IltSections
/// <summary>The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs).</summary>
public static readonly IltSection[] Tabs =
{
IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games,
IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons,
};
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
@ -55,6 +60,7 @@ internal static class IltSections
IltSection.Banking => "Banking",
IltSection.Gear => "Gear",
IltSection.Games => "Games",
IltSection.VaultedDungeons => "Vaulted Dungeons",
IltSection.Charms => "Charms",
IltSection.Guardian => "Guardian",
_ => s.ToString(),
@ -70,13 +76,15 @@ internal static class IltSections
IltSection.Banking => "banking",
IltSection.Gear => "gear",
IltSection.Games => "games",
IltSection.VaultedDungeons => "vaulted",
IltSection.Charms => "charms",
IltSection.Guardian => "guardian",
_ => s.ToString().ToLowerInvariant(),
};
/// <summary>True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games).</summary>
public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games;
/// <summary>True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons).</summary>
public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games
or IltSection.VaultedDungeons;
/// <summary>
/// Where a section that moved out of the Mini Remote lives now, as the chat command that opens
@ -104,6 +112,8 @@ internal static class IltSections
case "banking": case "bank": section = IltSection.Banking; return true;
case "gear": section = IltSection.Gear; return true;
case "games": case "game": section = IltSection.Games; return true;
case "vaulted": case "vaulteddungeons": case "vaulted-dungeons":
section = IltSection.VaultedDungeons; return true;
case "charms": case "charm": section = IltSection.Charms; return true;
case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Gear; return false;
@ -120,6 +130,7 @@ internal static class IltSections
IltSection.Gear => new Vector2(560, 520),
IltSection.Charms => new Vector2(560, 520),
IltSection.Games => new Vector2(520, 440),
IltSection.VaultedDungeons => new Vector2(360, 420),
_ => new Vector2(520, 440),
};

View file

@ -0,0 +1,919 @@
// IltVaultedDungeons.cs — Mini Remote "Vaulted Dungeons" tab (ILT / ACECustom only).
// Written by Silentkelpie (RynthSuite PR #12), a port of the UtilityBelt VaultedDungeons.lua script
// (owner 2026-09-27 / 2026-10-03): keeps the character in one Vaulted Dungeon via a tied Portal
// Recall Gem, and optionally /rc quit after N minutes without a kill.
//
// Safety rules (the owner's, added when it was taken in):
// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless
// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same
// verdict every other ILT feature follows. A command answers "not available on this server".
// * Master switch, off by default: RynthAi's "Vaulted Dungeons" setting (Settings > Navigation),
// read through RynthAi.Hub VaultedDungeonsEnabled. It is the only copy. While it is off the module
// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning
// it off while running stops the keeper at once and says so once.
// * Active is never resumed from the saved settings. It starts when the player turns it on, or on
// arriving in the chosen dungeon with Auto Start On Arrival on (master on); a relog starts Off.
// * No recall gem while RynthAi is in combat, buffing or waiting on the server, or the client is
// busy: the recall waits until it is clear (a warning on the normal 30 s cadence).
// * /rc quit goes out at most once per activation, and only if Active, ILT and the master are all
// still true at the moment of sending.
// * The no-kill timer restarts on the luminance line, on the server's killer notification (a
// killing blow of yours) and on a pet-capture success reply. Kills by pets or fellows that pay
// no luminance still don't count; the tab says so.
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>One known Vaulted Dungeon (landblock high word; the client does not see the layer).</summary>
internal readonly record struct VaultedDungeon(string Name, uint Landblock);
internal sealed class IltVaultedDungeons : IIltFeature
{
// Keep order stable: saved picks are by 1-based index into this list.
private static readonly VaultedDungeon[] Dungeons =
{
new("Tyrant's Quarry", 0x01F7),
new("Tusgian Barracks", 0x8C03),
new("Wailing Cells", 0x01C2),
new("Chamber of Idols", 0x5649),
new("Fiun Redoubt", 0x0178), // added 2026-09-27
new("Tumerok Tunnels", 0x5754), // added 2026-10-03
};
private static readonly string[] GemNames =
{
"Primary Portal Recall Gem",
"Secondary Portal Recall Gem",
};
private static readonly (string Name, float Value)[] Powers =
{
("Fast", 0f), ("Medium", 0.5f), ("Full Power", 1f),
};
private static readonly int[] QuitPresets = { 1, 2, 5, 10, 15, 30 };
private const long FirstRecallAfterMs = 1000;
private const long RecallAfterMs = 5000;
private const int QuitMin = 1, QuitMax = 30;
private const long WarnEveryMs = 30_000;
private const string SettingsFileName = "settings.json";
private const string SettingsBadFileName = "settings.unreadable.json";
private const string CmdMetaOff = "/vt opt set EnableMeta False";
private const string CmdNavOff = "/vt opt set EnableNav False";
private const string CmdRepeatOn = "/ub playeroption AutoRepeatAttack on";
private const string CmdAttackBar = "/vt setattackbar ";
private const string CmdQuit = "/rc quit";
// System line only (no player sender): "You've banked 1,234 Luminance."
private static readonly Regex KillLine = new(
@"^You've banked [\d,]+ Luminance\.\s*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>Why the keeper is idle (<see cref="Snapshot.Gate"/>): "" = it may run.</summary>
private const string GateWorld = "world", GateMaster = "master";
private readonly IltHubContext _ctx;
private readonly object _gate = new();
private Cfg _cfg = new();
private bool _loaded;
private bool _dirty;
private string? _lastGoodJson;
// Seams (the tests fake them): the master switch, what RynthAi is doing, the clock, the gem use.
internal Func<bool> MasterEnabled;
internal Func<RynthAiActivity?> Activity;
internal Func<long> Clock = () => IltHubContext.NowMs;
/// <summary>Uses the named gem from the pack; false when the pack has none.</summary>
internal Func<string, bool> UseGem;
// Runtime (pump thread).
private long _outSinceMs;
private long _lastRecallMs;
private long _clockStartMs;
private long _realKillMs;
private bool _wasInside;
private bool _quitSent;
private long _lastWarnMs = -WarnEveryMs;
private string _publishedGate = "?";
private string _state = "paused"; // paused / setup / in / out / portal / nogem
private long? _quitLeftMs;
private bool? _presentBefore;
private long _idleSecs;
private long _inSinceMs;
private long _portalSinceMs;
private int _kills;
private long _dungeonSecs;
private long _lastTickMs;
// Snapshot for the render thread (copied under _gate).
private Snapshot _snap = Snapshot.Empty;
public IltVaultedDungeons(IltHubContext ctx)
{
_ctx = ctx;
MasterEnabled = () => _ctx.Ai.VaultedDungeonsEnabled;
Activity = () => _ctx.Ai.Activity();
UseGem = gemName =>
{
var gem = _ctx.Inventory.FindByName(n => n.Equals(gemName, StringComparison.OrdinalIgnoreCase));
if (gem == null) return false;
_ctx.Inventory.Use(gem);
return true;
};
}
/// <summary>Whether the keeper is running (tests, status).</summary>
internal bool IsActive => _cfg.Active;
private long Now() => Clock();
/// <summary>
/// The two hard rules, asked fresh each time: an ILT-like world, and the master switch on.
/// <paramref name="gate"/> says which one failed ("" when allowed).
/// </summary>
private bool Allowed(out string gate)
{
gate = !_ctx.Options.IsIltLikeWorld ? GateWorld : !MasterEnabled() ? GateMaster : string.Empty;
return gate.Length == 0;
}
/// <summary>Same, for commands and the tab: why the keeper can't be used now (null = it can).</summary>
private static string? GateReply(string gate) => gate switch
{
GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).",
GateMaster => "Off: turn on \"Vaulted Dungeons\" in Settings > Navigation first (the master switch, off by default).",
_ => null,
};
// ── Persistence ─────────────────────────────────────────────────────────
private string SettingsDir => Path.Combine(_ctx.Store.CharFolder, "VaultedDungeons");
private string SettingsPath => Path.Combine(SettingsDir, SettingsFileName);
private void EnsureLoaded()
{
if (_loaded) return;
_loaded = true;
try
{
string path = SettingsPath;
if (!File.Exists(path)) return;
string text = File.ReadAllText(path);
var cfg = JsonSerializer.Deserialize(text, IltVaultedDungeonsJsonContext.Default.Cfg);
if (cfg == null) return;
_cfg = Sanitize(cfg);
_lastGoodJson = text;
}
catch (Exception ex)
{
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings load failed: {ex.Message}");
}
}
private void SaveIfDirty()
{
if (!_dirty) return;
_dirty = false;
try
{
Directory.CreateDirectory(SettingsDir);
string path = SettingsPath;
// Corrupt / mid-write: keep a copy, then rewrite from last good + current cfg.
if (File.Exists(path))
{
try
{
string existing = File.ReadAllText(path);
if (_lastGoodJson == null)
JsonSerializer.Deserialize(existing, IltVaultedDungeonsJsonContext.Default.Cfg); // throws if bad
}
catch
{
try
{
File.Copy(path, Path.Combine(SettingsDir, SettingsBadFileName), overwrite: true);
_ctx.Chat("[Vaulted Dungeons] settings.json would not read — kept a copy as "
+ SettingsBadFileName + ".");
}
catch { /* best effort */ }
}
}
string json = JsonSerializer.Serialize(_cfg, IltVaultedDungeonsJsonContext.Default.Cfg);
File.WriteAllText(path, json);
_lastGoodJson = json;
}
catch (Exception ex)
{
RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings save failed: {ex.Message}");
}
}
private static Cfg Sanitize(Cfg c)
{
// Never resumed from disk: the file keeps its "active" field, but a relog (or turning the
// master switch back on) starts Off. Auto Start On Arrival is the only way back in by itself.
c.Active = false;
c.Dungeon = ClampInt(c.Dungeon, 0, Dungeons.Length, 0);
c.Gem = ClampInt(c.Gem, 0, GemNames.Length, 0);
c.QuitMinutes = ClampInt(c.QuitMinutes, QuitMin, QuitMax, 2);
c.AttackPower = Powers[PowerIndex(c.AttackPower)].Value;
return c;
}
private static int ClampInt(int v, int lo, int hi, int def)
=> v < lo || v > hi ? def : v;
private static int PowerIndex(float v)
{
int best = 0;
float bestGap = float.MaxValue;
for (int i = 0; i < Powers.Length; i++)
{
float gap = Math.Abs(Powers[i].Value - v);
if (gap < bestGap) { best = i; bestGap = gap; }
}
return best;
}
private static string PowerText(float p)
{
string t = p.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture);
return t;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// The hard rules first: ILT only, master switch on. Nothing below runs otherwise (not even
// reading the settings file), and a keeper that was running is stopped on the spot.
if (!Allowed(out string gate))
{
StopForGate(gate);
PublishGate(gate);
return;
}
EnsureLoaded();
SaveIfDirty();
// Time in dungeon (kills/hour): only while last state was "in".
if (_lastTickMs > 0 && _state == "in")
_dungeonSecs += Math.Max(0, (nowMs - _lastTickMs) / 1000);
_lastTickMs = nowMs;
if (!_ctx.Host.HasGetPlayerPose || !_ctx.Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || cell == 0)
{
Publish();
return;
}
uint landblock = cell >> 16;
bool portaling = _ctx.Host.HasIsPortaling && _ctx.Host.IsPortaling();
VaultedDungeon? dungeon = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length
? Dungeons[_cfg.Dungeon - 1]
: null;
// Present check (for Auto Start / arrive actions) even while Off.
if (dungeon == null)
_presentBefore = null;
else if (!portaling)
{
bool here = landblock == dungeon.Value.Landblock;
if (here && _presentBefore != true) OnArrive(dungeon.Value, nowMs);
_presentBefore = here;
}
_quitLeftMs = null;
if (!_cfg.Active)
{
_state = "paused";
_outSinceMs = 0;
Publish();
return;
}
string? gemName = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length ? GemNames[_cfg.Gem - 1] : null;
if (dungeon == null || gemName == null)
{
_state = "setup";
_wasInside = false;
Warn(nowMs, dungeon == null
? "Pick a dungeon in the Vaulted Dungeons tab."
: "Pick a recall gem in the Vaulted Dungeons tab.");
Publish();
return;
}
bool inside = landblock == dungeon.Value.Landblock;
if (inside && !portaling)
{
if (!_wasInside)
{
_clockStartMs = nowMs;
_inSinceMs = nowMs;
}
_wasInside = true;
_outSinceMs = 0;
_portalSinceMs = 0;
_state = "in";
_idleSecs = Math.Max(0, (nowMs - _clockStartMs) / 1000);
if (_cfg.Quit)
{
long quitAfterMs = _cfg.QuitMinutes * 60_000L;
_quitLeftMs = Math.Max(0, quitAfterMs - (nowMs - _clockStartMs));
if (nowMs - _clockStartMs >= quitAfterMs && !_quitSent)
{
// Once per activation, and only if ILT, the master switch and Active are all
// still true right now (asked again: they may have changed since the top of the tick).
string nowGate = string.Empty;
if (!_cfg.Active || !Allowed(out nowGate))
{
StopForGate(nowGate);
PublishGate(nowGate);
return;
}
_quitSent = true;
_ctx.Chat($"[Vaulted Dungeons] No kill in {_cfg.QuitMinutes} minute"
+ (_cfg.QuitMinutes == 1 ? "" : "s") + " — quitting.");
Invoke(CmdQuit);
}
}
Publish();
return;
}
_wasInside = false;
if (portaling)
{
_state = "portal";
_outSinceMs = 0;
if (_portalSinceMs == 0) _portalSinceMs = nowMs;
Publish();
return;
}
_portalSinceMs = 0;
if (_outSinceMs == 0) _outSinceMs = nowMs;
_state = "out";
bool tried = _lastRecallMs >= _outSinceMs;
bool due = (!tried && nowMs - _outSinceMs >= FirstRecallAfterMs)
|| (tried && nowMs - _lastRecallMs >= RecallAfterMs);
if (due)
{
// Not in the middle of a fight, a buff chain or an unanswered use/cast: the recall waits
// (still due, so it goes out on the first clear tick) and says so on the normal cadence.
string? busy = BusyReason();
if (busy != null)
{
_state = "busy";
Warn(nowMs, $"Waiting to use the {gemName}: {busy}.");
}
else if (UseGem(gemName))
{
_lastRecallMs = nowMs;
_ctx.Chat($"[Vaulted Dungeons] Not in {dungeon.Value.Name} — using the {gemName}.");
}
else
{
_state = "nogem";
Warn(nowMs, $"No {gemName} in your pack.");
}
}
Publish();
}
/// <summary>
/// Why a recall gem must not be used now, or null when it may. RynthAi's activity (its "RynthAi.Activity"
/// bits: combat, buffing, loot, salvage, crafting, a use/cast waiting on the server) and the client's
/// busy hourglass; RynthAi not answering counts as busy (nothing is known, so nothing is used).
/// </summary>
private string? BusyReason()
{
RynthAiActivity? a = Activity();
if (a is null) return "RynthAi is not ready";
RynthAiActivity f = a.Value;
if ((f & RynthAiActivity.Combat) != 0) return "RynthAi is in combat";
if ((f & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing";
if ((f & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server";
if ((f & RynthAiActivity.Looting) != 0) return "RynthAi is looting";
if ((f & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging";
if ((f & RynthAiActivity.Crafting) != 0) return "RynthAi is crafting";
if (_ctx.Inventory.IsBusy) return "the client is busy";
return null;
}
/// <summary>
/// A rule failed (not ILT any more, or the master switch went off): a running keeper stops at once
/// and says so once; an idle one has nothing to do. Safe to call every tick.
/// </summary>
private void StopForGate(string gate)
{
_outSinceMs = 0;
_wasInside = false;
_quitLeftMs = null;
_presentBefore = null;
if (!_cfg.Active) return;
_cfg.Active = false;
_dirty = true;
_state = "paused";
_ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld
? "this is not an Infinite Leaftide / ACECustom world."
: "\"Vaulted Dungeons\" was turned off in Settings > Navigation."));
SaveIfDirty();
}
/// <summary>The idle snapshot (only when the reason changes: nothing else runs while gated).</summary>
private void PublishGate(string gate)
{
if (gate == _publishedGate) return;
_publishedGate = gate;
Publish(gate);
}
public bool OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return false;
string line = text.TrimEnd();
bool luminance = KillLine.IsMatch(line);
// A pet-capture success counts as a kill for the timer too (the same replies RynthAi's Pets
// tab matches); nothing else is guessed.
if (!luminance && !PetCaptureLines.IsSuccess(line)) return false;
if (!_cfg.Active || !Allowed(out _)) return false;
NoteKill(Now(), countKill: luminance);
return false; // never eat the luminance line
}
/// <summary>
/// The server's killer notification: this character landed a killing blow (RynthILTPlugin
/// .OnKillNotification, pump thread). Restarts the no-kill timer, like the luminance line.
/// </summary>
public void OnKillNotification()
{
if (!_cfg.Active || !Allowed(out _)) return;
NoteKill(Now(), countKill: false);
}
/// <summary>Restarts the Kill Client timer. The kill counter moves only on the luminance line (one per kill).</summary>
private void NoteKill(long now, bool countKill)
{
_clockStartMs = now;
_realKillMs = now;
if (countKill && _state == "in") _kills++;
Publish();
}
public void OnLogout()
{
// Logging out ends the run: Active is never carried over (see Sanitize).
_cfg.Active = false;
SaveIfDirty();
_wasInside = false;
_outSinceMs = 0;
_presentBefore = null;
_state = "paused";
Publish();
}
// ── Arrive / commands ───────────────────────────────────────────────────
private void OnArrive(VaultedDungeon dungeon, long nowMs)
{
// Only called while ILT and the master switch are on (Tick's gate), so Auto Start is honoured here only.
if (_cfg.AutoStart && !_cfg.Active)
{
Activate(nowMs);
_ctx.Chat($"[Vaulted Dungeons] Arrived in {dungeon.Name} — switched On (Auto Start On Arrival).");
}
// The arrival settings are part of running the keeper: nothing is sent while it is Off.
if (!_cfg.Active) return;
if (_cfg.DisableMeta) Invoke(CmdMetaOff);
if (_cfg.DisableNav) Invoke(CmdNavOff);
if (_cfg.RepeatAttack) Invoke(CmdRepeatOn);
if (_cfg.SetPower) Invoke(CmdAttackBar + PowerText(_cfg.AttackPower));
}
private void Invoke(string cmd)
{
if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd);
}
private void Warn(long nowMs, string text)
{
if (nowMs - _lastWarnMs < WarnEveryMs) return;
_lastWarnMs = nowMs;
_ctx.Chat("[Vaulted Dungeons] " + text);
}
/// <summary>Pump-thread: /ilt vaulted [on|off|toggle|status].</summary>
public bool HandleCommand(string[] args)
{
// ILT only, master switch on: otherwise the only answer is why (the keeper itself stays idle).
if (!Allowed(out string gate))
{
if (_cfg.Active) StopForGate(gate);
_ctx.Chat("[Vaulted Dungeons] " + GateReply(gate));
return true;
}
EnsureLoaded();
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
switch (sub)
{
case "on":
case "start":
SetActive(true);
return true;
case "off":
case "stop":
SetActive(false);
_ctx.Chat("[Vaulted Dungeons] Off.");
return true;
case "toggle":
SetActive(!_cfg.Active);
if (!_cfg.Active) _ctx.Chat("[Vaulted Dungeons] Off.");
return true;
default:
string d = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length
? Dungeons[_cfg.Dungeon - 1].Name : "(none)";
string g = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length
? GemNames[_cfg.Gem - 1] : "(none)";
_ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, "
+ $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}.");
_ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: Settings > Navigation > Vaulted Dungeons)");
return true;
}
}
/// <summary>Starts the keeper (the player's own action, or Auto Start On Arrival). Pump thread; ILT and master already checked.</summary>
private void Activate(long nowMs)
{
_cfg.Active = true;
_dirty = true;
_outSinceMs = 0;
_wasInside = false; // the no-kill clock starts when the first in-dungeon tick sees us inside
_clockStartMs = nowMs;
_quitSent = false; // /rc quit: once per activation
_lastRecallMs = 0;
Publish();
}
private void SetActive(bool value)
{
if (value)
{
// From the tab's button too (posted to the pump): re-check, the switch may have gone off since.
if (!Allowed(out string gate))
{
_ctx.Chat("[Vaulted Dungeons] " + GateReply(gate));
return;
}
EnsureLoaded();
if (!_cfg.Active)
{
Activate(Now());
_ctx.Chat("[Vaulted Dungeons] On.");
}
return;
}
_cfg.Active = false;
_outSinceMs = 0;
_dirty = true;
_clockStartMs = Now();
_wasInside = false;
_quitLeftMs = null;
_state = "paused";
Publish();
}
// ── Render snapshot ─────────────────────────────────────────────────────
private void Publish(string gate = "")
{
_publishedGate = gate;
lock (_gate)
{
_snap = new Snapshot(
_cfg.Active, _cfg.Dungeon, _cfg.Gem, _cfg.Quit, _cfg.QuitMinutes,
_cfg.ShowInDungeon, _cfg.AutoStart, _cfg.DisableMeta, _cfg.DisableNav,
_cfg.RepeatAttack, _cfg.SetPower, _cfg.AttackPower,
_state, _quitLeftMs, _idleSecs, _inSinceMs, _outSinceMs, _portalSinceMs,
_realKillMs, _kills, _dungeonSecs, Now(), gate);
}
}
private Snapshot Take()
{
lock (_gate) return _snap;
}
// ── UI (render thread) ──────────────────────────────────────────────────
private bool _showAdvanced;
// Pending edits from the UI, applied on the next pump tick via Post.
private void PostEdit(Action<Cfg> edit)
{
_ctx.Post(() =>
{
if (!Allowed(out _)) return; // gated while it waited: an edit changes nothing
EnsureLoaded();
edit(_cfg);
_dirty = true;
Publish();
});
}
public void Render()
{
// Settings load on the pump (Tick); the window only reads the snapshot.
Snapshot s = Take();
Vector4 colLabel = new(0.53f, 0.53f, 0.53f, 1f);
Vector4 colValue = new(1f, 1f, 1f, 1f);
Vector4 colGreen = new(0.27f, 0.80f, 0.40f, 1f);
Vector4 colAmber = new(0.95f, 0.65f, 0.20f, 1f);
Vector4 colRed = new(0.90f, 0.30f, 0.30f, 1f);
Vector4 colPurple = new(0.72f, 0.52f, 0.95f, 1f);
Vector4 colTitleRed = new(0.85f, 0.25f, 0.25f, 1f);
// Title row: Vaulted (red) Dungeons (white) + On/Off + Advanced.
ImGui.TextColored(colTitleRed, "Vaulted");
ImGui.SameLine(0, ImGui.CalcTextSize(" ").X);
ImGui.TextColored(colValue, "Dungeons");
// Not offered right now (the tab is hidden then; this covers a stale frame or a direct open).
if (s.Gate.Length > 0)
{
ImGui.Separator();
ImGui.TextWrapped(GateReply(s.Gate) ?? "Not available.");
return;
}
ImGui.SameLine(0, 16);
Vector4 pill = s.Active ? colGreen : new(0.85f, 0.10f, 0.10f, 1f);
ImGui.PushStyleColor(ImGuiCol.Button, pill);
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, pill);
ImGui.PushStyleColor(ImGuiCol.ButtonActive, pill);
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.05f, 0.05f, 0.05f, 1f));
if (ImGui.SmallButton((s.Active ? " On " : " Off ") + "##vdactive"))
_ctx.Post(() => SetActive(!s.Active));
ImGui.PopStyleColor(4);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(s.Active
? "On: keeping this character in the chosen dungeon.\nClick: turn off."
: "Off: doing nothing.\nClick: turn on.");
ImGui.SameLine();
if (ImGui.SmallButton("Advanced##vdoptions")) _showAdvanced = !_showAdvanced;
ImGui.Separator();
float labelW = ImGui.CalcTextSize("Recall Gem").X + 12;
void Label(string text)
{
ImGui.AlignTextToFramePadding();
ImGui.TextColored(colLabel, text);
ImGui.SameLine(labelW);
}
// Status
var (statusWord, statusCol) = s.State switch
{
"in" => ("In Dungeon", colGreen),
"out" => ("Recalling", colAmber),
"portal" => ("Portal Space", colPurple),
"setup" => ("Setup Needed", colAmber),
"nogem" => ("No Gem", colRed),
"busy" => ("Waiting (busy)", colAmber),
_ => ("Not Running", colRed),
};
long since = s.State == "in" ? s.InSinceMs
: s.State == "out" ? s.OutSinceMs
: s.State == "portal" ? s.PortalSinceMs : 0;
string statusText = statusWord;
if (since > 0)
{
long secs = Math.Max(0, (s.NowMs - since) / 1000);
long h = secs / 3600, m = (secs / 60) % 60, sec = secs % 60;
statusText += h > 0 ? $" ({h}:{m:D2}:{sec:D2})" : $" ({m}:{sec:D2})";
}
Label("Status");
ImGui.TextColored(statusCol, statusText);
// Dungeon combo (0 = pick, 1..N = Dungeons[i-1])
Label("Dungeon");
string[] dungeonChoices = BuildDungeonChoices();
int dungeonIdx = s.Dungeon;
ImGui.SetNextItemWidth(260);
if (ImGui.Combo("##vddungeon", ref dungeonIdx, dungeonChoices, dungeonChoices.Length))
PostEdit(c => { c.Dungeon = dungeonIdx; });
Label("Recall Gem");
string[] gemChoices = { "Pick a gem", GemNames[0], GemNames[1] };
int gemIdx = s.Gem;
ImGui.SetNextItemWidth(260);
if (ImGui.Combo("##vdgem", ref gemIdx, gemChoices, gemChoices.Length))
PostEdit(c => { c.Gem = gemIdx; });
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Tie this gem to the dungeon's portal first.");
Label("Last Kill");
if (s.State == "in" && s.RealKillMs > 0)
ImGui.TextUnformatted($"{(s.NowMs - s.RealKillMs) / 1000} s ago");
else
ImGui.TextUnformatted("-");
Label("Session");
string perHour = s.DungeonSecs < 60 ? "-"
: Commas((long)(s.Kills * 3600.0 / Math.Max(1, s.DungeonSecs)));
ImGui.TextUnformatted($"{Commas(s.Kills)} kills ({perHour} Per Hour)");
if (s.QuitLeftMs is long left && s.QuitMinutes > 0)
{
float frac = (float)(left / (double)(s.QuitMinutes * 60_000L));
string barLabel = $"Kill Client ({left / 60_000}:{(left / 1000) % 60:D2})";
ImGui.ProgressBar(Math.Clamp(frac, 0f, 1f), new Vector2(-1, ImGui.GetTextLineHeight()), barLabel);
}
if (_showAdvanced)
{
ImGui.Separator();
ImGui.TextColored(colValue, "Advanced");
bool quit = s.Quit;
if (ImGui.Checkbox("Kill Client##vdquit", ref quit))
{
bool on = quit;
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.Quit = on;
_cfg.QuitMinutes = ClampInt(_cfg.QuitMinutes, QuitMin, QuitMax, 2);
_clockStartMs = Now();
_dirty = true;
Publish();
});
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip("No kill for the set minutes in the dungeon: /rc quit closes the client (once per run).\n"
+ "The timer restarts on the server's \"You've banked N Luminance.\" line, on your own killing blow,\n"
+ "and on a successful pet capture. Kills by pets or fellows that pay you no luminance\n"
+ "do NOT restart it, so keep the minutes generous if you hunt with pets.");
ImGui.SameLine();
ImGui.TextColored(colLabel, "after");
ImGui.SameLine();
if (ImGui.SmallButton($"{s.QuitMinutes} minute{(s.QuitMinutes == 1 ? "" : "s")}##vdmincycle"))
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, +1);
_clockStartMs = Now();
_dirty = true;
Publish();
});
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
_ctx.Post(() =>
{
if (!Allowed(out _)) return;
EnsureLoaded();
_cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, -1);
_clockStartMs = Now();
_dirty = true;
Publish();
});
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Minutes with no kill before Kill Client quits.\nClick: longer. Right-click: shorter. (1, 2, 5, 10, 15, 30)");
BoolRow("Auto Start On Arrival##vdautostart", s.AutoStart,
v => PostEdit(c => c.AutoStart = v),
"Switch On by itself when you arrive in the chosen dungeon (logging in there counts).");
BoolRow("Disable Meta##vdnometa", s.DisableMeta,
v => PostEdit(c => c.DisableMeta = v),
"On arriving: " + CmdMetaOff);
BoolRow("Disable Nav##vdnonav", s.DisableNav,
v => PostEdit(c => c.DisableNav = v),
"On arriving: " + CmdNavOff);
BoolRow("Repeat Attacks On##vdrepeat", s.RepeatAttack,
v => PostEdit(c => c.RepeatAttack = v),
"On arriving: " + CmdRepeatOn);
BoolRow("Set Attack Power##vdpower", s.SetPower,
v => PostEdit(c => c.SetPower = v),
"On arriving: " + CmdAttackBar + PowerText(s.AttackPower));
ImGui.SameLine();
int pi = PowerIndex(s.AttackPower);
if (ImGui.SmallButton(Powers[pi].Name + "##vdpowercycle"))
PostEdit(c => c.AttackPower = Powers[(pi + 1) % Powers.Length].Value);
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
PostEdit(c => c.AttackPower = Powers[(pi - 1 + Powers.Length) % Powers.Length].Value);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Fast (0), Medium (0.5) or Full Power (1).\nClick: next. Right-click: back.");
}
ImGui.Spacing();
ImGui.TextDisabled("Note: the client sees the landblock, not the layer - standing in the retail copy also counts as \"in it\".");
ImGui.TextDisabled("Kill Client: pet or fellow kills that pay you no luminance do not restart its timer.");
ImGui.TextDisabled("Recalls wait while RynthAi is in combat, buffing or waiting on the server.");
ImGui.TextDisabled("/ilt vaulted [on|off|toggle|status]");
}
private static void BoolRow(string id, bool value, Action<bool> set, string tip)
{
bool v = value;
if (ImGui.Checkbox(id, ref v)) set(v);
if (ImGui.IsItemHovered()) ImGui.SetTooltip(tip);
}
private static string[] BuildDungeonChoices()
{
var list = new string[Dungeons.Length + 1];
list[0] = "Pick a dungeon";
for (int i = 0; i < Dungeons.Length; i++) list[i + 1] = Dungeons[i].Name;
return list;
}
private static int StepPreset(int current, int dir)
{
if (dir > 0)
{
foreach (int m in QuitPresets) if (m > current) return m;
return QuitPresets[0];
}
for (int i = QuitPresets.Length - 1; i >= 0; i--)
if (QuitPresets[i] < current) return QuitPresets[i];
return QuitPresets[^1];
}
private static string Commas(long n)
{
string s = Math.Abs(n).ToString();
var chars = new List<char>();
for (int i = 0; i < s.Length; i++)
{
if (i > 0 && (s.Length - i) % 3 == 0) chars.Add(',');
chars.Add(s[i]);
}
return (n < 0 ? "-" : "") + new string(chars.ToArray());
}
// ── Config / snapshot types ─────────────────────────────────────────────
// internal (not private) so the source-generated IltVaultedDungeonsJsonContext can reach it.
internal sealed class Cfg
{
public bool Active { get; set; }
/// <summary>0 = none, 1..N = Dungeons index.</summary>
public int Dungeon { get; set; }
/// <summary>0 = none, 1 = primary, 2 = secondary.</summary>
public int Gem { get; set; }
public bool Quit { get; set; }
public int QuitMinutes { get; set; } = 2;
public bool ShowInDungeon { get; set; }
public bool AutoStart { get; set; }
public bool DisableMeta { get; set; }
public bool DisableNav { get; set; }
public bool RepeatAttack { get; set; }
public bool SetPower { get; set; }
public float AttackPower { get; set; }
}
private readonly record struct Snapshot(
bool Active, int Dungeon, int Gem, bool Quit, int QuitMinutes,
bool ShowInDungeon, bool AutoStart, bool DisableMeta, bool DisableNav,
bool RepeatAttack, bool SetPower, float AttackPower,
string State, long? QuitLeftMs, long IdleSecs, long InSinceMs, long OutSinceMs, long PortalSinceMs,
long RealKillMs, int Kills, long DungeonSecs, long NowMs, string Gate)
{
/// <summary>Before the first tick (the tab is only offered while the keeper may run).</summary>
public static Snapshot Empty => new(false, 0, 0, false, 2,
false, false, false, false, false, false, 0f,
"paused", null, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty);
}
}
// Source-generated JSON only: the NativeAOT build (what the installer ships) has reflection-based
// serialization turned off, so JsonSerializer.Deserialize<Cfg>(text, options) failed there and the
// Vaulted Dungeons settings never loaded or saved. Same file format as before (camelCase,
// indented, nulls left out, case-sensitive property names on read).
[JsonSerializable(typeof(IltVaultedDungeons.Cfg))]
[JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
internal partial class IltVaultedDungeonsJsonContext : JsonSerializerContext { }

View file

@ -123,6 +123,44 @@ internal sealed unsafe class RynthAiClient
}
}
// ── Vaulted Dungeons (master switch, activity) ──────────────────────────
/// <summary>
/// RynthAi's "Vaulted Dungeons" setting (Settings > Navigation): the master switch of the Vaulted
/// Dungeons keeper, and the only place it is stored. False when RynthAi isn't loaded, is older than
/// the call, hasn't logged in, or has it off (the default): the keeper then does nothing. Any thread.
/// </summary>
public bool VaultedDungeonsEnabled
{
get
{
var t = AnyThreadTable;
return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.VaultedDungeonsEnabledOffset)
&& t->VaultedDungeonsEnabled != null && t->VaultedDungeonsEnabled() != 0;
}
}
/// <summary>
/// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast
/// waiting on the server...); null when RynthAi isn't loaded or isn't ready. Resolved again every
/// call, as that interface requires (a RynthAi reload frees its table). Pump thread.
/// </summary>
public RynthAiActivity? Activity()
{
if (!_host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act == null || act->Version < 1 || act->StructSize < (uint)sizeof(RynthAiActivityApiV1) || act->GetActivityFlags == null) return null;
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
catch
{
return null; // a RynthAi mid-reload: not there this tick
}
}
// ── Quests (/myquests) ──────────────────────────────────────────────────
/// <summary>A /myquests flag from RynthAi's tracker (pump thread).</summary>

View file

@ -56,6 +56,10 @@
<!-- The two interfaces between RynthILT and RynthAi (linked into both plugins). -->
<Compile Include="..\Shared\RynthIltHubApi.cs" Link="Shared\RynthIltHubApi.cs" />
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<!-- "RynthAi.Activity": what the bot is doing (the Vaulted Dungeons keeper waits out combat and buffing). -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- The pet-capture success lines (shared with RynthAi's Pets tab): they count as a kill for Vaulted Dungeons' timer. -->
<Compile Include="..\Shared\PetCaptureLines.cs" Link="Shared\PetCaptureLines.cs" />
<!-- "RynthILT.Data": the charms list and bank balances for other plugins (DataInterface.cs). -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
<!-- RynthCore's server list (API v86): the ILT verdict the Hub follows (IltSettingsView/). -->

View file

@ -520,7 +520,11 @@ public sealed class RynthILTPlugin : RynthPluginBase
}
// The server's killer notification: this character landed the killing blow.
public override void OnKillNotification(string? deathMessage) => _bounties?.OnKill();
public override void OnKillNotification(string? deathMessage)
{
_bounties?.OnKill();
_hub?.OnKillNotification();
}
private void DrainTypedBounty()
{
@ -674,6 +678,15 @@ public sealed class RynthILTPlugin : RynthPluginBase
case "hub":
case "rates":
break;
case "vaulted":
case "vaulteddungeons":
{
// "/ilt vaulted [on|off|toggle|status]": the Vaulted Dungeons keeper (ILT only; the
// module answers "not available" elsewhere, and while the master switch is off).
if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; }
_hub.VaultedDungeons.HandleCommand(args);
return;
}
case "settings":
case "options":
{
@ -694,6 +707,7 @@ public sealed class RynthILTPlugin : RynthPluginBase
case "help":
ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list|<names>|default],");
ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),");
ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: RynthAi Settings > Navigation > Vaulted Dungeons, off by default),");
ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),");
ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),");
ChatLine("[RynthILT] /ilt trace <category|all|list> [on|off], /ilt debug [on|off].");

View file

@ -90,9 +90,12 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_vault = new VaultFeed(text => Host.InvokeChatParser(text));
_view = new InventoryView(_c);
// No bar button of its own: opened from the engine Inventory window's GInv button, the
// Scripts menu or /ginv.
_window = _ui.Add(new UiWindow("RynthInventory/Main", "Global Inventory")
{
DefaultWidth = 640f, DefaultHeight = 600f, MinWidth = 420f, MinHeight = 300f,
BarButton = false,
});
Host.Log($"[RynthInventory] {Version} initialized. /ginv opens the window. Files: {_c.Store.Root}");

View file

@ -143,6 +143,22 @@ internal sealed class Atlas
// ── Search ───────────────────────────────────────────────────────────────
/// <summary>
/// "a || b || c": the first candidate that is coordinates, or that names a place on the map as a
/// whole word or more (<see cref="MatchScore"/> 60+: "Mite Maze" yes, "Bur" inside "Burun" no),
/// so a loose candidate never picks an unrelated place. Null when none does.
/// </summary>
public string? FirstOnMap(string alternatives, bool hasPos, double ns, double ew)
{
foreach (string raw in alternatives.Split("||", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (NavCoords.TrySplitCoordsAndName(raw, out _, out _, out _)) return raw;
AtlasLocation? best = FindBest(raw, hasPos, ns, ew);
if (best != null && MatchScore(best.Name, raw) >= 60) return raw;
}
return null;
}
/// <summary>How well <paramref name="name"/> matches <paramref name="q"/> (lower case): 0 = not at all.</summary>
public static int MatchScore(string name, string q)
{

View file

@ -669,6 +669,25 @@ public sealed partial class RynthNavPlugin
return true;
}
/// <summary>
/// "a || b || c": the first candidate that is coordinates, or that names a place on the map
/// as a whole word or more (Atlas.MatchScore 60+: "Mite Maze" yes, "Bur" inside "Burun" no),
/// so a loose candidate never sends the character to an unrelated place. False (and why)
/// when none does.
/// </summary>
private bool PickAlternative(string text, out string picked, out string why)
{
why = "";
bool hasPos = PlayerMapPos(out double pns, out double pew);
picked = _atlas.FirstOnMap(text, hasPos, pns, pew) ?? "";
if (picked.Length > 0) return true;
// Coordinates are always taken, so here every candidate was a name.
why = _atlas.Locations.Count == 0
? "the Atlas isn't loaded (" + _atlasStatus + ")"
: "none of these is a place on the map: " + text.Replace("||", ",");
return false;
}
/// <summary>The Atlas place the last ResolveTarget picked (null for bare coordinates). Tick thread.</summary>
private AtlasLocation? _resolvedPlace;
@ -995,6 +1014,12 @@ public sealed partial class RynthNavPlugin
int sp = raw.IndexOf(' ');
string cmd = (sp < 0 ? raw : raw.Substring(0, sp)).ToLowerInvariant();
string rest = sp < 0 ? string.Empty : raw.Substring(sp + 1).Trim();
// "go a || b || c" (Oracle's Dynamic Stamps, any caller): the first candidate on the map.
if (cmd is "go" or "goto" or "route" or "arrow" && rest.Contains("||", StringComparison.Ordinal))
{
if (!PickAlternative(rest, out string picked, out string why)) { Note(why); return; }
rest = picked;
}
switch (cmd)
{
case "":

View file

@ -0,0 +1,41 @@
// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// The lines a click on a quest prints in chat. Upstream's quest list "thinks" them to the player:
/// the quest's info and hint text ("{flag}: {details}", or "{flag}: No hint available"), its wiki
/// link ("{flag}: No url available" when there is none), and the flag's own history
/// ("{flag}: {description} CompletedOn:... Solves:... MaxSolves:... RepeatTime:...", or
/// "{flag}: Never completed"). The texts come from the quest list's Info and Hint columns.
/// </summary>
internal static class QuestText
{
public static List<string> Lines(Quest q, QuestFlagStore flags, QuestBook book, DateTime utcNow)
{
string flag = q.Flag;
var lines = new List<string>();
string status = q.IsComplete(flags) ? q.Status(flags, utcNow) : "not done";
string name = q.IsNew ? (q.Name.Length > 0 ? q.Name : "Not in the quest list") : q.DisplayName;
lines.Add($"{name} ({flag}) - {status}");
string details = q.Details();
lines.Add(details.Length > 0 ? $"{flag}: {details}" : $"{flag}: No hint available");
lines.Add(q.Url.Length > 0 ? $"{flag}: {q.Url}" : $"{flag}: No url available");
lines.Add(History(flag, flags));
if (book.TryGetReward(flag, out QuestReward r)) lines.Add("Rewards: " + r.LongSummary());
return lines;
}
/// <summary>Upstream's QuestFlag.ToString(), or "Never completed" for a flag the character doesn't hold.</summary>
public static string History(string flag, QuestFlagStore flags)
{
if (!flags.TryGet(flag, out QuestFlag f)) return $"{flag}: Never completed";
string done = f.CompletedOnUtc == DateTime.MinValue ? "never" : f.CompletedOnUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
return $"{f.Key}: {f.Description} CompletedOn:{done} Solves:{f.Solves} MaxSolves:{f.MaxSolves} RepeatTime:{TimeText.Friendly(f.RepeatTime)}";
}
}

View file

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// Notices when a quest timer comes up. It remembers which watched quests were on cooldown and
/// reports each one once, the moment its timer runs out. A quest that is simply ready when first
/// seen (the login read) is not reported: only the step from waiting to ready is.
/// </summary>
internal sealed class QuestTimerWatcher
{
private readonly HashSet<string> _waiting = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _seen = new(StringComparer.OrdinalIgnoreCase);
private readonly List<Quest> _ready = new();
/// <summary>Forget everything (logout, or a different character).</summary>
public void Reset() => _waiting.Clear();
/// <summary>
/// Checks the watched quests and returns those whose timers came up since the last check (the
/// list is reused: read it before the next call). <paramref name="watch"/> is the flags to
/// watch, or null for every quest the character holds.
/// </summary>
public IReadOnlyList<Quest> Check(QuestFlagStore flags, QuestCatalog catalog, IEnumerable<string>? watch, DateTime utcNow)
{
_ready.Clear();
if (flags.LastReadUtc == DateTime.MinValue) return _ready;
_seen.Clear();
foreach (string flag in watch ?? flags.Flags.Keys)
{
_seen.Add(flag);
Quest q = catalog.TryGet(flag, out Quest known) ? known : new Quest { Flag = flag, IsNew = true };
if (!flags.TryGet(flag, out _)) { _waiting.Remove(flag); continue; }
QuestTimerState state = QuestTimer.State(q, flags, utcNow, out _);
if (state == QuestTimerState.Waiting) _waiting.Add(flag);
else if (state == QuestTimerState.Ready && _waiting.Remove(flag)) _ready.Add(q);
else _waiting.Remove(flag); // in progress, or done for good
}
_waiting.RemoveWhere(k => !_seen.Contains(k)); // no longer watched
return _ready;
}
}

View file

@ -12,6 +12,7 @@ internal sealed class OracleContext
public readonly OracleSettings Settings = new();
public readonly QuestFlagStore Flags = new();
public readonly QuestCatalog Catalog = new();
public readonly QuestTimerWatcher Timers = new();
public readonly QuestCatalogUpdater Updater = new();
/// <summary>This character's tracked quests and recorded rewards (loaded once the name is known).</summary>
public readonly QuestBook Book = new();
@ -42,8 +43,20 @@ internal sealed class OracleContext
/// <summary>The last thing the quest list check said, shown on the About tab.</summary>
public string UpdaterMessage = "";
/// <summary>Set by the plugin: sends /myquests (reply hidden when the setting says so).</summary>
public Action RequestQuests = () => { };
/// <summary>Set by the plugin: sends /myquests (reply hidden when the setting says so). False when nothing was sent (not in world, or one went out moments ago).</summary>
public Func<bool> RequestQuests = () => false;
/// <summary>Set by the plugin (the Refresh buttons): re-reads the character's stats and buffs, and RynthAi's session, at once.</summary>
public Action RereadCharacter = () => { };
/// <summary>Set by the plugin: re-reads the titles the engine holds for the character.</summary>
public Action RereadTitles = () => { };
/// <summary>Set by the plugin: reloads the quest list and server pack from their files and re-asks RynthCore which server this is.</summary>
public Action ReloadQuestList = () => { };
/// <summary>Where <see cref="Print"/> goes instead of the chat window (the offline tests).</summary>
public Action<string>? PrintSink = null;
/// <summary>Set by the plugin: sends a chat command to the server as if typed (the views' buttons).</summary>
public Func<string, bool> Send = _ => false;
@ -61,7 +74,14 @@ internal sealed class OracleContext
/// <summary>A line in the player's chat window only (nothing is sent to the server).</summary>
public void Print(string text)
{
if (PrintSink != null) { PrintSink(text); return; }
if (!Host.WriteToChat("[RynthOracle] " + text, 1))
Host.Log("[RynthOracle] " + text);
}
/// <summary>A click on a quest: its info and hint text, link and flag history in chat (upstream "thinks" them).</summary>
public void PrintQuest(Quest q)
{
foreach (string line in QuestText.Lines(q, Flags, Book, UtcNow)) Print(line);
}
}

View file

@ -29,6 +29,10 @@ internal sealed class OracleSettings
public string TabName = "Quests";
/// <summary>ConquestAC: "/bank deposit" at every ten-minute mark (upstream's auto-deposit; off by default).</summary>
public bool ConquestAutoDeposit;
/// <summary>Say so in chat when a tracked quest's timer comes up.</summary>
public bool AlertTimers = true;
/// <summary>false: only tracked quests are watched; true: every quest the character holds.</summary>
public bool AlertAllTimers;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json");
@ -48,6 +52,8 @@ internal sealed class OracleSettings
MainWindowOpen = Bool(r, "mainWindowOpen", MainWindowOpen);
QuestTimersOpen = Bool(r, "questTimersOpen", QuestTimersOpen);
ConquestAutoDeposit = Bool(r, "conquestAutoDeposit", ConquestAutoDeposit);
AlertTimers = Bool(r, "alertTimers", AlertTimers);
AlertAllTimers = Bool(r, "alertAllTimers", AlertAllTimers);
if (r.TryGetProperty("tabName", out JsonElement t) && t.ValueKind == JsonValueKind.String) TabName = t.GetString() ?? TabName;
if (r.TryGetProperty("lastQuestListCheck", out JsonElement c) && c.ValueKind == JsonValueKind.String
&& DateTime.TryParse(c.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime when))
@ -73,6 +79,8 @@ internal sealed class OracleSettings
sb.Append(" \"mainWindowOpen\": ").Append(MainWindowOpen ? "true" : "false").Append(",\n");
sb.Append(" \"questTimersOpen\": ").Append(QuestTimersOpen ? "true" : "false").Append(",\n");
sb.Append(" \"conquestAutoDeposit\": ").Append(ConquestAutoDeposit ? "true" : "false").Append(",\n");
sb.Append(" \"alertTimers\": ").Append(AlertTimers ? "true" : "false").Append(",\n");
sb.Append(" \"alertAllTimers\": ").Append(AlertAllTimers ? "true" : "false").Append(",\n");
sb.Append(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append("\"\n");
sb.Append("}\n");
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);

View file

@ -38,7 +38,7 @@ public static unsafe class PluginExports
public static IntPtr GetVersion()
{
// Keep in step with RynthOraclePlugin.Version (a u8 literal can't be built from a const string).
try { return LiteralPointer("0.2.1"u8); }
try { return LiteralPointer("0.2.2"u8); }
catch { return IntPtr.Zero; }
}

View file

@ -18,8 +18,8 @@ namespace RynthCore.Plugin.RynthOracle;
/// </summary>
public sealed class RynthOraclePlugin : RynthPluginBase
{
// Previous release: 0.2.0.
public const string Version = "0.2.1";
// Previous release: 0.2.1.
public const string Version = "0.2.2";
private const long QuestReadDelayMs = 6000; // after login, before the hidden /myquests
private const long CharacterReadMs = 1000;
@ -33,6 +33,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
private OracleView? _mainView;
private VoidView? _voidView;
private QuestTimersView? _timersView;
private SkillsEmbed? _skills;
private int _seenBookRevision = -1;
private readonly ConcurrentQueue<string> _commands = new();
@ -57,11 +58,16 @@ public sealed class RynthOraclePlugin : RynthPluginBase
_c.Host = Host;
_c.Settings.Load();
_c.RequestQuests = RequestQuests;
_c.RereadCharacter = RereadCharacter;
_c.RereadTitles = RereadTitles;
_c.ReloadQuestList = ReloadQuestList;
_c.Send = cmd => _c.InWorld && Host.InvokeChatParser(cmd);
_c.RunCommand = cmd => _c.InWorld && Host.InvokeChatParser(cmd);
_ui.Log = msg => Host.Log(msg);
_mainView = new OracleView(_c);
// The Skills / Attributes / Progress tabs: RynthCore draws its Skills panel body in the window.
_skills = new SkillsEmbed(cmd => Host.InvokeChatParser(cmd));
_voidView = new VoidView(_c);
_timersView = new QuestTimersView(_c);
_main = _ui.Add(new UiWindow("RynthOracle/Oracle", "Oracle")
@ -135,6 +141,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
if (_void != null) { _void.Visible = false; _void.NeedsPass = true; }
// The quest book loads once the character's name (and world) are known (TickData).
_c.Book.Clear();
_c.Timers.Reset();
if (_timers != null) { _timers.Visible = _c.Settings.QuestTimersOpen; _timers.NeedsPass = true; }
}
@ -146,8 +153,10 @@ public sealed class RynthOraclePlugin : RynthPluginBase
if (_main != null) { _main.Visible = false; _main.NeedsPass = true; }
if (_void != null) { _void.Visible = false; _void.NeedsPass = true; }
if (_timers != null) { _timers.Visible = false; _timers.NeedsPass = true; }
_skills?.Update(string.Empty, false, false, Environment.TickCount64);
_ui.SubmitEmpty(Host);
_c.Book.Clear(); // saved as it changed
_c.Timers.Reset();
_c.Flags.Clear();
_c.Void.Clear();
_c.Conquest.Clear();
@ -214,6 +223,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
public override void Shutdown()
{
_skills?.Shutdown();
_ui.SubmitEmpty(Host);
_c.Updater.Shutdown();
_c.Settings.Save();
@ -315,6 +325,21 @@ public sealed class RynthOraclePlugin : RynthPluginBase
// RynthAi, RynthILT and RynthCore's menus link here; it shows, never toggles off.
ShowTab(OracleView.TabCharacter);
break;
case "skills":
case "skill":
// The Skills tab: RynthCore's skills panel (raise and train) inside this window.
ShowTab(OracleView.TabSkills);
break;
case "attributes":
case "attrs":
case "attribute":
case "vitals":
ShowTab(OracleView.TabAttributes);
break;
case "progress":
case "progression":
ShowTab(OracleView.TabProgress);
break;
case "status":
string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : "";
string titles = _c.TitlesKnown ? $", {_c.EarnedTitles.Count} titles held" : "";
@ -327,12 +352,14 @@ public sealed class RynthOraclePlugin : RynthPluginBase
ShowTab(OracleView.TabAbout);
break;
default:
_c.Print("Commands: /ro (window), /ro character (Character tab: status, session), /ro void (Void window), "
_c.Print("Commands: /ro (window), /ro character (Character tab: status, session), "
+ "/ro skills|attributes|progress (those tabs), /ro void (Void window), "
+ "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), /ro quests (read quest flags), /ro status, "
+ "/ro about (About tab: settings, server)");
break;
}
if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char"
or "skills" or "skill" or "attributes" or "attrs" or "attribute" or "vitals" or "progress" or "progression"
or "about" && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
@ -340,11 +367,54 @@ public sealed class RynthOraclePlugin : RynthPluginBase
}
}
private void RequestQuests()
/// <summary>Sends /myquests; false when nothing went out (not in the world, or one was sent moments ago).</summary>
private bool RequestQuests()
{
if (!_c.InWorld) return false;
bool sent = _c.Flags.Request(cmd => Host.InvokeChatParser(cmd), Environment.TickCount64);
if (!sent) Host.Log("[RynthOracle] /myquests was sent moments ago; waiting for that reply.");
if (_main != null) _main.NeedsPass = true;
return sent;
}
// ── The Oracle window's Refresh buttons (the data side; Views\RefreshBar.cs has the rest) ──
/// <summary>Reads the character's stats, buffs and (on the Character tab) RynthAi's session now, not at the next timer.</summary>
private void RereadCharacter()
{
if (!_c.InWorld) return;
if (!_c.Flags.Request(cmd => Host.InvokeChatParser(cmd), Environment.TickCount64))
Host.Log("[RynthOracle] /myquests was sent moments ago; waiting for that reply.");
long now = Environment.TickCount64;
_c.Character.Read(Host);
_c.Void.RemoveExpired(now);
_nextCharacterReadMs = now + CharacterReadMs;
_nextCharacterExtrasMs = 0;
ReadCharacterExtras(now);
if (_main != null) _main.NeedsPass = true;
if (_void != null) _void.NeedsPass = true;
}
/// <summary>Asks the engine for the character's titles again (it keeps them from the login events).</summary>
private void RereadTitles()
{
_titleCount = -2;
ReadTitles();
if (_main != null) _main.NeedsPass = true;
}
/// <summary>
/// Reloads the quest list and the server's pack from their files (a downloaded list, or a pack
/// dropped into %APPDATA%\RynthCore\RynthOracle\packs) and asks RynthCore which server this is.
/// </summary>
private void ReloadQuestList()
{
long now = Environment.TickCount64;
_c.ServerState.Poll(Host, now, force: true);
_seenServerStateRevision = _c.ServerState.Revision;
_c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.ServerState.State);
try { _c.Catalog.Load(_c.Server.Tag, msg => Host.Log(msg)); }
catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); }
_c.Catalog.SyncDiscoveries(_c.Flags);
ApplyServer();
if (_main != null) _main.NeedsPass = true;
}
@ -362,6 +432,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase
TickData(now);
if (!Host.HasUi) return;
// After the poll, so a tab clicked this tick is already selected.
if (_skills != null && _main != null && _mainView != null)
_skills.Update(_mainView.Tab, _main.Visible, _c.InWorld, now);
RecordWindows(now);
_ui.Submit(Host, now);
@ -454,6 +527,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
_c.Server.Refresh(Host, _c.Character.PlayerId, _c.ServerState.State);
ApplyServer();
LoadQuestBook(now);
AnnounceTimers();
ReadTitles();
TickConquest(now);
if (!_voidAutoDecided && _c.Character.Valid)
@ -475,6 +549,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase
}
}
/// <summary>Says in chat which watched quest timers came up: tracked quests, or every held quest if so set.</summary>
private void AnnounceTimers()
{
if (!_c.Settings.AlertTimers || !_c.Book.Loaded) { _c.Timers.Reset(); return; }
var ready = _c.Timers.Check(_c.Flags, _c.Catalog, _c.Settings.AlertAllTimers ? null : _c.Book.Tracked, _c.UtcNow);
foreach (Quest q in ready)
_c.Print($"Quest ready again: {q.Label}");
}
/// <summary>
/// Loads this character's quest book (tracked quests, rewards) once the name is known and the
/// world has been announced, or after <see cref="BookWorldWaitMs"/> without one (then filed

View file

@ -21,6 +21,9 @@ internal sealed partial class OracleView
w.Checkbox("Hide the replies to RynthOracle's own requests", "o.hide", s.HideOwnQuestReplies, v => { s.HideOwnQuestReplies = v; s.Save(); });
w.Tooltip("/myquests, and on their servers /b, /augs, /top and the like. A command you type yourself always shows its reply.");
w.Checkbox("Show the Void window for characters with Void Magic", "o.void", s.AutoShowVoidWindow, v => { s.AutoShowVoidWindow = v; s.Save(); });
w.Checkbox("Say in chat when a quest timer comes up", "o.alert", s.AlertTimers, v => { s.AlertTimers = v; s.Save(); });
w.Tooltip("Watches the quests you track (the * on the Quests tab) and prints a line the moment a cooldown ends.");
w.Checkbox("...for every quest you hold, not just tracked ones", "o.alertall", s.AlertAllTimers, v => { s.AlertAllTimers = v; s.Save(); });
w.Checkbox("Check once a day for a newer quest list", "o.daily", s.CheckQuestListDaily, v => { s.CheckQuestListDaily = v; s.Save(); });
w.Tooltip("Downloads Oracle of Dereth's master quest list from GitHub, as the original plugin does.");
@ -64,6 +67,7 @@ internal sealed partial class OracleView
w.SeparatorText("Commands");
w.BulletText("/ro open or close this window");
w.BulletText("/ro character the Character tab (status, session)");
w.BulletText("/ro skills the Skills tab (raise and train); /ro attributes, /ro progress likewise");
w.BulletText("/ro timers open or close the Quest Timers window");
w.BulletText("/ro fellowship the Fellowship tab");
w.BulletText("/ro about this tab (settings, server)");

View file

@ -34,9 +34,6 @@ internal sealed partial class OracleView
w.ToggleButton(cq.Boards[i].Label, "cb.tab." + i, i == _conquestBoard, () => _conquestBoard = index, small: true);
}
ConquestBoard b = cq.Boards[_conquestBoard];
w.Button("Refresh", "cb.refresh", () => _c.Send(cq.RequestBoard(b, _c.NowMs)));
w.Tooltip($"Sends {b.Command} and reads the reply.");
w.SameLine();
w.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}");
if (b.You != null) w.Text($"You: #{b.You.Rank} with {b.You.Value}");
DrawRows(w, "cb.rows", b.Rows);
@ -76,8 +73,6 @@ internal sealed partial class OracleView
if (_aelrynthView == 1)
{
w.Button("Refresh", "ab.me", () => _c.Send(a.RequestTop("me", _c.NowMs)));
w.Tooltip("Sends /top me.");
w.BeginChild("ab.melist", 0f, 0f, border: true);
foreach (AelrynthStanding s in a.Standings)
{
@ -93,9 +88,6 @@ internal sealed partial class OracleView
if (_aelrynthView == 2)
{
w.Button("Refresh", "ab.trials", () => _c.Send(a.RequestTrial("", _c.NowMs)));
w.Tooltip("Sends /trial.");
w.SameLine();
w.InputText("Dungeon", "ab.trialarg", _trialArg, 48, s => _trialArg = s);
w.SameLine();
w.Button("Top 10", "ab.trialtop", () => { if (_trialArg.Trim().Length > 0) _c.Send(a.RequestTrial(_trialArg, _c.NowMs)); });

View file

@ -44,9 +44,6 @@ internal sealed partial class OracleView
private void DrawConquestBank(UiWindow w)
{
ConquestData cq = _c.Conquest;
w.Button("Refresh", "cq.bank.refresh", () => _c.Send(cq.RequestBank(_c.NowMs)));
w.Tooltip("Sends /b and reads your balances.");
w.SameLine();
w.TextDisabled(ReadAt(cq.BankUtc));
foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase))
{
@ -90,9 +87,6 @@ internal sealed partial class OracleView
private void DrawConquestAugs(UiWindow w)
{
ConquestData cq = _c.Conquest;
w.Button("Refresh", "cq.augs.refresh", () => _c.Send(cq.RequestAugs(_c.NowMs)));
w.Tooltip("Sends /augs.");
w.SameLine();
w.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total");
w.TextDisabled("Aug"); w.SameLine(120f); w.TextDisabled("Have"); w.SameLine(170f); w.TextDisabled("Next costs"); w.SameLine(330f); w.TextDisabled("Effect now");
foreach (ConquestAug a in cq.Augs)
@ -111,9 +105,6 @@ internal sealed partial class OracleView
private void DrawConquestEnl(UiWindow w)
{
ConquestData cq = _c.Conquest;
w.Button("Refresh", "cq.enl.refresh", () => _c.Send(cq.RequestEnl(_c.NowMs)));
w.Tooltip("Sends /enl augs.");
w.SameLine();
w.TextDisabled(ReadAt(cq.EnlUtc));
foreach (NamedValue a in cq.EnlAugs)
{
@ -157,9 +148,6 @@ internal sealed partial class OracleView
w.Text($"Next costs {TimeText.Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance");
w.SeparatorText("Experience bonuses");
w.Button("Refresh", "cq.bonus.refresh", () => _c.Send(cq.RequestBonus(_c.NowMs)));
w.Tooltip("Sends /bonus.");
w.SameLine();
w.TextDisabled(ReadAt(cq.BonusUtc));
foreach (NamedValue b in cq.Bonuses)
{
@ -172,9 +160,6 @@ internal sealed partial class OracleView
private void DrawConquestFships(UiWindow w)
{
ConquestData cq = _c.Conquest;
w.Button("Refresh", "cq.fship.refresh", () => _c.Send(cq.RequestFships(_c.NowMs)));
w.Tooltip("Sends /fship list.");
w.SameLine();
w.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members");
w.Combo("Sort", "cq.fship.sort", _fshipSort, new[] { "Name", "Leader", "Most members", "Location" }, i => _fshipSort = i);
var list = _fshipSort switch

View file

@ -9,12 +9,18 @@ namespace RynthCore.Plugin.RynthOracle.Views;
/// </summary>
internal sealed partial class OracleView
{
public const string TabQuests = "Quests", TabCharacter = "Character", TabAugs = "Augs", TabSociety = "Society",
public const string TabQuests = "Quests", TabCharacter = "Character",
TabSkills = "Skills", TabAttributes = "Attributes", TabProgress = "Progress",
TabAugs = "Augs", TabSociety = "Society",
TabMarkers = "Markers", TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship",
TabBoards = "Leaderboards", TabConquest = "Conquest", TabAbout = "About";
/// <summary>A tab: shown where any of its server tags matches the server; no tags = everywhere (retail).</summary>
private sealed record TabDef(string Name, string[] Servers, Action<UiWindow> Draw, bool LiveTimers);
/// <summary>
/// A tab: shown where any of its server tags matches the server; no tags = everywhere (retail).
/// Refresh is the page's Refresh button (Views\RefreshBar.cs); Help its tooltip.
/// </summary>
private sealed record TabDef(string Name, string[] Servers, Action<UiWindow> Draw, bool LiveTimers,
Func<RefreshResult> Refresh, Func<string> Help);
private readonly OracleContext _c;
private readonly TabDef[] _tabs;
@ -29,18 +35,35 @@ internal sealed partial class OracleView
string[] any = Array.Empty<string>();
_tabs = new TabDef[]
{
new(TabQuests, any, DrawQuests, true),
new(TabCharacter, any, DrawCharacter, true),
new(TabAugs, any, DrawAugs, true),
new(TabSociety, any, DrawSociety, true),
new(TabMarkers, any, DrawMarkers, false),
new(TabTitles, any, DrawTitles, false),
new(TabVoid, any, DrawVoid, true),
new(TabFellowship, any, DrawFellowship, false),
new(TabQuests, any, DrawQuests, true, () => RefreshQuests(),
() => "Sends /myquests to the server and reads the reply."),
new(TabCharacter, any, DrawCharacter, true, RefreshCharacter,
() => "Re-reads your level, experience, buffs and skills from the game now (and RynthAi's session)."),
// Skills / Attributes / Progress: RynthCore draws its Skills panel body under the tab
// strip (SkillsEmbed). The engine's panel reads the game itself, so there is no Refresh row.
new(TabSkills, any, DrawEmbedded, false, RefreshCharacter,
() => "RynthCore's skills panel: raise and train skills."),
new(TabAttributes, any, DrawEmbedded, false, RefreshCharacter,
() => "RynthCore's skills panel: attributes and vitals."),
new(TabProgress, any, DrawEmbedded, false, RefreshCharacter,
() => "RynthCore's skills panel: progression planners (Infinite Leaftide)."),
new(TabAugs, any, DrawAugs, true, RefreshCharacterAndQuests,
() => "Re-reads your character from the game and sends /myquests for the gem timers."),
new(TabSociety, any, DrawSociety, true, RefreshCharacterAndQuests,
() => "Re-reads your society standing from the game and sends /myquests for today's ribbons and quest timers."),
new(TabMarkers, any, DrawMarkers, false, () => RefreshQuests(),
() => "Sends /myquests: the markers you found are in your quest flags."),
new(TabTitles, any, DrawTitles, false, RefreshTitles,
() => "Re-reads the titles you hold from the game."),
new(TabVoid, any, DrawVoid, true, RefreshVoid,
() => "Re-reads your buffs from the game and drops the spell timers that ran out."),
new(TabFellowship, any, DrawFellowship, false, RefreshFellowship,
() => "Re-reads the fellowship and its members from the game."),
// Server-specific: each parser and its commands only exist on its own server.
new(TabBoards, new[] { Data.ServerTags.Conquest, Data.ServerTags.Aelrynth }, DrawBoards, false),
new(TabConquest, new[] { Data.ServerTags.Conquest }, DrawConquest, true),
new(TabAbout, any, DrawAbout, false),
new(TabBoards, new[] { Data.ServerTags.Conquest, Data.ServerTags.Aelrynth }, DrawBoards, false, RefreshBoards, BoardsHelp),
new(TabConquest, new[] { Data.ServerTags.Conquest }, DrawConquest, true, RefreshConquest, ConquestHelp),
new(TabAbout, any, DrawAbout, false, RefreshAbout,
() => "Loads the quest list and server pack from their files again and asks RynthCore which server this is."),
};
}
@ -103,11 +126,20 @@ internal sealed partial class OracleView
return;
}
// Skills / Attributes / Progress: nothing more is recorded. The rest of the window is
// the region RynthCore fills with its Skills panel body (see SkillsEmbed), so the page
// has no Refresh row and no child of its own to cover it.
if (SkillsEmbed.IsEmbedTab(tab)) return;
if (current != null) DrawRefreshRow(w, current);
w.BeginChild("page." + tab, 0f, 0f, border: false);
(current?.Draw ?? DrawAbout)(w);
w.EndChild();
}
/// <summary>The Skills-family tabs record nothing: <see cref="Draw"/> returns before it would call this.</summary>
private void DrawEmbedded(UiWindow w) { }
// ── Shared helpers ──────────────────────────────────────────────────────
/// <summary>"Done" in green or "--" in grey, the status column most lists start with.</summary>
@ -125,7 +157,7 @@ internal sealed partial class OracleView
w.Text(value);
}
/// <summary>Prints a quest's name, status, notes and wiki link in chat (upstream "thinks" them).</summary>
/// <summary>Prints an entry's name, status, notes and wiki link in chat (upstream "thinks" them). Quests print more: <see cref="OracleContext.PrintQuest"/>.</summary>
private void PrintEntry(string name, string flag, string status, string details, string url)
{
_c.Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name);

View file

@ -54,9 +54,10 @@ internal sealed class QuestTimersView
foreach (Quest q in _rows)
{
string flag = q.Flag;
w.Text(Cut(q.Label, 26));
Quest row = q;
w.Selectable(Cut(q.Label, 26), "qt.r." + flag, false, () => _c.PrintQuest(row), StatusX - 10f);
string reward = _c.Book.RewardText(flag);
w.Tooltip(reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}");
w.Tooltip((reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}") + "\nClick: prints its texts in chat.");
w.SameLine(StatusX);
QuestTimerState s = QuestTimer.State(q, flags, now, out string text);
bool held = flags.TryGet(flag, out _);
@ -74,7 +75,7 @@ internal sealed class QuestTimersView
if (flags.Loading) w.TextColored(UiColors.Yellow, "Reading quest flags...");
else if (flags.LastReadUtc == DateTime.MinValue) w.TextDisabled("Quest flags not read yet.");
w.SmallButton("Refresh", "qt.refresh", _c.RequestQuests);
w.SmallButton("Refresh", "qt.refresh", () => _c.RequestQuests());
w.Tooltip("Sends /myquests and reads the reply (timers count down by themselves between reads).");
if (flags.LastReadUtc != DateTime.MinValue)
{

View file

@ -51,9 +51,6 @@ internal sealed partial class OracleView
else
w.Text($"{flags.Flags.Count} quest flags on this character, read at {flags.LastReadUtc.ToLocalTime():HH:mm}.");
w.Button("Refresh", "q.refresh", _c.RequestQuests);
w.Tooltip("Sends /myquests to the server and reads the reply.");
w.SameLine();
bool timersShown = _c.QuestTimersWindowVisible();
w.Button(timersShown ? "Hide quest timers" : "Show quest timers", "q.timers", () => _c.SetQuestTimersWindow(!timersShown));
w.Tooltip("A small window with the quests you track (the * column) and the time left on each.");
@ -125,7 +122,7 @@ internal sealed partial class OracleView
w.SameLine(72f);
Quest row = q;
w.Selectable(Cut(q.Label, 44), "q.r." + flag, flag == _questSel, () => SelectQuest(row), 290f);
w.Tooltip(flag);
w.Tooltip(flag + "\nClick: opens it below and prints its texts in chat.");
w.SameLine(370f);
TimerText(w, q, flags, now, done);
string solves = q.SolvesText(flags);
@ -163,9 +160,14 @@ internal sealed partial class OracleView
// ── The opened quest and its rewards ──────────────────────────────────
/// <summary>
/// A click opens the quest below the list (a second click closes it) and, as upstream's list
/// does, prints its texts in chat: the info and hint, the wiki link and the flag's history.
/// </summary>
private void SelectQuest(Quest q)
{
if (_questSel == q.Flag) { _questSel = ""; return; } // a second click closes it
_c.PrintQuest(q);
if (_questSel == q.Flag) { _questSel = ""; return; }
_questSel = q.Flag;
_rewardMsg = "";
LoadRewardEdit(q.Flag);
@ -208,7 +210,7 @@ internal sealed partial class OracleView
w.Tooltip("List this quest in the Quest Timers window.");
w.SameLine();
Quest print = q;
w.Button("Print in chat", "q.sel.print", () => PrintQuest(print));
w.Button("Print in chat", "q.sel.print", () => _c.PrintQuest(print));
w.SameLine();
w.Button("Close", "q.sel.close", () => _questSel = "");
@ -272,13 +274,6 @@ internal sealed partial class OracleView
_rewardMsg = r.IsEmpty ? "Cleared." : "Saved: " + r.ShortSummary();
}
private void PrintQuest(Quest q)
{
string status = q.IsComplete(_c.Flags) ? q.Status(_c.Flags, _c.UtcNow) : "not done";
PrintEntry(q.IsNew ? (q.Name.Length > 0 ? q.Name : "Not in the quest list") : q.DisplayName, q.Flag, status, q.Details(), q.Url);
if (_c.Book.TryGetReward(q.Flag, out QuestReward r)) _c.Print("Rewards: " + r.LongSummary());
}
// ── Rows ──────────────────────────────────────────────────────────────
/// <summary>The filtered, sorted rows; rebuilt when the filter or data changed (or every 5 s for timers).</summary>

View file

@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.RynthOracle.Ui;
namespace RynthCore.Plugin.RynthOracle.Views;
/// <summary>
/// The Refresh button every page of the Oracle window starts with, and the status line beside it.
/// What "refresh" means depends on where a page's data comes from:
/// - data the server owns (quest flags, ConquestAC's bank and boards, Aelrynth's /top and /trial)
/// is asked for again with the same command the page always used, and the line waits for the
/// reply;
/// - data read from the game client (level, buffs, titles, fellowship) is re-read at once instead
/// of at the next timer;
/// - files (the About page) are loaded again.
/// A page that needs both does both. Nothing here blocks: a request is one chat command, and the
/// same request is refused for <see cref="CooldownMs"/> after it went out (the quest read has its
/// own 5 s gap), so the button can't spam the server.
/// </summary>
internal sealed partial class OracleView
{
private const long CooldownMs = 3000;
private const long ReplyWaitMs = 15_000;
/// <summary>What a Refresh did, and (when it asked the server) how to tell the reply has landed.</summary>
private sealed record RefreshResult(string What, Func<bool>? Done = null);
private string _refreshScope = "", _refreshWhat = "";
private Func<bool>? _refreshDone;
private bool _refreshDoneSeen;
private long _refreshAtMs;
private DateTime _refreshAtUtc, _refreshDoneUtc;
private readonly Dictionary<string, long> _refreshSent = new();
/// <summary>The tab, plus the sub-page a tab has (Conquest's views, the boards), so a status line stays with its own page.</summary>
private string RefreshScope(string tab) => tab switch
{
TabConquest => tab + _conquestView,
TabBoards => tab + _aelrynthView + _conquestBoard,
_ => tab,
};
private void DrawRefreshRow(UiWindow w, TabDef def)
{
string scope = RefreshScope(def.Name);
w.Button("Refresh", "refresh." + scope, () => DoRefresh(def, scope), small: true);
w.Tooltip(def.Help());
if (_refreshScope != scope || _refreshWhat.Length == 0) return;
w.SameLine();
if (_refreshDone != null && !_refreshDoneSeen && _refreshDone())
{
_refreshDoneSeen = true;
_refreshDoneUtc = _c.UtcNow;
}
if (_refreshDone != null && !_refreshDoneSeen)
{
if (_c.NowMs - _refreshAtMs > ReplyWaitMs) w.TextColored(UiColors.Red, "No reply yet. Press Refresh to ask again.");
else w.TextColored(UiColors.Yellow, _refreshWhat + " Waiting for the reply...");
}
else if (_refreshDone != null)
w.TextDisabled($"Updated {_refreshDoneUtc.ToLocalTime():HH:mm:ss}. {_refreshWhat}");
else
w.TextDisabled($"Refreshed {_refreshAtUtc.ToLocalTime():HH:mm:ss}. {_refreshWhat}");
}
private void DoRefresh(TabDef def, string scope)
{
RefreshResult r;
try { r = def.Refresh(); }
catch (Exception ex) { r = new RefreshResult("Couldn't refresh: " + ex.Message); }
_refreshScope = scope;
_refreshWhat = r.What;
_refreshDone = r.Done;
_refreshDoneSeen = false;
_refreshAtMs = _c.NowMs;
_refreshAtUtc = _c.UtcNow;
}
// ── What each page's Refresh does ───────────────────────────────────────
/// <summary>The same request twice within <see cref="CooldownMs"/> is refused.</summary>
private bool CoolingDown(string key)
{
if (_refreshSent.TryGetValue(key, out long t) && _c.NowMs - t < CooldownMs) return true;
_refreshSent[key] = _c.NowMs;
return false;
}
private const string TooSoon = "That was just asked for; wait a few seconds before asking again.";
/// <summary>Sends one chat command (the page's own) and waits for <paramref name="state"/> to change.</summary>
private RefreshResult Ask(string key, Func<long> state, Func<string> command)
{
if (CoolingDown(key)) return new RefreshResult(TooSoon);
long before = state();
string cmd = command();
if (!_c.Send(cmd)) return new RefreshResult($"Couldn't send {cmd} (not in the world).");
return new RefreshResult($"Sent {cmd}.", () => state() != before);
}
/// <summary>/myquests (refused for 5 s after the last one); the line waits for the new flags.</summary>
private RefreshResult RefreshQuests(string before = "")
{
QuestFlagStore f = _c.Flags;
int rev = f.Revision;
if (_c.RequestQuests()) return new RefreshResult(before + "Asked the server for your quest flags (/myquests).", () => f.Revision != rev);
if (f.Loading) return new RefreshResult(before + "Your quest flags are already being read.", () => f.Revision != rev);
return new RefreshResult(before + "Your quest flags were asked for a moment ago; wait a few seconds before asking again.");
}
private RefreshResult RefreshCharacter()
{
_c.RereadCharacter();
return new RefreshResult("Re-read your level, experience, buffs and skills from the game.");
}
/// <summary>Pages built from the character's properties and the quest flags: both are read again.</summary>
private RefreshResult RefreshCharacterAndQuests()
{
_c.RereadCharacter();
return RefreshQuests("Re-read your character from the game. ");
}
private RefreshResult RefreshTitles()
{
_c.RereadTitles();
return new RefreshResult(_c.TitlesKnown
? $"Re-read your titles from the game: {_c.EarnedTitles.Count} held."
: "The game hasn't sent this character's titles yet (they arrive at login).");
}
private RefreshResult RefreshVoid()
{
_c.RereadCharacter();
return new RefreshResult("Re-read your buffs and dropped the spell timers that ran out. Timers on targets are learned from your casts.");
}
private RefreshResult RefreshFellowship()
{
_c.Fellowship.Invalidate();
return new RefreshResult("Re-read the fellowship from the game.");
}
private RefreshResult RefreshAbout()
{
if (CoolingDown("about")) return new RefreshResult(TooSoon);
_c.ReloadQuestList();
QuestCatalog cat = _c.Catalog;
string pack = cat.PackServer.Length > 0 ? $" + {cat.ServerCount} {cat.PackServer}" : "";
return new RefreshResult($"Reloaded the quest list ({cat.RetailCount} retail{pack}) and asked RynthCore which server this is.");
}
private RefreshResult RefreshBoards()
{
if (_c.Server.Is(ServerTags.Conquest))
{
ConquestData cq = _c.Conquest;
ConquestBoard b = cq.Boards[Math.Clamp(_conquestBoard, 0, cq.Boards.Count - 1)];
return Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, () => cq.RequestBoard(b, _c.NowMs));
}
AelrynthBoards a = _c.Boards;
return _aelrynthView switch
{
1 => Ask("top me", () => a.Revision, () => a.RequestTop("me", _c.NowMs)),
2 => Ask("trial", () => a.Revision, () => a.RequestTrial("", _c.NowMs)),
_ => Ask("top " + _aelrynthBoardArg, () => a.Revision,
() => a.RequestTop(a.BoardTitle.Length > 0 ? _aelrynthBoardArg : "", _c.NowMs)),
};
}
private string BoardsHelp()
{
if (_c.Server.Is(ServerTags.Conquest))
{
ConquestBoard b = _c.Conquest.Boards[Math.Clamp(_conquestBoard, 0, _c.Conquest.Boards.Count - 1)];
return $"Sends {b.Command} and reads the reply.";
}
return _aelrynthView switch
{
1 => "Sends /top me and reads the reply.",
2 => "Sends /trial and reads the dungeon list.",
_ => "Sends /top (every board's leader), or asks again for the board that is open.",
};
}
private RefreshResult RefreshConquest()
{
ConquestData cq = _c.Conquest;
switch (_conquestView)
{
case 0: return Ask("bank", () => cq.BankUtc.Ticks, () => cq.RequestBank(_c.NowMs));
case 1: return Ask("augs", () => cq.AugsUtc.Ticks, () => cq.RequestAugs(_c.NowMs));
case 2: return Ask("enl", () => cq.EnlUtc.Ticks, () => cq.RequestEnl(_c.NowMs));
case 3:
_c.RereadCharacter();
return Ask("bonus", () => cq.BonusUtc.Ticks, () => cq.RequestBonus(_c.NowMs));
case 4: return Ask("fship", () => cq.FshipUtc.Ticks, () => cq.RequestFships(_c.NowMs));
default: return RefreshQuests();
}
}
private string ConquestHelp() => _conquestView switch
{
0 => "Sends /b and reads your balances.",
1 => "Sends /augs and reads your advanced augmentations.",
2 => "Sends /enl augs and reads your enlightenment augmentations.",
3 => "Re-reads your level, and sends /bonus for the experience bonuses.",
4 => "Sends /fship list and reads the fellowships looking for members.",
_ => "Sends /myquests: the custom quests' status comes from your quest flags.",
};
}

View file

@ -0,0 +1,90 @@
using System;
namespace RynthCore.Plugin.RynthOracle.Views;
/// <summary>
/// The Skills, Attributes and Progress tabs have no page of their own: RynthCore draws its Skills
/// panel body (raise and train, attributes and vitals, the ILT planners) into the Oracle window,
/// below the tab strip. This class is the plugin's half of that hand-off. It tells the engine
/// which body to draw with "/rc oracle-skills skills|attrs|progress" and to stop with
/// "/rc oracle-skills off".
///
/// It is a small state machine over what the engine was last told, so a command goes out only
/// when the wanted mode changes: never once per frame or per recorded pass. The first command,
/// once a character is in the world, is sent whatever the mode (usually "off"): the engine takes
/// any "/rc oracle-skills" as Oracle announcing that it has these tabs, and only then points the
/// bar's Skills icon and "/rc skills" at them instead of its standalone Skills panel.
/// </summary>
internal sealed class SkillsEmbed
{
/// <summary>The engine's word for "no embedded Skills body".</summary>
public const string Off = "off";
/// <summary>A failed send is tried again no sooner than this.</summary>
public const long RetryMs = 1000;
private readonly Func<string, bool> _send;
private string? _sent; // null until the first command has gone out (the engine knows nothing of us yet)
private long _retryAtMs;
/// <param name="send">Runs a chat command through the engine; false when it didn't go out.</param>
public SkillsEmbed(Func<string, bool> send) => _send = send;
/// <summary>What the engine was last told (and accepted): "skills", "attrs", "progress" or "off"; "off" before any command.</summary>
public string Sent => _sent ?? Off;
/// <summary>True once the engine has been sent a command (it then knows Oracle has these tabs).</summary>
public bool Announced => _sent != null;
/// <summary>The engine mode for an Oracle tab, or null when the tab isn't one of the three.</summary>
public static string? ModeFor(string tab) => tab switch
{
OracleView.TabSkills => "skills",
OracleView.TabAttributes => "attrs",
OracleView.TabProgress => "progress",
_ => null,
};
/// <summary>True for the tabs whose page is drawn by the engine.</summary>
public static bool IsEmbedTab(string tab) => ModeFor(tab) != null;
/// <summary>
/// The mode the engine should be in: the selected tab's while the Oracle window is showing and
/// a character is in the world, otherwise off.
/// </summary>
public static string Wanted(string tab, bool windowVisible, bool inWorld) =>
windowVisible && inWorld ? ModeFor(tab) ?? Off : Off;
/// <summary>
/// Sends the command for the wanted mode if it differs from the last one sent (the first
/// command waits for the world). Returns true when a command went out. A refused send leaves
/// the state as it was and is retried after <see cref="RetryMs"/>.
/// </summary>
public bool Update(string tab, bool windowVisible, bool inWorld, long nowMs)
{
if (_sent == null && !inWorld) return false;
string want = Wanted(tab, windowVisible, inWorld);
if (want == _sent || nowMs < _retryAtMs) return false;
if (!_send("/rc oracle-skills " + want))
{
_retryAtMs = nowMs + RetryMs;
return false;
}
_sent = want;
return true;
}
/// <summary>
/// Unload: leave the engine with no embedded body, whatever was shown. One attempt; nothing is
/// kept to retry. Returns true when a command went out.
/// </summary>
public bool Shutdown()
{
if (_sent == null || _sent == Off) return false;
bool ok;
try { ok = _send("/rc oracle-skills " + Off); }
catch { ok = false; }
if (ok) _sent = Off;
return ok;
}
}

View file

@ -66,6 +66,21 @@ public static unsafe class PluginExports
try { if (utf8 != IntPtr.Zero) Runtime.Plugin?.EnqueueCommand(Marshal.PtrToStringUTF8(utf8)); } catch { }
}
// Commands from other plugins (host SendPluginCommand): action "rsort", value an /rsort
// command without the "/rsort" ("now", "status"); RynthAi sends ub-IT's /ub packsort this way.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(actionAnsi) ?? "" : "";
string value = valueAnsi != IntPtr.Zero ? Marshal.PtrToStringAnsi(valueAnsi) ?? "" : "";
string? arg = RynthSortPlugin.RemoteSortArgument(action, value);
if (arg != null) Runtime.Plugin?.EnqueueCommand(arg);
}
catch { }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
}

View file

@ -60,6 +60,13 @@ public sealed class RynthSortPlugin : RynthPluginBase
/// <summary>For the engine's dashboard toggle (RynthSortAutoState): -1 not logged in yet, 0 auto-sort off, 1 on. Any thread.</summary>
public int AutoState => _autoState;
/// <summary>
/// A command from another plugin (RynthPluginApplyRemoteCommand): the /rsort argument when
/// <paramref name="action"/> is "rsort" (value "now", "status"...), else null (not ours).
/// </summary>
internal static string? RemoteSortArgument(string? action, string? value)
=> string.Equals(action, "rsort", StringComparison.OrdinalIgnoreCase) ? value ?? string.Empty : null;
/// <summary>An /rsort command from the engine (RynthSortCommand), without "/rsort". Any thread; runs on the tick.</summary>
public void EnqueueCommand(string? arg)
{
@ -77,9 +84,12 @@ public sealed class RynthSortPlugin : RynthPluginBase
Warnings = () => _warnings,
Character = () => _identityKnown ? _character : string.Empty,
};
// No bar button of its own: opened from the engine Inventory window's Sort button, the
// Scripts menu or /rsort.
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
{
DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f,
BarButton = false,
});
Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}");
return 0;

View file

@ -197,7 +197,8 @@ internal static class ActionPacer
_gapEnd = 0;
_gapLen = 0;
_errorAnswers.Clear();
_staleDrops = _latchExpiries = _burstHolds = 0;
_staleDrops = _latchExpiries = _burstHolds = _emergencyThroughLatch = 0;
_healWaitAt = 0;
}
}
@ -381,8 +382,10 @@ internal static class ActionPacer
bool animationGate = true, bool settleGate = true, bool attackRepeat = false)
{
if (!Enabled) { why = ""; return true; }
if (ServerBusyHolds(host, who, attackRepeat, out why, healStart: heal != HealNeed.None)) return false;
if (settleGate && MoveAudit.SettleHolds(host, out why))
if (ServerBusyHolds(host, who, attackRepeat, out why, heal)) return false;
// An emergency heal does not wait for the movement settle (150-600 ms): at Emergency Heal At
// the heal comes first; it still obeys the in-flight rules below (OutstandingAllows, GestureHolds).
if (settleGate && heal != HealNeed.Emergency && MoveAudit.SettleHolds(host, out why))
{
bool log;
lock (Gate) { _settleHolds++; log = _settleLogged.Add(who); }
@ -662,7 +665,11 @@ internal static class ActionPacer
private static long _lastFrameMs; // the last NoteFrame (gap detection; 0 = never)
private static long _gapEnd, _gapLen; // the frame that ended the last gap, and its length (0 = none)
private static readonly Queue<long> _errorAnswers = new(); // times of error UseDones (burst limiter)
private static long _staleDrops, _latchExpiries, _burstHolds;
private static long _staleDrops, _latchExpiries, _burstHolds, _emergencyThroughLatch;
private static long _healWaitAt; // when a plain heal was last held by the 'too busy' latch (0 = none)
/// <summary>A heal held by the latch this recently keeps the latch's probe slot from starts that are no heal.</summary>
public const long HealWaitFreshMs = 500;
public static long EmergencyThroughLatch => _emergencyThroughLatch;
public static long StaleDrops => _staleDrops;
public static long LatchExpiries => _latchExpiries;
public static long BurstHolds => _burstHolds;
@ -711,6 +718,16 @@ internal static class ActionPacer
}
}
/// <summary>
/// The macro was switched on. The host gives no time for a UseDone, only its count, so a UseDone that
/// came while nothing was checking (the macro off) cannot be told from a new one; the next check takes
/// the current count as its baseline instead, so a stale 0x1D read at the start latches nothing.
/// </summary>
public static void NoteMacroStart()
{
lock (Gate) _lastSeenSeq = int.MinValue;
}
/// <summary>Reads the last UseDone: a 0x1D starts or feeds the latch, any other answer clears it.</summary>
private static void ObserveUseDone(RynthCoreHost host, long now, out string? line)
{
@ -745,9 +762,10 @@ internal static class ActionPacer
/// a hung cast) or the character is in the air after a breaker jump. Runs the held-cast turn and
/// the stuck-cast breaker. Called by MayStart.
/// </summary>
private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, bool healStart = false)
private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, HealNeed heal = HealNeed.None)
{
why = "";
bool healStart = heal != HealNeed.None;
long now = NowMs();
long gapEnd, gapLen;
lock (Gate) { gapEnd = _gapEnd; gapLen = _gapLen; }
@ -789,7 +807,12 @@ internal static class ActionPacer
// A forced break with no cast of ours open (stage for nothing): once on the ground, it is
// over. Left set it would block the latch expiry and the probe for good.
else if (_stageFor == null && _stage != BreakStage.None && _jumpAt == 0) { _stage = BreakStage.None; _stageAt = 0; }
if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None
// A plain heal held by the latch (an emergency heal is never held by it): the probe slot is its.
// While one waited a moment ago, a start that is no heal does not take the slot (a door or corpse
// use would send first every time and the heal would see the next slot, up to BusyProbeMaxMs later).
if (heal == HealNeed.Heal && _busySince != 0) _healWaitAt = now;
bool healWaiting = heal != HealNeed.Heal && _healWaitAt != 0 && now - _healWaitAt < HealWaitFreshMs;
if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting
&& now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs))
{
probe = true;
@ -825,6 +848,16 @@ internal static class ActionPacer
lock (Gate) latched = _busySince != 0 || _hung != null;
// Our cast still inside CastMaxMs with no 0x1D: OutstandingAllows holds it (heal rules included).
if (!latched) return false;
// At Emergency Heal At the heal is not held by the latch, whatever set it (any refused use or
// pickup): a refusal of the heal costs a chat line, a held heal can cost the character. The jump
// wait (AirborneHolds, above) and the in-flight rules (MayStart) still apply.
if (heal == HealNeed.Emergency)
{
bool logEm;
lock (Gate) { _emergencyThroughLatch++; logEm = _busyLogged.Add(who + "/emergency"); }
if (logEm) Log(host, $"[Pace] {who}: the emergency heal goes ahead of the server's 'too busy' answer");
return false;
}
if (probe)
{
Log(host, $"[Pace] {who}: one try (#{_probes}) after the server's 'too busy' answer; no cast of ours is open");

View file

@ -0,0 +1,29 @@
// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked.
//
// One list for both plugins (linked source): RynthAi's Pets tab reads them to time its auto-capture
// (success -> short cooldown), and RynthILT's Vaulted Dungeons keeper counts a capture as a kill for
// its "Kill Client" timer (a hunter who captures instead of killing is not idle). They are the
// MonsterCapture success replies the Pets tab already matched; nothing new is guessed here.
using System;
namespace RynthCore.Plugin.Shared;
internal static class PetCaptureLines
{
/// <summary>Substrings of the success replies (matched case-insensitively).</summary>
private static readonly string[] Success =
{
"successfully siphoned the essence",
"The echo resonates perfectly",
"The essence is captured",
};
/// <summary>True when <paramref name="text"/> is a capture-success reply.</summary>
public static bool IsSuccess(string? text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (string part in Success)
if (text.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
}

View file

@ -166,4 +166,19 @@ public unsafe struct RynthAiHubApiV1
/// cap); 0 before login. RynthTracker shows RynthAi's session through this and SessionStats. Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<SessionStatsMoreV1*, int> SessionStatsMore;
// ── Appended 2026-10-18 (check with Has before calling) ─────────────────
/// <summary>
/// The byte offset of <see cref="VaultedDungeonsEnabled"/> (for <see cref="Has"/>): right after
/// SessionStatsMore.
/// </summary>
public static int VaultedDungeonsEnabledOffset => (int)BaseStructSize + sizeof(nint);
/// <summary>
/// VaultedDungeonsEnabled(): 1 when RynthAi's "Vaulted Dungeons" setting (Settings > Navigation) is
/// on. That setting is the master switch of RynthILT's Vaulted Dungeons keeper and lives only in
/// RynthAi; 0 (off) is also the answer before login and after shutdown. Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<int> VaultedDungeonsEnabled;
}

View file

@ -60,6 +60,8 @@ public static class RynthIltHub
public const string FeatureQuests = "quests";
public const string FeaturePetRefill = "pet_refill";
public const string FeatureUniversalMastery = "universal_mastery";
/// <summary>ACECustom siphon lenses (monster capture into a pet essence).</summary>
public const string FeatureMonsterCapture = "monster_capture";
public const string FeatureRequireComps = "require_spell_comps";
/// <summary>Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off).</summary>
public const string FeaturePetBreeding = "pet_breeding";

View file

@ -138,10 +138,53 @@ public sealed class LootEditItemRequest
/// 2026-10-07; an older engine never sends it, so it reads false.
/// </summary>
public bool IncludeT11 { get; set; }
/// <summary>
/// The attribute checklist's choices (added 2026-10-18), one per row the player changed; rows
/// without a choice keep their default (ticked for "items like this", T11 rows with
/// IncludeT11). Null from an older engine: every row at its default, as before.
/// </summary>
public List<LootEditItemChoice>? Choices { get; set; }
/// <summary>Echoed in the draft so the popup knows the answer is to its latest ask.</summary>
public int Seq { get; set; }
}
/// <summary>One checklist row as the player set it (LootEditItemAttribute.Id).</summary>
public sealed class LootEditItemChoice
{
public string Id { get; set; } = string.Empty;
public bool On { get; set; }
/// <summary>A LootItemAttributeOp code; -1 = the row's default.</summary>
public int Op { get; set; } = -1;
/// <summary>The edited value; empty = the item's own.</summary>
public string Value { get; set; } = string.Empty;
}
/// <summary>
/// One row of the popup's attribute checklist (added 2026-10-18): something the item has that a
/// rule can require, its value, and how it is required now.
/// </summary>
public sealed class LootEditItemAttribute
{
/// <summary>Stable within the item ("L:131", "D:152", "spell:Major Strength", "t11:tier").</summary>
public string Id { get; set; } = string.Empty;
/// <summary>Item, Weapon / Armor, Ratings, Spells, Pet essence, T11, Requirements.</summary>
public string Group { get; set; } = string.Empty;
public string Label { get; set; } = string.Empty;
/// <summary>The item's own value, for display ("Gold", "7", "1.12", "Major").</summary>
public string ItemValue { get; set; } = string.Empty;
/// <summary>The value the rule uses now (the item's, or the player's edit).</summary>
public string Value { get; set; } = string.Empty;
/// <summary>The row's comparison now (LootItemAttributeOp).</summary>
public int Op { get; set; }
/// <summary>The comparisons the row offers, the default first.</summary>
public List<int> Ops { get; set; } = new();
/// <summary>The value can be typed (a number); named values and spells can't.</summary>
public bool Editable { get; set; }
/// <summary>The rule requires this row now.</summary>
public bool On { get; set; }
public string Tip { get; set; } = string.Empty;
}
/// <summary>The rule an item makes, as the popup shows it, and what happened when it was added.</summary>
public sealed class LootEditItemDraft
{
@ -182,6 +225,13 @@ public sealed class LootEditItemDraft
/// </summary>
public string BuiltInReason { get; set; } = string.Empty;
public List<string> Notes { get; set; } = new();
/// <summary>
/// True from a RynthAi with the attribute checklist (added 2026-10-18): the popup shows
/// <see cref="Attributes"/> instead of its single "Include T11 attributes" box.
/// </summary>
public bool AttributesSupported { get; set; }
/// <summary>The item's checklist rows, grouped in display order (added 2026-10-18).</summary>
public List<LootEditItemAttribute> Attributes { get; set; } = new();
/// <summary>item_add went through; Message says what was added where.</summary>
public bool Added { get; set; }
public string Message { get; set; } = string.Empty;

View file

@ -0,0 +1,539 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.T11;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
// "Add to loot profile"'s attribute checklist (2026-10-18): every attribute a clicked item
// has that a loot rule can require, grouped for the popup, each with the item's value, the
// comparisons it offers and whether it is ticked by default. LootItemRules.Build turns the
// ticked rows into conditions, in row order. With no choices from the popup (an older engine,
// /ra loot add) the defaults reproduce the rules "items like this" and "Include T11
// attributes" always made.
/// <summary>How a checklist row is required (LootEditItemAttribute.Op).</summary>
public enum LootItemAttributeOp
{
AtLeast = 0,
Exactly = 1,
AtMost = 2,
Not = 3,
/// <summary>A spell by its exact name.</summary>
SpellExact = 10,
/// <summary>This spell at this tier or a higher one (Major Strength: Major, Epic or Legendary).</summary>
SpellOrBetter = 11,
/// <summary>This spell at any tier.</summary>
SpellAnyTier = 12,
}
/// <summary>One checklist row while a rule is built (the wire form is LootEditItemAttribute).</summary>
public sealed class LootItemAttribute
{
internal enum Shape { Long, Double, TotalRatings, Spell, CantripTier, SpellCount }
public string Id { get; init; } = string.Empty;
public string Group { get; init; } = string.Empty;
public string Label { get; init; } = string.Empty;
public string Tip { get; init; } = string.Empty;
internal Shape Kind { get; init; }
/// <summary>The property key (long or double rows), or the cantrip tier (CantripTier rows).</summary>
internal int Key { get; init; }
internal double ItemValue { get; init; }
public string ItemText { get; init; } = string.Empty;
public LootItemAttributeOp[] Ops { get; init; } = Array.Empty<LootItemAttributeOp>();
/// <summary>The item's value can be replaced by a typed number.</summary>
public bool Editable { get; init; }
/// <summary>Spell rows: the spell's name.</summary>
internal string Spell { get; init; } = string.Empty;
// Where the row stands now (defaults, then the player's choice).
public bool On { get; set; }
public LootItemAttributeOp Op { get; set; }
internal double Value { get; set; }
/// <summary>The value as the player typed it (empty: the item's).</summary>
internal string Typed { get; set; } = string.Empty;
public LootEditItemAttribute ToWire() => new()
{
Id = Id, Group = Group, Label = Label, ItemValue = ItemText, Tip = Tip, Editable = Editable, On = On,
Op = (int)Op, Ops = new List<int>(Array.ConvertAll(Ops, o => (int)o)),
Value = Editable ? LootItemAttributes.Number(Value) : ItemText,
};
}
public static class LootItemAttributes
{
public const string GroupItem = "Item", GroupGear = "Weapon / Armor", GroupRatings = "Ratings", GroupSpells = "Spells",
GroupPet = "Pet essence", GroupT11 = "T11", GroupRequirements = "Requirements";
/// <summary>Cantrip tiers, lowest first: "Major Strength" is tier 2.</summary>
public static readonly string[] CantripTiers = { "Minor", "Major", "Epic", "Legendary" };
private static readonly string[] Roman = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII" };
// Pet essence property ids (ACECustom; the Mini Remote's PetStats reads the same).
public const int KeyBond = 9053, KeyCapturedDamageType = 9054, KeyPotencyStored = 9056, KeyBreedingCharges = 9057,
KeyMutations = 9075, KeySummoningMastery = 362, KeyUseLevelRequirement = 364, KeyUseRequiresSkill = 366,
KeyUseRequiresSkillSpec = 368, KeyUseRequiresLevel = 369;
private const int SkillSummoning = 54;
private enum Cmp { Min, Max, Named }
private readonly record struct Spec(string Group, int Key, bool IsDouble, string Label, Cmp Cmp, string Tip = "");
/// <summary>The property rows, in display (and condition) order. Spells, T11 and the rating total are built separately.</summary>
private static readonly Spec[] Specs =
{
new(GroupItem, LootItemRules.KeyMaterial, false, "Material", Cmp.Named),
new(GroupItem, LootItemRules.KeyWorkmanship, false, "Workmanship", Cmp.Min),
new(GroupItem, 19, false, "Value", Cmp.Min),
new(GroupItem, 5, false, "Burden", Cmp.Max),
new(GroupItem, 106, false, "Spellcraft", Cmp.Min),
new(GroupItem, 108, false, "Max mana", Cmp.Min),
new(GroupItem, 109, false, "Arcane Lore to use", Cmp.Max, "The Arcane Lore the item's spells need (lower is easier)."),
new(GroupItem, 92, false, "Uses left", Cmp.Min),
new(GroupItem, 91, false, "Max uses", Cmp.Min),
new(GroupItem, 265, false, "Armor set", Cmp.Named, "The set id (the same set's pieces share it)."),
new(GroupItem, 353, false, "Imbue", Cmp.Named),
new(GroupItem, 166, false, "Slayer", Cmp.Named),
new(GroupItem, 45, false, "Damage type", Cmp.Named),
new(GroupGear, LootItemRules.KeyWieldSkill, false, "Wield skill", Cmp.Named),
new(GroupGear, LootItemRules.KeyWeaponSkill, false, "Weapon skill", Cmp.Named),
new(GroupGear, LootItemRules.KeyDamage, false, "Max damage", Cmp.Min),
new(GroupGear, 22, true, "Damage variance", Cmp.Max, "Lower is steadier damage."),
new(GroupGear, 63, true, "Damage modifier", Cmp.Min, "Missile weapons' damage multiplier."),
new(GroupGear, 62, true, "Attack modifier", Cmp.Min),
new(GroupGear, 29, true, "Melee defense modifier", Cmp.Min),
new(GroupGear, 149, true, "Missile defense modifier", Cmp.Min),
new(GroupGear, 150, true, "Magic defense modifier", Cmp.Min),
new(GroupGear, 144, true, "Mana conversion modifier", Cmp.Min),
new(GroupGear, LootItemRules.KeyElementalDamageMod, true, "Elemental damage vs monsters", Cmp.Min),
new(GroupGear, LootItemRules.KeyEquipSlots, false, "Equip slots", Cmp.Named, "Where it is worn or wielded."),
new(GroupGear, LootItemRules.KeyArmorLevel, false, "Armor level", Cmp.Min),
// The rating total comes first in this group (built separately); then each rating.
new(GroupRatings, 370, false, "Damage rating", Cmp.Min),
new(GroupRatings, 371, false, "Damage resist rating", Cmp.Min),
new(GroupRatings, 372, false, "Crit rating", Cmp.Min),
new(GroupRatings, 373, false, "Crit resist rating", Cmp.Min),
new(GroupRatings, 374, false, "Crit damage rating", Cmp.Min),
new(GroupRatings, 375, false, "Crit damage resist rating", Cmp.Min),
new(GroupRatings, 376, false, "Heal boost rating", Cmp.Min),
new(GroupRatings, 377, false, "Nether resist rating", Cmp.Min),
new(GroupRatings, 379, false, "Vitality rating", Cmp.Min),
new(GroupPet, KeyBond, false, "Bond level", Cmp.Min),
new(GroupPet, KeyUseRequiresLevel, false, "Level", Cmp.Min),
new(GroupPet, KeyUseLevelRequirement, false, "Level requirement", Cmp.Min),
new(GroupPet, KeyPotencyStored, false, "Potency stored", Cmp.Min),
new(GroupPet, KeySummoningMastery, false, "Summoning mastery", Cmp.Named),
new(GroupPet, KeyMutations, false, "Mutations", Cmp.Min),
new(GroupPet, 9070, false, "Damage mutations", Cmp.Min),
new(GroupPet, 9071, false, "Damage resist mutations", Cmp.Min),
new(GroupPet, 9072, false, "Crit mutations", Cmp.Min),
new(GroupPet, 9073, false, "Vitality mutations", Cmp.Min),
new(GroupPet, 9074, false, "Potency mutations", Cmp.Min),
new(GroupPet, KeyCapturedDamageType, false, "Captured damage type", Cmp.Named),
new(GroupPet, 307, false, "Pet damage rating", Cmp.Min),
new(GroupPet, 308, false, "Pet damage resist rating", Cmp.Min),
new(GroupPet, 313, false, "Pet crit rating", Cmp.Min),
new(GroupPet, 314, false, "Pet crit damage rating", Cmp.Min),
new(GroupPet, 315, false, "Pet crit resist rating", Cmp.Min),
new(GroupPet, 316, false, "Pet crit damage resist rating", Cmp.Min),
new(GroupPet, KeyBreedingCharges, false, "Breeding charges", Cmp.Min),
new(GroupRequirements, 158, false, "Wield requirement", Cmp.Named),
new(GroupRequirements, 160, false, "Wield difficulty", Cmp.Max, "Lower is easier to wield."),
};
/// <summary>Every int property a checklist can use: what RynthAi reads into LootItemFacts.</summary>
public static readonly int[] IntKeys = BuildKeys(isDouble: false);
/// <summary>Every float property a checklist can use.</summary>
public static readonly int[] DoubleKeys = BuildKeys(isDouble: true);
private static int[] BuildKeys(bool isDouble)
{
var keys = new List<int>();
foreach (Spec s in Specs)
if (s.IsDouble == isDouble && !keys.Contains(s.Key)) keys.Add(s.Key);
if (!isDouble)
foreach (int k in new[] { KeyUseRequiresSkill, KeyUseRequiresSkillSpec })
if (!keys.Contains(k)) keys.Add(k);
return keys.ToArray();
}
/// <summary>
/// A combat / summoning essence: the plugin says so, or the item carries ACECustom's bond or
/// potency, or using it needs Summoning.
/// </summary>
public static bool IsPetEssence(LootItemFacts f)
=> f.IsPetEssence || f.Int(KeyBond) > 0 || f.Ints.ContainsKey(KeyPotencyStored)
|| f.Int(KeyUseRequiresSkill) == SkillSummoning || f.Int(KeyUseRequiresSkillSpec) == SkillSummoning
|| f.ObjectClass == (int)AcObjectClass.CombatPet;
/// <summary>
/// The item's rows with their defaults: ticked for "items like this" (<paramref name="like"/>)
/// what that match always required, the T11 rows when <paramref name="includeT11"/>.
/// </summary>
public static List<LootItemAttribute> For(LootItemFacts f, bool like, bool includeT11)
{
var rows = new List<LootItemAttribute>();
bool pet = IsPetEssence(f);
HashSet<int> likeKeys = like ? LikeKeys(f, pet) : new HashSet<int>();
foreach (Spec s in Specs)
{
if (s.Group == GroupPet && !pet) continue;
if (s.Group == GroupRatings && s.Key == 370) AddTotalRatings(rows, f, like);
double v = s.IsDouble ? f.Double(s.Key) : f.Int(s.Key);
if (s.Cmp == Cmp.Named ? v == 0 : v <= 0) continue;
// A pet's level comes from 369 when it has one (PetStats does the same).
if (s.Key == KeyUseLevelRequirement && f.Int(KeyUseRequiresLevel) > 0) continue;
rows.Add(PropertyRow(s, v, likeKeys.Contains(s.IsDouble ? -s.Key : s.Key)));
}
// Spells and T11 go after the ratings and before Requirements.
int req = rows.FindIndex(r => r.Group == GroupRequirements);
var tail = req >= 0 ? rows.GetRange(req, rows.Count - req) : new List<LootItemAttribute>();
if (req >= 0) rows.RemoveRange(req, rows.Count - req);
AddSpellRows(rows, f, like);
AddT11Rows(rows, f, includeT11);
rows.AddRange(tail);
return rows;
}
/// <summary>
/// The keys "items like this" required before the checklist (doubles negated), plus a
/// pet essence's bond, level, potency, mastery and mutations.
/// </summary>
private static HashSet<int> LikeKeys(LootItemFacts f, bool pet)
{
var k = new HashSet<int> { LootItemRules.KeyMaterial, LootItemRules.KeyWorkmanship };
int wieldSkill = f.Int(LootItemRules.KeyWieldSkill);
switch ((AcObjectClass)f.ObjectClass)
{
case AcObjectClass.MeleeWeapon:
k.Add(wieldSkill != 0 ? LootItemRules.KeyWieldSkill : LootItemRules.KeyWeaponSkill);
k.Add(LootItemRules.KeyDamage);
break;
case AcObjectClass.MissileWeapon:
k.Add(wieldSkill != 0 ? LootItemRules.KeyWieldSkill : LootItemRules.KeyWeaponSkill);
break;
case AcObjectClass.WandStaffOrb:
k.Add(LootItemRules.KeyWieldSkill);
k.Add(-LootItemRules.KeyElementalDamageMod);
break;
case AcObjectClass.Armor:
case AcObjectClass.Clothing:
k.Add(LootItemRules.KeyEquipSlots);
k.Add(LootItemRules.KeyArmorLevel);
break;
case AcObjectClass.Jewelry:
k.Add(LootItemRules.KeyEquipSlots);
break;
}
if (pet)
foreach (int key in new[] { KeyBond, KeyUseRequiresLevel, KeyUseLevelRequirement, KeyPotencyStored, KeySummoningMastery, KeyMutations })
k.Add(key);
return k;
}
private static LootItemAttribute PropertyRow(Spec s, double v, bool on)
{
LootItemAttributeOp[] ops = s.Cmp switch
{
Cmp.Named => new[] { LootItemAttributeOp.Exactly, LootItemAttributeOp.Not },
Cmp.Max => new[] { LootItemAttributeOp.AtMost, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtLeast },
_ => new[] { LootItemAttributeOp.AtLeast, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtMost },
};
string text = s.IsDouble ? Number(v) : NamedOrNumber(s.Key, (int)v);
return new LootItemAttribute
{
Id = (s.IsDouble ? "D:" : "L:") + s.Key.ToString(CultureInfo.InvariantCulture),
Group = s.Group, Label = s.Label, Tip = s.Tip,
Kind = s.IsDouble ? LootItemAttribute.Shape.Double : LootItemAttribute.Shape.Long,
Key = s.Key, ItemValue = v, ItemText = text, Ops = ops, Editable = s.Cmp != Cmp.Named,
On = on, Op = ops[0], Value = v,
};
}
private static void AddTotalRatings(List<LootItemAttribute> rows, LootItemFacts f, bool like)
{
int total = 0;
foreach (int k in LootItemRules.RatingKeys) total += Math.Max(0, f.Int(k));
if (total <= 0 || rows.Exists(r => r.Kind == LootItemAttribute.Shape.TotalRatings)) return;
rows.Add(new LootItemAttribute
{
Id = "ratings", Group = GroupRatings, Label = "Total ratings", Kind = LootItemAttribute.Shape.TotalRatings,
Tip = "Damage, damage resist, crit, crit resist, crit damage, crit damage resist, heal boost and vitality ratings added up.",
ItemValue = total, ItemText = Number(total), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true,
On = like, Op = LootItemAttributeOp.AtLeast, Value = total,
});
}
// ── Spells ──────────────────────────────────────────────────────────────
/// <summary>"Major Strength": tier 1 (CantripTiers index) and "Strength".</summary>
public static bool TryCantrip(string spell, out int tier, out string rest)
{
for (int i = 0; i < CantripTiers.Length; i++)
{
string p = CantripTiers[i] + " ";
if (spell.StartsWith(p, StringComparison.OrdinalIgnoreCase) && spell.Length > p.Length)
{
tier = i;
rest = spell.Substring(p.Length);
return true;
}
}
tier = -1;
rest = string.Empty;
return false;
}
/// <summary>"Strength Self VI": level 6 and "Strength Self".</summary>
public static bool TryLevel(string spell, out int level, out string rest)
{
int sp = spell.LastIndexOf(' ');
if (sp > 0)
{
int idx = Array.IndexOf(Roman, spell.Substring(sp + 1).ToUpperInvariant());
if (idx >= 0)
{
level = idx + 1;
rest = spell.Substring(0, sp);
return true;
}
}
level = 0;
rest = string.Empty;
return false;
}
/// <summary>The spell condition's pattern for a spell row's comparison.</summary>
public static string SpellPattern(string spell, LootItemAttributeOp op)
{
if (op == LootItemAttributeOp.SpellOrBetter || op == LootItemAttributeOp.SpellAnyTier)
{
int from;
if (TryCantrip(spell, out int tier, out string rest))
{
from = op == LootItemAttributeOp.SpellAnyTier ? 0 : tier;
return "^(" + string.Join("|", CantripTiers, from, CantripTiers.Length - from) + ") " + LootItemRules.EscapeText(rest) + "$";
}
if (TryLevel(spell, out int level, out rest))
{
from = op == LootItemAttributeOp.SpellAnyTier ? 0 : level - 1;
return "^" + LootItemRules.EscapeText(rest) + " (" + string.Join("|", Roman, from, Roman.Length - from) + ")$";
}
}
return LootItemRules.ExactPattern(spell);
}
/// <summary>
/// A row per spell (cantrips default to "or better", leveled spells to the exact spell, as
/// "items like this" always did; the first <see cref="LootItemRules.MaxSpells"/> ticked
/// for it), then "N cantrips of a tier or better" and the spell count.
/// </summary>
private static void AddSpellRows(List<LootItemAttribute> rows, LootItemFacts f, bool like)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var tiers = new List<int>();
int ticked = 0, count = 0;
foreach (string raw in f.Spells)
{
string s = LootItemRules.OneLine(raw).Trim();
if (s.Length == 0 || !seen.Add(s)) continue;
count++;
bool cantrip = TryCantrip(s, out int tier, out _);
int level = 0;
bool leveled = !cantrip && TryLevel(s, out level, out _);
if (cantrip) tiers.Add(tier);
LootItemAttributeOp[] ops = cantrip
? new[] { LootItemAttributeOp.SpellOrBetter, LootItemAttributeOp.SpellExact, LootItemAttributeOp.SpellAnyTier }
: leveled
? new[] { LootItemAttributeOp.SpellExact, LootItemAttributeOp.SpellOrBetter, LootItemAttributeOp.SpellAnyTier }
: new[] { LootItemAttributeOp.SpellExact };
bool on = like && ticked < LootItemRules.MaxSpells;
if (on) ticked++;
rows.Add(new LootItemAttribute
{
Id = "spell:" + s, Group = GroupSpells, Label = s, Kind = LootItemAttribute.Shape.Spell, Spell = s,
ItemText = cantrip ? CantripTiers[tier] + " cantrip" : leveled ? "level " + Roman[level - 1] : "spell",
Tip = cantrip ? "Or better: this cantrip at this tier or higher. Any tier: Minor to Legendary."
: leveled ? "Or better: this spell at this level or higher. Any tier: any level."
: "The item has this spell.",
Ops = ops, On = on, Op = ops[0],
});
}
// "At least N Epic-or-better cantrips": one row per tier the item has, highest first.
tiers.Sort();
for (int t = CantripTiers.Length - 1; t >= 0; t--)
{
if (!tiers.Contains(t)) continue;
int n = tiers.FindAll(x => x >= t).Count;
string label = t == CantripTiers.Length - 1 ? CantripTiers[t] + " cantrips" : CantripTiers[t] + "-or-better cantrips";
rows.Add(new LootItemAttribute
{
Id = "cantrips:" + CantripTiers[t], Group = GroupSpells, Label = label, Kind = LootItemAttribute.Shape.CantripTier,
Key = t, ItemValue = n, ItemText = Number(n), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true,
Tip = "How many of the item's cantrips are this tier or higher.", Op = LootItemAttributeOp.AtLeast, Value = n,
});
}
if (count > 0)
rows.Add(new LootItemAttribute
{
Id = "spellcount", Group = GroupSpells, Label = "Spell count", Kind = LootItemAttribute.Shape.SpellCount,
ItemValue = count, ItemText = Number(count), Ops = new[] { LootItemAttributeOp.AtLeast }, Editable = true,
Op = LootItemAttributeOp.AtLeast, Value = count,
});
}
/// <summary>How many spell rows there are (the "more than 4 spells" note).</summary>
internal static int SpellRowCount(List<LootItemAttribute> rows) => rows.FindAll(r => r.Kind == LootItemAttribute.Shape.Spell).Count;
/// <summary>True for the T11 group's rows.</summary>
internal static bool IsT11Row(LootItemAttribute r) => r.Group == GroupT11;
// ── T11 ─────────────────────────────────────────────────────────────────
/// <summary>
/// The T11 rows on RynthAi's virtual T11 keys, in the order "Include T11 attributes" always
/// added them (Is T11, tier, weapon grade, damage %, gear grade, each catalogued modifier,
/// Has Slot Special for a value-less one, Cast on Strike count), then the summary keys,
/// off by default. Left out on purpose: Can Wield (the character), Zone Locked (where it
/// was appraised), property slots and Tainted (bag state, not quality).
/// </summary>
private static void AddT11Rows(List<LootItemAttribute> rows, LootItemFacts f, bool on)
{
T11ItemInfo? t = f.T11;
if (t == null || !t.IsT11) return;
void Row(string id, string label, int key, int v, bool named, bool def = true, bool equal = false, string tip = "")
{
LootItemAttributeOp[] ops = equal ? new[] { LootItemAttributeOp.Exactly }
: new[] { LootItemAttributeOp.AtLeast, LootItemAttributeOp.Exactly, LootItemAttributeOp.AtMost };
rows.Add(new LootItemAttribute
{
Id = "t11:" + id, Group = GroupT11, Label = label, Kind = LootItemAttribute.Shape.Long, Key = key, Tip = tip,
ItemValue = v, ItemText = named ? NamedOrNumber(key, v) : equal ? "yes" : Number(v), Ops = ops,
Editable = !named && !equal, On = on && def, Op = ops[0], Value = v,
});
}
Row("is", "Is T11", T11Keys.IsT11, 1, named: false, equal: true);
if (!t.HasText) return;
if (t.Tier > 0) Row("tier", t.TierIsExact ? "Tier" : "Tier (estimated)", T11Keys.EstimatedTier, t.Tier, named: false);
if (t.GradeRank > 0) Row("grade", "Weapon grade", T11Keys.WeaponGrade, t.GradeRank, named: true);
if (t.DamagePercent > 0) Row("dmgpct", "Damage %", T11Keys.DamagePercent, t.DamagePercent, named: false);
if (t.GearGradeRank > 0) Row("geargrade", "Gear grade", T11Keys.GearGrade, t.GearGradeRank, named: true);
bool valuelessSpecial = false;
foreach (T11Modifier m in t.Modifiers)
{
if (T11Catalog.ModifierByKey(m.Key) == null) continue;
// A modifier's key reads 0 when it is absent, so a value-less one can't be required by value.
if (m.Value > 0) Row("mod:" + m.Key.ToString(CultureInfo.InvariantCulture), "Mod: " + m.Name, T11Keys.ForModifier(m.Key), m.Value, named: false);
else if (m.IsSlotSpecial) valuelessSpecial = true;
}
if (valuelessSpecial) Row("special", "Has slot special", T11Keys.HasSlotSpecial, 1, named: false, equal: true);
if (t.Procs.Count > 0) Row("cos", "Cast on Strike count", T11Keys.CastOnStrikeCount, t.Procs.Count, named: false);
foreach (var (key, label) in new[] { (T11Keys.ModifierCount, "Modifier count"), (T11Keys.ModifierRatingTotal, "Modifier rating total"), (T11Keys.BestRollPercent, "Best roll %") })
if (T11Keys.TryGetValue(t, key, null, out int v) && v > 0)
Row("sum:" + key.ToString(CultureInfo.InvariantCulture), label, key, v, named: false, def: false);
}
/// <summary>The catalogued-but-unknown T11 modifiers (the rule can't require them).</summary>
internal static List<string> UnknownT11Modifiers(LootItemFacts f)
{
var unknown = new List<string>();
if (f.T11 is { IsT11: true } t)
foreach (T11Modifier m in t.Modifiers)
if (T11Catalog.ModifierByKey(m.Key) == null) unknown.Add(m.Name);
return unknown;
}
// ── Choices and conditions ──────────────────────────────────────────────
/// <summary>
/// The player's choices onto the rows (unknown ids are ignored: the item may have changed).
/// A typed value that isn't a number keeps the item's and says so in <paramref name="notes"/>.
/// </summary>
public static void Apply(List<LootItemAttribute> rows, IReadOnlyList<LootEditItemChoice>? choices, List<string> notes)
{
if (choices == null) return;
foreach (LootEditItemChoice c in choices)
{
LootItemAttribute? r = rows.Find(x => x.Id == c.Id);
if (r == null) continue;
r.On = c.On;
if (c.Op >= 0 && Array.IndexOf(r.Ops, (LootItemAttributeOp)c.Op) >= 0) r.Op = (LootItemAttributeOp)c.Op;
string typed = (c.Value ?? string.Empty).Trim();
if (!r.Editable || typed.Length == 0) continue;
bool whole = r.Kind != LootItemAttribute.Shape.Double;
if (double.TryParse(typed, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) && v >= 0 && (!whole || v == Math.Floor(v)))
{
r.Value = v;
r.Typed = typed;
}
else
notes.Add($"{r.Label}: '{typed}' isn't a{(whole ? " whole" : "")} number of 0 or more; the item's {r.ItemText} is used.");
}
}
/// <summary>The ticked rows' conditions onto <paramref name="rule"/>, in row order; how many rows added one.</summary>
public static int AddConditions(VTankLootRule rule, List<LootItemAttribute> rows)
{
int n = 0;
foreach (LootItemAttribute r in rows)
{
if (!r.On) continue;
n++;
string key = r.Key.ToString(CultureInfo.InvariantCulture);
switch (r.Kind)
{
case LootItemAttribute.Shape.Long:
string iv = ((long)r.Value).ToString(CultureInfo.InvariantCulture);
int type = r.Op switch
{
LootItemAttributeOp.Exactly => VTankNodeTypes.LongValKeyE,
LootItemAttributeOp.AtMost => VTankNodeTypes.LongValKeyLE,
LootItemAttributeOp.Not => VTankNodeTypes.LongValKeyNE,
_ => VTankNodeTypes.LongValKeyGE,
};
rule.Conditions.Add(Cond(type, iv, key));
break;
case LootItemAttribute.Shape.Double:
string dv = Number(r.Value);
if (r.Op != LootItemAttributeOp.AtMost) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, dv, key));
if (r.Op != LootItemAttributeOp.AtLeast) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyLE, dv, key));
break;
case LootItemAttribute.Shape.TotalRatings:
rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Number(r.Value)));
break;
case LootItemAttribute.Shape.Spell:
rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, SpellPattern(r.Spell, r.Op)));
break;
case LootItemAttribute.Shape.CantripTier:
string tiers = string.Join("|", CantripTiers, r.Key, CantripTiers.Length - r.Key);
rule.Conditions.Add(Cond(VTankNodeTypes.SpellMatch, "^(" + tiers + ") ", string.Empty, Number(r.Value)));
break;
case LootItemAttribute.Shape.SpellCount:
rule.Conditions.Add(Cond(VTankNodeTypes.SpellCountGE, Number(r.Value)));
break;
}
}
return n;
}
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
/// <summary>A number as rules write it: whole numbers plain, decimals to 4 places.</summary>
public static string Number(double v) => v.ToString("0.####", CultureInfo.InvariantCulture);
/// <summary>A long key's value by name when it has one ("Gold", "Light Weapons"), else the number.</summary>
private static string NamedOrNumber(int key, int v)
=> LootRuleText.ValueName(key, v.ToString(CultureInfo.InvariantCulture)) ?? v.ToString(CultureInfo.InvariantCulture);
}

View file

@ -32,6 +32,8 @@ public sealed class LootItemFacts
/// <see cref="T11ItemInfo.None"/> for an item that isn't T11 gear.
/// </summary>
public T11ItemInfo? T11 { get; set; }
/// <summary>The plugin knows it for a summoning essence (by WCID, icon, use requirement; added 2026-10-18).</summary>
public bool IsPetEssence { get; set; }
public bool Stackable => MaxStackSize > 1 || StackSize > 1;
@ -64,6 +66,11 @@ public sealed class LootItemRuleOptions
/// slot special, Cast on Strike), each at least as good as this item's. Works with any match.
/// </summary>
public bool IncludeT11 { get; set; }
/// <summary>
/// The popup's attribute checklist choices (LootItemAttributes); null: every row at its
/// default, which is the rule "items like this" and IncludeT11 always made.
/// </summary>
public IReadOnlyList<LootEditItemChoice>? Choices { get; set; }
}
/// <summary>A built rule, ready to preview and insert.</summary>
@ -76,6 +83,8 @@ public sealed class LootItemRuleDraft
public string DefaultName { get; init; } = string.Empty;
/// <summary>Things the player should know (a broad rule, spells left out...).</summary>
public List<string> Notes { get; init; } = new();
/// <summary>The item's checklist rows as the rule used them (the popup shows them).</summary>
public List<LootItemAttribute> Attributes { get; init; } = new();
}
public static class LootItemRules
@ -86,10 +95,9 @@ public static class LootItemRules
public const int KeyElementalDamageMod = 152;
/// <summary>The ratings TotalRatingsGE adds up (same list as both evaluators).</summary>
public static readonly int[] RatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 };
/// <summary>The int properties a "like this" rule can use: what RynthAi reads into LootItemFacts.</summary>
public static readonly int[] IntKeys =
{ KeyArmorLevel, KeyEquipSlots, KeyDamage, KeyWeaponSkill, KeyWorkmanship, KeyMaterial, KeyWieldSkill, 370, 371, 372, 373, 374, 375, 376, 379 };
public static readonly int[] DoubleKeys = { KeyElementalDamageMod };
/// <summary>The int properties a rule from an item can use: what RynthAi reads into LootItemFacts.</summary>
public static int[] IntKeys => LootItemAttributes.IntKeys;
public static int[] DoubleKeys => LootItemAttributes.DoubleKeys;
/// <summary>Spell conditions a "like this" rule takes at most (all must match: more makes it narrower).</summary>
public const int MaxSpells = 4;
@ -109,16 +117,17 @@ public static class LootItemRules
/// A name as an exact, case-insensitive regex: ^name$ with the regex
/// metacharacters escaped (spaces left alone, unlike Regex.Escape, so it reads well).
/// </summary>
public static string ExactPattern(string name)
public static string ExactPattern(string name) => "^" + EscapeText(name) + "$";
/// <summary>Text with the regex metacharacters escaped (spaces left alone), for a pattern's middle.</summary>
public static string EscapeText(string text)
{
var sb = new StringBuilder(name.Length + 8);
sb.Append('^');
foreach (char ch in name)
var sb = new StringBuilder(text.Length + 8);
foreach (char ch in text)
{
if ("\\*+?|{}[]()^$.#".IndexOf(ch) >= 0) sb.Append('\\');
sb.Append(ch);
}
sb.Append('$');
return sb.ToString();
}
@ -189,139 +198,60 @@ public static class LootItemRules
return null;
}
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
likeBare = AddLikeConditions(rule, f, notes) == 0;
likeBare = true;
break;
}
int t11Added = o.IncludeT11 ? AddT11Conditions(rule, f, notes) : 0;
if (likeBare && t11Added == 0)
// The attribute checklist: defaults for this match, then the popup's choices.
List<LootItemAttribute> rows = LootItemAttributes.For(f, match == LootItemMatch.Like, o.IncludeT11);
LootItemAttributes.Apply(rows, o.Choices, notes);
int added = LootItemAttributes.AddConditions(rule, rows);
AddRowNotes(f, o, rows, match, notes);
if (likeBare && added == 0)
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match);
string ruleName = OneLine(o.RuleName).Trim();
rule.Name = ruleName.Length > 0 ? ruleName : defaultName;
return new LootItemRuleDraft { Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes };
}
/// <summary>The "like this" conditions for the item's kind; how many it added.</summary>
private static int AddLikeConditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
{
int n = rule.Conditions.Count;
var cls = (AcObjectClass)f.ObjectClass;
void LongE(int key) { int v = f.Int(key); if (v != 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key))); }
void LongGE(int key) { int v = f.Int(key); if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
void DoubleGE(int key)
return new LootItemRuleDraft
{
double v = f.Double(key);
if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, v.ToString("0.####", CultureInfo.InvariantCulture), Num(key)));
}
LongE(KeyMaterial);
LongGE(KeyWorkmanship);
switch (cls)
{
case AcObjectClass.MeleeWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
LongGE(KeyDamage);
break;
case AcObjectClass.MissileWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
break;
case AcObjectClass.WandStaffOrb:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill);
DoubleGE(KeyElementalDamageMod);
break;
case AcObjectClass.Armor:
case AcObjectClass.Clothing:
LongE(KeyEquipSlots);
LongGE(KeyArmorLevel);
break;
case AcObjectClass.Jewelry:
LongE(KeyEquipSlots);
break;
}
int ratings = 0;
foreach (int k in RatingKeys) ratings += Math.Max(0, f.Int(k));
if (ratings > 0) rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Num(ratings)));
int spells = 0;
foreach (string s in f.Spells)
{
string sn = OneLine(s).Trim();
if (sn.Length == 0) continue;
if (spells == MaxSpells)
{
notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells}.");
break;
}
rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, ExactPattern(sn)));
spells++;
}
return rule.Conditions.Count - n;
Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes, Attributes = rows,
};
}
/// <summary>
/// The T11 conditions, on RynthAi's virtual T11 keys: Is T11, then tier (the server's
/// stamped tier when sent), weapon grade, damage %, gear grade, every catalogued modifier,
/// slot special and Cast on Strike count, each at least this item's. Left out on purpose:
/// Can Wield (the character, not the item), Zone Locked (where it was appraised), the wield
/// gates (they follow from the tier), the modifier count / rating total / roll % (they
/// follow from the per-modifier values), and the property slots and Tainted (bag state,
/// not quality). How many it added.
/// What the player should know about the rows: spells "like this" left unticked, a T11 item
/// not identified yet, T11 modifiers RynthAi has no key for, T11 asked of a non-T11 item.
/// </summary>
private static int AddT11Conditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
private static void AddRowNotes(LootItemFacts f, LootItemRuleOptions o, List<LootItemAttribute> rows, LootItemMatch match, List<string> notes)
{
if (match == LootItemMatch.Like && o.Choices == null && LootItemAttributes.SpellRowCount(rows) > MaxSpells)
notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells} (the Add to loot profile popup can tick the rest).");
bool t11Asked = o.IncludeT11 || rows.Exists(r => r.On && LootItemAttributes.IsT11Row(r));
if (!t11Asked) return;
T11ItemInfo? t = f.T11;
if (t == null || !t.IsT11)
{
notes.Add("Not a T11 item, so there are no T11 attributes to add.");
return 0;
return;
}
int n = rule.Conditions.Count;
void Equal(int key, int v) => rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key)));
void AtLeast(int key, int v) { if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
Equal(T11Keys.IsT11, 1);
if (!t.HasText)
{
notes.Add("The item hasn't been identified, so only \"Is T11\" could be added. Assess it and preview again for its tier, grade and modifiers.");
return rule.Conditions.Count - n;
return;
}
AtLeast(T11Keys.EstimatedTier, t.Tier);
AtLeast(T11Keys.WeaponGrade, t.GradeRank);
AtLeast(T11Keys.DamagePercent, t.DamagePercent);
AtLeast(T11Keys.GearGrade, t.GearGradeRank);
bool valuelessSpecial = false;
var unknown = new List<string>();
foreach (T11Modifier m in t.Modifiers)
{
if (T11Catalog.ModifierByKey(m.Key) == null)
{
unknown.Add(m.Name);
continue;
}
// A modifier's key reads 0 when it is absent, so a value-less one can't be required by value.
if (m.Value > 0) AtLeast(T11Keys.ForModifier(m.Key), m.Value);
else if (m.IsSlotSpecial) valuelessSpecial = true;
}
if (valuelessSpecial) Equal(T11Keys.HasSlotSpecial, 1);
AtLeast(T11Keys.CastOnStrikeCount, t.Procs.Count);
List<string> unknown = LootItemAttributes.UnknownT11Modifiers(f);
if (unknown.Count > 0)
notes.Add("Left out (RynthAi has no loot key for these modifiers yet): " + string.Join(", ", unknown) + ".");
return rule.Conditions.Count - n;
}
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture);
private static string OneLine(string? s) =>
internal static string OneLine(string? s) =>
string.IsNullOrEmpty(s) ? string.Empty : s.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
// =====================================================================

View file

@ -47,8 +47,24 @@ public static class LootRuleText
{
(5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage (max)"), (45, "DamageType"),
(48, "WeaponSkill"), (54, "WeaponEncumbrance"), // 54 was labelled MaxDamage until 2026-10-07; max damage is 44
(87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"),
// 87 / 88 were labelled MaxStructure / Structure until 2026-10-18; uses are 91 / 92
// (what the Pets tab reads for an essence's uses), and 107 is the current mana.
(86, "MinLevelRestrict"), (87, "MaxLevelRestrict"), (88, "LockpickSkillBonus"),
(91, "UsesTotal (MaxStructure)"), (92, "UsesRemaining (Structure)"),
(105, "ItemWorkmanship"), (106, "ItemSpellcraft"), (107, "ItemCurMana"), (108, "ItemMaxMana"),
(109, "ItemDifficulty (Arcane Lore)"),
(131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"),
// ACECustom / ACE appraisal: slayer weapons (166) and combat-essence pet stats (9053-9075).
// "Slayer Type" is the player-facing name; the ACE property is still SlayerCreatureType.
(166, "Slayer Type"), (9053, "Pet Bond Level"), (9054, "Pet Captured Damage Type"), (9056, "Pet Potency Stored"),
(9057, "Pet Breeding Charges"), (9070, "Pet Damage Mutations"), (9071, "Pet Damage Resist Mutations"),
(9072, "Pet Crit Mutations"), (9073, "Pet Vitality Mutations"), (9074, "Pet Potency Mutations"),
(9075, "Pet Mutation Count"),
(307, "Pet DamageRating"), (308, "Pet DamageResistRating"), (313, "Pet CritRating"),
(314, "Pet CritDamageRating"), (315, "Pet CritResistRating"), (316, "Pet CritDamageResistRating"),
(362, "SummoningMastery"), (364, "UseLevelRequirement"), (366, "UseRequiresSkill"),
(368, "UseRequiresSkillSpec"), (369, "UseRequiresLevel"),
(179, "Imbued (Decal)"), (265, "EquipmentSetId (armor set)"),
(218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"),
(372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"),
(375, "CritDamageResistRating"), (376, "HealBoostRating"), (377, "NetherResistRating"), (379, "VitalityRating"),
@ -81,7 +97,8 @@ public static class LootRuleText
public static readonly (int Id, string Name)[] DoubleKeys =
{
(5, "ManaRate"), (22, "DamageVariance"), (29, "WeaponDefense"), (62, "WeaponOffense"),
(63, "DamageMod"), (144, "ManaConversionMod"), (149, "WeaponMissileDefense"),
(63, "DamageMod"), (138, "Slayer Damage Bonus"), // often unset on ACE appraisal; prefer LongDesc / int 166
(144, "ManaConversionMod"), (149, "WeaponMissileDefense"),
(150, "WeaponMagicDefense"), (152, "ElementalDamageVsMonsters"), (167, "CooldownDuration"),
(0x0A000009, "SalvageWorkmanship"), (0x0A00000B, "Variance"),
(0x0A00000C, "AttackBonus"), (0x0A00000E, "DamageBonus"),
@ -158,27 +175,85 @@ public static class LootRuleText
(512, "Mana"), (1024, "Nether"),
};
/// <summary>
/// Slayer Type (166 / ACE SlayerCreatureType): ACE CreatureType enum names
/// (same set as RynthAi CreatureTypeNames). Index 0 is Invalid and omitted.
/// Listed A–Z so players can find a type quickly; ids stay ACE order for .utl.
/// Unknown ids still show as "value N".
/// </summary>
public static readonly (int Id, string Name)[] CreatureTypes = BuildCreatureTypes();
private static (int Id, string Name)[] BuildCreatureTypes()
{
// Keep in sync with Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureTypeNames.cs.
string[] names =
{
"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", "Anekshay",
};
var list = new List<(int, string)>(names.Length - 1);
for (int i = 1; i < names.Length; i++)
list.Add((i, names[i]));
// Alphabetical for the picker (same idea as Skills); id is what the .utl stores.
list.Sort((a, b) => string.Compare(a.Item2, b.Item2, StringComparison.OrdinalIgnoreCase));
return list.ToArray();
}
/// <summary>
/// The names for a long key's value, or null when the key's value is a plain
/// number. Unknown values are still valid: show them as "value N".
/// </summary>
/// <summary>
/// ImbuedEffect (353): ACE's ImbuedEffectType flags. A combination (two imbues) shows as
/// "value N".
/// </summary>
public static readonly (int Id, string Name)[] ImbuedEffects =
{
(1, "Critical Strike"), (2, "Crippling Blow"), (4, "Armor Rending"), (8, "Slash Rending"),
(16, "Pierce Rending"), (32, "Bludgeon Rending"), (64, "Acid Rending"), (128, "Cold Rending"),
(256, "Electric Rending"), (512, "Fire Rending"), (1024, "Melee Defense"), (2048, "Missile Defense"),
(4096, "Magic Defense"), (8192, "Spellbook"), (16384, "Nether Rending"),
};
/// <summary>SummoningMastery (362): the pet school an essence needs (ACE SummoningMastery).</summary>
public static readonly (int Id, string Name)[] SummoningMasteries =
{
(1, "Primalist"), (2, "Necromancer"), (3, "Naturalist"),
};
public static (int Id, string Name)[]? ValueTableFor(int longKey) => longKey switch
{
45 or 0x0D000021 => DamageTypes,
45 or 0x0D000021 or 9054 => DamageTypes,
48 or 0x0D000020 => Skills,
131 => Materials,
158 => WieldRequirements,
159 => Skills,
159 or 366 or 368 => Skills,
166 => CreatureTypes,
353 => ImbuedEffects,
362 => SummoningMasteries,
T11.T11Keys.WeaponGrade => T11.T11Catalog.Grades,
T11.T11Keys.GearGrade => T11.T11Catalog.Grades,
_ => null,
};
/// <summary>True when the long key's value is a set of flags (a named value is one flag or a common pair).</summary>
public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021;
public static bool ValueTableIsFlags(int longKey) => longKey is 45 or 0x0D000021 or 9054 or 353;
/// <summary>The long keys that have a value table, for the vocabulary.</summary>
public static readonly int[] KeysWithValueTables = { 45, 48, 131, 158, 159, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade };
public static readonly int[] KeysWithValueTables =
{ 45, 48, 131, 158, 159, 166, 353, 362, 366, 368, 9054, 0x0D000020, 0x0D000021, T11.T11Keys.WeaponGrade, T11.T11Keys.GearGrade };
/// <summary>
/// True for the conditions whose value is picked by name when the key has a

View file

@ -81,10 +81,20 @@ internal sealed class LongValuePicker : ContentControl
_box.Width = 80;
_box.Margin = new Thickness(4, 0, 0, 0);
ToolTip.SetTip(_box, "Any number, named or not");
_combo = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch, MinWidth = 160 };
_combo = new ComboBox
{
HorizontalAlignment = HorizontalAlignment.Stretch,
MinWidth = 160,
IsTextSearchEnabled = true, // type while open to jump (Olthoi, Virindi, …)
MaxDropDownHeight = 360,
};
_combo.DisplayMemberBinding = new Avalonia.Data.Binding(nameof(Opt.Display));
if (LootRuleText.ValueTableIsFlags(key))
ToolTip.SetTip(_combo, "Flags: other combinations are typed as a number in the box");
else if (key == 166)
ToolTip.SetTip(_combo, "Slayer creature type — pick by name (list is A–Z). Any slayer: use >= 1");
else
ToolTip.SetTip(_combo, "Pick by name, or type a number in the box");
_combo.SelectionChanged += (_, _) =>
{
if (_syncing || _combo.SelectedItem is not Opt { Id: int id }) return;

View file

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
namespace RynthCore.LootSdkTests;
// "Add to loot profile"'s attribute checklist (2026-10-18): every attribute a clicked item has,
// grouped, each ticked or not with a comparison and a value; spells by tier; pet essences.
// The defaults (no choices) are covered by LootAddItemTests / LootAddT11Tests, which still
// expect the rules "items like this" and "Include T11 attributes" always made.
internal static partial class Program
{
private static void RunLootAddAttributeTests()
{
Console.WriteLine("\n-- LootAdd: attribute checklist --");
TestAttrRowsAndGroups();
TestAttrChoices();
TestAttrSpellTiers();
TestAttrCantripCounts();
TestAttrPetEssence();
TestAttrNativeAndWire();
TestAttrVocab();
}
private static LootItemFacts Sword() => new()
{
Id = 10, Name = "Gold Tachi", ObjectClass = (int)AcObjectClass.MeleeWeapon,
Ints = { [131] = 60, [105] = 8, [159] = 45, [44] = 52, [5] = 300, [370] = 3, [374] = 2, [160] = 400, [158] = 2 },
Doubles = { [62] = 1.18, [29] = 1.2 },
Spells = { "Legendary Blood Thirst", "Epic Heart Thirst", "Major Strength", "Blood Drinker Self VI" },
};
private static List<LootEditItemChoice> Pick(params (string Id, bool On, LootItemAttributeOp Op, string Value)[] p)
=> p.Select(x => new LootEditItemChoice { Id = x.Id, On = x.On, Op = (int)x.Op, Value = x.Value }).ToList();
private static void TestAttrRowsAndGroups()
{
LootItemRuleDraft d = BuildOk(Sword());
List<LootItemAttribute> rows = d.Attributes;
Check(rows.Count > 0, "attr: rows for an item");
Check(!rows.Any(r => r.On), "attr: name + class ticks nothing by default");
string[] groups = rows.Select(r => r.Group).Distinct().ToArray();
Eq(string.Join(",", groups), "Item,Weapon / Armor,Ratings,Spells,Requirements", "attr: groups in display order");
LootItemAttribute mat = rows.Single(r => r.Id == "L:131");
Eq(mat.ItemText, "Gold", "attr: named value shown by name");
Check(!mat.Editable && mat.Ops[0] == LootItemAttributeOp.Exactly, "attr: material is = (or !=), not typed");
LootItemAttribute burden = rows.Single(r => r.Id == "L:5");
Eq(burden.Ops[0], LootItemAttributeOp.AtMost, "attr: burden defaults to at most");
Check(rows.Any(r => r.Id == "ratings" && r.ItemText == "5"), "attr: total ratings row (3 + 2)");
Check(rows.Any(r => r.Id == "D:62") && rows.Any(r => r.Id == "D:29"), "attr: weapon modifiers (doubles)");
Check(!rows.Any(r => r.Group == LootItemAttributes.GroupPet), "attr: no pet rows on a sword");
// "Items like this" ticks what it always required, nothing more.
LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like });
Eq(string.Join(",", like.Attributes.Where(r => r.On).Select(r => r.Id)),
"L:131,L:105,L:159,L:44,ratings,spell:Legendary Blood Thirst,spell:Epic Heart Thirst,spell:Major Strength,spell:Blood Drinker Self VI",
"attr: like ticks material, workmanship, wield skill, damage, ratings, the first 4 spells");
}
private static void TestAttrChoices()
{
// Burden at most 250 (typed), attack modifier exactly (two double conditions), material !=,
// and a row the item doesn't have (ignored).
List<LootEditItemChoice> c = Pick(
("L:5", true, LootItemAttributeOp.AtMost, "250"),
("D:62", true, LootItemAttributeOp.Exactly, ""),
("L:131", true, LootItemAttributeOp.Not, ""),
("L:9999", true, LootItemAttributeOp.AtLeast, "1"));
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = c });
string conds = string.Join(" ; ", d.Rule.Conditions.Select(Lines));
Eq(conds, "7:1 ; 1:^Gold Tachi$|1 ; 13:60|131 ; 2:250|5 ; 5:1.18|62 ; 4:1.18|62",
"attr: name + class, then the ticked rows in row order with their comparisons");
Eq(d.Attributes.Single(r => r.Id == "L:5").ToWire().Value, "250", "attr: the typed value goes back to the popup");
Check(d.Notes.Count == 0, "attr: no notes");
// A bad typed value keeps the item's and says so; an op the row doesn't offer is ignored.
LootItemRuleDraft bad = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.SpellOrBetter, "lots")) });
Check(bad.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: bad value: the item's 8, at least");
Check(bad.Notes.Any(n => n.StartsWith("Workmanship: 'lots'")), "attr: bad value: a note");
LootItemRuleDraft frac = BuildOk(Sword(), new() { Choices = Pick(("L:105", true, LootItemAttributeOp.AtLeast, "7.5")) });
Check(frac.Notes.Any(n => n.Contains("whole number")), "attr: a long row takes whole numbers only");
// "Items like this" with a row unticked: the choice wins over the default.
LootItemRuleDraft like = BuildOk(Sword(), new() { Match = LootItemMatch.Like, Choices = Pick(("L:131", false, LootItemAttributeOp.Exactly, "")) });
Check(!like.Rule.Conditions.Any(x => Lines(x) == "12:60|131"), "attr: like, material unticked");
Check(like.Rule.Conditions.Any(x => Lines(x) == "3:8|105"), "attr: like, the other defaults stay");
Check(!like.Notes.Any(n => n.Contains("more than 4 spells")), "attr: no 4-spell note once the player chooses");
}
private static void TestAttrSpellTiers()
{
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength$", "spell: cantrip or better");
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellAnyTier), "^(Minor|Major|Epic|Legendary) Strength$", "spell: cantrip any tier");
Eq(LootItemAttributes.SpellPattern("Major Strength", LootItemAttributeOp.SpellExact), "^Major Strength$", "spell: exact");
Eq(LootItemAttributes.SpellPattern("Blood Drinker Self VI", LootItemAttributeOp.SpellOrBetter), "^Blood Drinker Self (VI|VII|VIII)$", "spell: level or better");
Eq(LootItemAttributes.SpellPattern("Legendary Blood Thirst", LootItemAttributeOp.SpellOrBetter), "^(Legendary) Blood Thirst$", "spell: Legendary or better is Legendary");
Eq(LootItemAttributes.SpellPattern("Aura of Defender", LootItemAttributeOp.SpellOrBetter), "^Aura of Defender$", "spell: no tier: exact");
Eq(LootItemAttributes.SpellPattern("Major Strength (II)", LootItemAttributeOp.SpellOrBetter), "^(Major|Epic|Legendary) Strength \\(II\\)$", "spell: the rest is escaped");
string orBetter = LootItemAttributes.SpellPattern("Epic Heart Thirst", LootItemAttributeOp.SpellOrBetter);
Check(Regex.IsMatch("Legendary Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Legendary is better than Epic");
Check(!Regex.IsMatch("Major Heart Thirst", orBetter, RegexOptions.IgnoreCase), "spell: Major is not");
Check(!Regex.IsMatch("Epic Heart Thirsty", orBetter, RegexOptions.IgnoreCase), "spell: still the whole name");
List<LootItemAttribute> rows = BuildOk(Sword()).Attributes;
Eq(rows.Single(r => r.Id == "spell:Major Strength").Ops[0], LootItemAttributeOp.SpellOrBetter, "spell: a cantrip defaults to or better");
Eq(rows.Single(r => r.Id == "spell:Blood Drinker Self VI").Ops[0], LootItemAttributeOp.SpellExact, "spell: a leveled spell defaults to exact (as before)");
Eq(rows.Single(r => r.Id == "spell:Major Strength").ItemText, "Major cantrip", "spell: the tier is shown");
// Like with every spell ticked: no limit of four once chosen.
var many = new LootItemFacts { Name = "Robe", ObjectClass = (int)AcObjectClass.Clothing, Spells = { "Minor Focus", "Major Willpower", "Epic Strength", "Legendary Endurance", "Major Coordination" } };
LootItemRuleDraft d = BuildOk(many, new() { Match = LootItemMatch.Like, Choices = Pick(("spell:Major Coordination", true, LootItemAttributeOp.SpellAnyTier, "")) });
Eq(d.Rule.Conditions.Count(x => x.NodeType == VTankNodeTypes.SpellNameMatch), 5, "spell: a fifth spell can be ticked");
Check(d.Rule.Conditions.Any(x => Lines(x) == "0:^(Minor|Major|Epic|Legendary) Coordination$"), "spell: any tier pattern in the rule");
}
private static void TestAttrCantripCounts()
{
List<LootItemAttribute> rows = BuildOk(Sword()).Attributes;
Eq(string.Join(",", rows.Where(r => r.Id.StartsWith("cantrips:")).Select(r => r.Label + "=" + r.ItemText)),
"Legendary cantrips=1,Epic-or-better cantrips=2,Major-or-better cantrips=3", "cantrips: a row per tier the item has, highest first");
Check(rows.Any(r => r.Id == "spellcount" && r.ItemText == "4"), "cantrips: spell count");
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("cantrips:Epic", true, LootItemAttributeOp.AtLeast, "2"), ("spellcount", true, LootItemAttributeOp.AtLeast, "3")) });
Check(d.Rule.Conditions.Any(x => Lines(x) == "9:^(Epic|Legendary) ||2"), "cantrips: Spell Match, Epic or Legendary, at least 2");
Check(d.Rule.Conditions.Any(x => Lines(x) == "8:3"), "cantrips: spell count >= 3");
Check(LootItemRules.PreviewLines(d.Rule).Any(l => l.Contains(">= 2 spells matching")), "cantrips: preview in words");
}
private static void TestAttrPetEssence()
{
var wolf = new LootItemFacts
{
Id = 20, Name = "Fire Wolf Essence", ObjectClass = (int)AcObjectClass.Misc,
Ints = { [9053] = 12, [369] = 180, [9056] = 40, [362] = 1, [9075] = 2, [9070] = 1, [9054] = 16, [370] = 5, [92] = 30, [91] = 50 },
};
List<LootItemAttribute> rows = BuildOk(wolf).Attributes;
Check(rows.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: bond makes it an essence");
Eq(rows.Single(r => r.Id == "L:362").ItemText, "Primalist", "pet: mastery by name");
Eq(rows.Single(r => r.Id == "L:9054").ItemText, "Fire", "pet: captured damage type by name");
Check(rows.Any(r => r.Id == "L:92" && r.Label == "Uses left"), "pet: uses (Item group)");
LootItemRuleDraft like = BuildOk(wolf, new() { Match = LootItemMatch.Like });
string conds = string.Join(" ; ", like.Rule.Conditions.Select(Lines));
Eq(conds, "7:8 ; 2007:5 ; 3:12|9053 ; 3:180|369 ; 3:40|9056 ; 12:1|362 ; 3:2|9075",
"pet: like = class, ratings, bond, level, potency, mastery, mutations");
var flagged = new LootItemFacts { Name = "Odd Essence", ObjectClass = (int)AcObjectClass.Misc, IsPetEssence = true, Ints = { [9073] = 1 } };
Check(BuildOk(flagged).Attributes.Any(r => r.Id == "L:9073"), "pet: the plugin's IsPetEssence shows the group");
var notPet = new LootItemFacts { Name = "Jibril's Essence", ObjectClass = (int)AcObjectClass.Misc, Ints = { [9073] = 1 } };
Check(!BuildOk(notPet).Attributes.Any(r => r.Group == LootItemAttributes.GroupPet), "pet: a name alone isn't an essence");
}
private static void TestAttrNativeAndWire()
{
LootItemRuleDraft d = BuildOk(Sword(), new() { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, ""), ("spell:Major Strength", true, LootItemAttributeOp.SpellOrBetter, ""), ("cantrips:Legendary", true, LootItemAttributeOp.AtLeast, "")) });
var dropped = new List<string>();
LootRule? n = LootItemRules.ToNative(d.Rule, dropped);
Check(n != null && n.Conditions.Any(c => c.ToString().Contains("LongValKey") || c.ToString().Contains("[5]")), "native: burden converts");
Eq(dropped.Count, 2, "native: the two spell conditions are named as left out");
var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 4, AttributesSupported = true } };
foreach (LootItemAttribute r in d.Attributes) st.ItemDraft.Attributes.Add(r.ToWire());
string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState);
LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState);
LootEditItemAttribute? spell = back?.ItemDraft?.Attributes.FirstOrDefault(a => a.Id == "spell:Major Strength");
Check(back?.ItemDraft?.AttributesSupported == true, "wire: attributes supported round-trips");
Check(spell != null && spell.On && spell.Op == (int)LootItemAttributeOp.SpellOrBetter && spell.Ops.Count == 3, "wire: a row round-trips");
var cmd = new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { Choices = Pick(("L:5", true, LootItemAttributeOp.AtMost, "9")) } };
string cj = System.Text.Json.JsonSerializer.Serialize(cmd, LootEditJsonContext.Default.LootEditCommand);
LootEditCommand? cb = System.Text.Json.JsonSerializer.Deserialize(cj, LootEditJsonContext.Default.LootEditCommand);
Eq(cb?.Item?.Choices?.Single().Value, "9", "wire: choices round-trip");
LootEditCommand? old = System.Text.Json.JsonSerializer.Deserialize("{\"Op\":\"item_preview\",\"Item\":{\"Match\":2}}", LootEditJsonContext.Default.LootEditCommand);
Check(old?.Item != null && old.Item.Choices == null, "wire: an older engine's ask has no choices (defaults)");
}
private static void TestAttrVocab()
{
Eq(LootRuleText.ValueName(353, "4"), "Armor Rending", "vocab: imbue names");
Eq(LootRuleText.ValueName(362, "3"), "Naturalist", "vocab: summoning mastery");
Check(LootRuleText.LongKeys.Any(k => k.Id == 9053) && LootRuleText.LongKeys.Any(k => k.Id == 9075), "vocab: pet keys named");
Check(LootRuleText.LongKeys.Any(k => k.Id == 92 && k.Name.StartsWith("UsesRemaining")), "vocab: 92 is uses remaining");
Check(LootRuleText.LongKeys.Any(k => k.Id == 107 && k.Name == "ItemCurMana") && LootRuleText.LongKeys.Any(k => k.Id == 108 && k.Name == "ItemMaxMana"), "vocab: current and max mana");
var ids = LootRuleText.LongKeys.Select(k => k.Id).ToList();
Eq(ids.Count, ids.Distinct().Count(), "vocab: no long key named twice");
}
}

View file

@ -39,12 +39,19 @@ internal static partial class Program
{
("skills", LootRuleText.Skills), ("wield requirements", LootRuleText.WieldRequirements),
("materials", LootRuleText.Materials), ("damage types", LootRuleText.DamageTypes),
("creature types", LootRuleText.CreatureTypes),
})
{
Eq(table.Select(t => t.Id).Distinct().Count(), table.Length, $"{label}: ids unique");
Check(table.All(t => t.Name.Length > 0 && t.Name.All(ch => ch >= 32 && ch < 128)), $"{label}: names ASCII");
Eq(table.Select(t => t.Name).Distinct().Count(), table.Length, $"{label}: names unique");
}
Check(ReferenceEquals(LootRuleText.ValueTableFor(166), LootRuleText.CreatureTypes), "166 Slayer Type -> creature types");
Eq(LootRuleText.LongKeys.First(k => k.Id == 166).Name, "Slayer Type", "166 player-facing name");
Eq(LootRuleText.ValueName(166, "1"), "Olthoi", "ValueName 166/1 Olthoi");
Check(LootRuleText.CreatureTypes.Select(t => t.Name)
.SequenceEqual(LootRuleText.CreatureTypes.Select(t => t.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)),
"creature types listed alphabetically");
// Retail / ACE numbering (the old table had Light Weapons at 47, which is Missile Weapons).
string Skill(int id) => LootRuleText.Skills.First(s => s.Id == id).Name;

View file

@ -46,6 +46,7 @@ internal static partial class Program
RunLootAddTests(args);
RunT11Tests();
RunLootAddT11Tests();
RunLootAddAttributeTests();
RunUnknownNodeTests();
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");

View file

@ -255,6 +255,18 @@
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- Kite / pull-away -->
<DataGridTemplateColumn Header="Kite" Width="90" MinWidth="70">
<DataGridTemplateColumn.CellTemplate><DataTemplate>
<TextBlock Text="{Binding Kite}" Padding="3,1" VerticalAlignment="Center"
ToolTip.Tip="Default = DEFAULT row. Off = fight in place. PullAway = tag then run until pulled clear, then kill."/>
</DataTemplate></DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
<ComboBox ItemsSource="{Binding $parent[Window].((local:MainWindow)DataContext).KiteOptions}"
SelectedItem="{Binding Kite, Mode=TwoWay}"/>
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- Delete -->
<DataGridTemplateColumn Header="Del" Width="34" CanUserResize="False" CanUserSort="False">
<DataGridTemplateColumn.CellTemplate><DataTemplate>

View file

@ -29,6 +29,9 @@ public partial class MainWindow : Window
{ "None", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
public string[] PetOptions { get; } =
{ "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
/// <summary>RynthAi KiteModes: Default follows the DEFAULT row; PullAway tags then runs clear.</summary>
public string[] KiteOptions { get; } =
{ "Default", "Off", "PullAway" };
private string _charFolder = string.Empty;
private string _monstersPath = string.Empty;

View file

@ -23,6 +23,7 @@ public class MonsterRule : INotifyPropertyChanged
private int _offhandId;
private int _preferredAmmoItemId;
private string _petDamage = "PAuto";
private string _kite = "Default";
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
/// <summary>The plugin's rule group label. Kept and editable here (before 2026-10-05 an
@ -58,6 +59,8 @@ public class MonsterRule : INotifyPropertyChanged
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
/// <summary>Pull-away kite: Default (follow DEFAULT row), Off, or PullAway. RynthAi KiteModes.</summary>
public string Kite { get => _kite; set { _kite = value ?? "Default"; OnPropertyChanged(); } }
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
/// or one added later), written back unchanged.</summary>
@ -94,6 +97,7 @@ public class MonsterRule : INotifyPropertyChanged
OffhandId = _offhandId,
PreferredAmmoItemId = _preferredAmmoItemId,
PetDamage = _petDamage,
Kite = _kite,
};
}
@ -122,6 +126,7 @@ public class MonsterRule : INotifyPropertyChanged
OffhandId = src.OffhandId;
PreferredAmmoItemId = src.PreferredAmmoItemId;
PetDamage = src.PetDamage;
Kite = src.Kite;
}
public event PropertyChangedEventHandler? PropertyChanged;

View file

@ -113,10 +113,16 @@ internal static unsafe class FakeHost
/// <summary>When true (the default) a give lands at once, as the server does when it isn't busy:
/// the item goes to the target. False = the server hasn't taken it (still carried).</summary>
public static bool GiveLands = true;
/// <summary>Optional: runs for every give instead of the default landing (a test's own server: NPC takes one per give, busy, ...).</summary>
public static Action<uint, uint, int>? GiveHandler;
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
public static bool StopCalls;
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
public static int Stops;
/// <summary>Opt-in: wires MeleeAttack and MissileAttack; calls land in <see cref="AttackCalls"/>.</summary>
public static bool AttackSendCalls;
/// <summary>Every melee or missile attack (kind, target, height, power), in order (opt-in with <see cref="AttackSendCalls"/>).</summary>
public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new();
/// <summary>Opt-in: wires SetMotion; calls land in <see cref="MotionCalls"/>.</summary>
public static bool SetMotionCalls;
/// <summary>Every SetMotion (motion, on), in order (opt-in with <see cref="SetMotionCalls"/>).</summary>
@ -139,6 +145,8 @@ internal static unsafe class FakeHost
/// and is counted in <see cref="RefusedIdRequests"/>, not in <see cref="IdRequests"/>.</summary>
public static bool RequestIdAccepts = true;
public static int RefusedIdRequests;
/// <summary>False = UseObject returns 0 (the engine did not send it); the use is still recorded in <see cref="Uses"/>.</summary>
public static bool UseObjectAccepts = true;
/// <summary>Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and
/// GetCurrentCombatMode (answering <see cref="CombatModeValue"/>). Tests written without
/// them keep seeing those calls as absent.</summary>
@ -261,7 +269,9 @@ internal static unsafe class FakeHost
public static void Reset()
{
EquippedCalls = false; EquippedNotReady = false; Equipped.Clear();
#if !RYNTHILT_TESTS
RynthCore.Plugin.RynthAi.EquippedState.Invalidate();
#endif
Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear();
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
@ -272,9 +282,9 @@ internal static unsafe class FakeHost
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
RequestIdAccepts = true; RefusedIdRequests = 0;
RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
WeenieErrorCalls = false; WeenieErrSeq = 0; WeenieErrCode = WeenieErrEvent = WeenieErrObject = 0;
@ -349,6 +359,11 @@ internal static unsafe class FakeHost
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
if (SetMotionCalls)
api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&SetMotion;
if (AttackSendCalls)
{
api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MeleeAttack;
api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MissileAttack;
}
if (Nav3DCalls)
{
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
@ -778,6 +793,12 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MissileAttack(uint target, int height, float power) { AttackCalls.Add(("missile", target, height, power)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; }
@ -803,7 +824,10 @@ internal static unsafe class FakeHost
private static int GiveObjectTo(uint item, uint target, int amount)
{
Gives.Add((item, target, amount));
if (GiveLands && amount == 0) Containers[item] = target;
if (GiveHandler != null) { GiveHandler(item, target, amount); return 1; }
// The server takes the whole object for amount 0, or for an amount that covers the stack (a single
// item has no StackCount: its stack is 1, so an explicit 1 takes it whole).
if (GiveLands && (amount == 0 || amount >= (Ints.TryGetValue((item, 12), out int stack) ? stack : 1))) Containers[item] = target;
return 1;
}
@ -813,7 +837,7 @@ internal static unsafe class FakeHost
private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return 1; }
private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return UseObjectAccepts ? 1 : 0; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectState(uint id, uint* state)
{

View file

@ -92,10 +92,13 @@ internal static class Program
TargetingTests.Register(runner);
LootAddItemTests.Register(runner);
GiveTests.Register(runner);
IdRefusalTests.Register(runner);
DungeonMapBakeTests.Register(runner);
MonsterEditorTests.Register(runner);
InstallPathsTests.Register(runner);
PetRefillTests.Register(runner);
AutoStackTests.Register(runner);
RingEvadeTests.Register(runner);
IgnoreMonsterTests.Register(runner);
WorldCacheTypedTests.Register(runner);
NavOverlayTests.Register(runner);
@ -128,12 +131,15 @@ internal static class Program
VTankHotkeyTests.Register(runner);
OneTouchHealTests.Register(runner);
SaveFailureTests.Register(runner);
EnvironmentImpactTests.Register(runner);
SkCombatAddonTests.Register(runner);
DoorTests.Register(runner);
ServerPolicyTests.Register(runner);
BlankLoadTests.Register(runner);
GiveProfileTests.Register(runner);
TinkerTests.Register(runner);
LauncherSwapTests.Register(runner);
MissileCraftingTests.Register(runner);
SelfRatingsTests.Register(runner);
IltClientLookupTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);

View file

@ -66,7 +66,8 @@ internal static class ActionPacingTests
r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal);
r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing);
r.Add("corpse id: a refused RequestId is not recorded as asked - the next evaluation asks again and the accepted one goes out", CorpseIdRefusedRetried);
r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, with no give-up cap", CorpseIdReaskedWithoutData);
r.Add("corpse id: an accepted request with no data is asked again after 3 s (not before), once per 3 s, at most 3 re-asks per corpse", CorpseIdReaskedWithoutData);
r.Add("corpse id: Loot From All Corpses needs no killer name - the first request goes out, no re-ask ever follows; My Kills Only gives up after 3 re-asks, a new corpse starts over", CorpseIdAllCorpsesNoReask);
r.Add("corpse id: two corpses in range, no data for either - only the targeted one re-asks; the other stays at one accepted request (a refused one is still retried)", CorpseIdOnlyCandidateReasks);
r.Add("corpse id: 20 uncached corpses, a refusal window, then accept - at most 2 requests in the first accepted tick, the target among them; refused retries are 250 ms apart", CorpseIdBurstCapped);
r.Add("corpse id: the open container is a candidate and re-asks; delete and the >200 prune clear every id map", CorpseIdOpenContainerAndCleanup);
@ -871,13 +872,46 @@ internal static class ActionPacingTests
Check.Eq(Asked(), 2, "1 s after the re-ask: waits");
_t += 2_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 3, "one re-ask per 3 s, and no cap");
Check.Eq(Asked(), 3, "one re-ask per 3 s");
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 4, "the third re-ask is the last");
for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 13, "ten more 3 s periods, ten more asks");
Check.Eq(Asked(), 4, "ten more 3 s periods, no more asks: the corpse is given up on");
FakeHost.Strings[(Corpse, LongDescKey)] = $"Killed by {Me}.";
_t += 3_000;
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 13, "once the data has arrived nothing more is asked");
Check.Eq(Asked(), 4, "and once the data has arrived nothing is asked either");
});
private static void CorpseIdAllCorpsesNoReask() => Paced(() =>
{
// All Corpses: the killer name decides nothing, so no stream of requests (each accepted one
// raises the client's busy count). The one first request still goes out: the radar colours
// your own kills from the LongDesc it brings.
var (bot, obj) = CorpseIdRig();
bot.S.LootOwnership = 2;
int Asked() => FakeHost.IdRequests.Count(i => i == Corpse);
bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 1, "All Corpses: the first request goes out");
for (int i = 0; i < 6; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 1, "All Corpses: no re-ask in 18 s without data");
object dec = bot.Call("EvaluateCorpseLootDecision", obj)!;
Check.True((bool)dec.GetType().GetProperty("ShouldLoot")!.GetValue(dec)!, "the corpse is looted either way");
// The same corpse in My Kills Only: the cap applies, the count is per corpse and a deleted
// corpse starts over.
bot.S.LootOwnership = 0;
_t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 2, "My Kills Only: the name is needed, so it re-asks");
for (int i = 0; i < 10; i++) { _t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj); }
Check.Eq(Asked(), 4, "and stops after the third re-ask");
bot.Call("HandleCorpseObjectDeleted", Corpse);
_t += 3_000; bot.Call("EvaluateCorpseLootDecision", obj);
Check.Eq(Asked(), 5, "a corpse that comes back (deleted and created again) starts over");
var counts = bot.Get<System.Collections.Generic.Dictionary<int, int>>("_corpseIdAskCount");
bot.Call("HandleCorpseObjectDeleted", Corpse);
Check.False(counts.ContainsKey(unchecked((int)Corpse)), "delete clears _corpseIdAskCount");
});
private static void CorpseIdOnlyCandidateReasks() => Paced(() =>
{
@ -900,7 +934,7 @@ internal static class ActionPacingTests
Check.Eq(Asked(Corpse), 1, "the candidate: refused once, then one accepted request");
Check.Eq(Asked(CorpseB), 1, "the other corpse: a refused request is retried, one accepted request");
for (int i = 0; i < 4; i++) { _t += 3_000; Both(); }
Check.Eq(Asked(Corpse), 5, "no data: the candidate re-asks once per 3 s");
Check.Eq(Asked(Corpse), 4, "no data: the candidate re-asks once per 3 s, three times at most");
Check.Eq(Asked(CorpseB), 1, "the other corpse never asks a second time");
bot.Set("_targetCorpseId", unchecked((int)CorpseB));
_t += 3_000; Both();

View file

@ -0,0 +1,38 @@
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// AutoStack (Loot/InventoryManager.cs): the group key and the merge-progress rule. From Silentkelpie's
// PR 12 (group by WCID: two stacks with the same name but different weenies never merge, and AutoStack
// retried them forever), plus the partial fill: a pair whose total is over the max is still merged
// (the server fills the target, the source survives smaller) and that counts as progress.
internal static class AutoStackTests
{
public static void Register(Runner r)
{
r.Add("autostack: stacks group by WCID; the name is only the fallback while the WCID is unknown", GroupKey);
r.Add("autostack: a partial fill (target grew, source shrank) is progress; an untouched pair is not", Progress);
}
private static void GroupKey()
{
Check.True(InventoryManager.StackGroupKey(42517, "Coalesced Mana") != InventoryManager.StackGroupKey(42518, "Coalesced Mana"),
"same name, different WCIDs: separate groups");
Check.Eq(InventoryManager.StackGroupKey(42517, "Coalesced Mana"), InventoryManager.StackGroupKey(42517, "Coalesced Mana (renamed)"),
"same WCID: one group whatever the label says");
Check.Eq(InventoryManager.StackGroupKey(0, "Taper"), InventoryManager.StackGroupKey(0, "Taper"), "no WCID: the name groups");
Check.True(InventoryManager.StackGroupKey(0, "Taper") != InventoryManager.StackGroupKey(5, "Taper"), "known and unknown WCID do not mix");
Check.True(InventoryManager.StackGroupKey(7, null).Length > 0, "a null name is safe");
}
private static void Progress()
{
// 90 + 20 over a max of 100: the server fills the target to 100 and leaves 10 in the source.
Check.True(InventoryManager.MergeProgressed(90, 20, 100, 10), "partial fill");
Check.True(InventoryManager.MergeProgressed(30, 20, 50, 20), "target grew (source count read late)");
Check.True(InventoryManager.MergeProgressed(30, 20, 30, 0), "source emptied");
Check.False(InventoryManager.MergeProgressed(30, 20, 30, 20), "nothing changed: not progress");
Check.False(InventoryManager.MergeProgressed(0, 20, 30, 20), "no recorded counts: not progress");
}
}

View file

@ -70,6 +70,7 @@ internal static class BuffTests
r.Add("buff filter: the skip line groups by reason, is capped, and repeats only when it changes", SkipLineGroupedAndCapped);
r.Add("buff filter: the weapon kit is cached for a second, and rebuilt when its inputs change", KitCached);
r.Add("buff filter: skipped buffs are named, once per run", FilterVisibility);
r.Add("buff filter: untrained skills alone never print a chat line (log, page and /ra buff skipped keep them)", UntrainedSkillIsQuiet);
r.Add("buff filter: SkipUnusableBuffs defaults on, loads, saves, bridges, is in the settings map", SkipUnusableSetting);
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
@ -93,6 +94,11 @@ internal static class BuffTests
r.Add("buff upgrade: a late line the cast tracker credits to an earlier send does not confirm the pending cast", UpgradeLateLineFromEarlierSend);
r.Add("buff upgrade: two upgrade no-shows do not park the family; its lower level running low is recast", UpgradeNoShowsDoNotPark);
r.Add("buff upgrade: two item spell upgrades with no chat do not park the family; its lower level running low is recast", UpgradeArmorNoChatDoesNotPark);
r.Add("buff upgrade: an upgrade an item spell never lands is parked, not looped; the lower level is still refreshed and the park ends", UpgradeArmorNoChatParksUpgrade);
r.Add("buff upgrade: three silent self-buff no-shows park the upgrade only; the lower level is still refreshed", UpgradeNoShowsParkUpgrade);
r.Add("buff upgrade: an in-run upgrade the server never answers is parked and the force run ends", UpgradeNoShowInRunEnds);
r.Add("buff upgrade: a confirmed upgrade resets the no-show count", UpgradeConfirmedResetsNoShows);
r.Add("buff upgrade: Cancel Buffing ends the pending upgrade", UpgradeCancelEndsPending);
r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve);
}
@ -1389,10 +1395,12 @@ internal static class BuffTests
/// <summary>Lets the pending <paramref name="id"/> reach its give-up unanswered twice (it is resent
/// in between); returns the give-ups done. Every other cast is confirmed.</summary>
private static int FailTwice(BeatRig h, int id)
private static int FailTwice(BeatRig h, int id) => FailTimes(h, id, 2);
private static int FailTimes(BeatRig h, int id, int times)
{
int gaveUp = 0;
for (int k = 0; k < 20 && gaveUp < 2; k++)
for (int k = 0; k < 20 && gaveUp < times; k++)
{
if (h.R.B.PendingSpellId != id) { if (h.Beats(40, x => x == id) == 0) break; continue; }
h.SendLongAgo(6);
@ -1448,6 +1456,133 @@ internal static class BuffTests
Check.True(h.Beats(40, id => FamilyOf(id) == fam) != 0, "running low: recast");
}
private static bool Has(BuffManager b, string field, int key) => ((System.Collections.IDictionary)Fld<object>(b, field)).Contains(key);
/// <summary>The registry as the first run left it (every player buff of the suite at tier 6), CEM with <paramref name="cemLeft"/> s left.</summary>
private static (string, double)[] SixRegistry(int cem, double cemLeft) =>
FakeHost.Casts.Select(c => c.SpellId).Where(id => !BuffManager.IsItemEnchantment(NameOf(id))).Distinct()
.Select(id => (NameOf(id), FamilyOf(id) == cem ? cemLeft : 3000.0)).ToArray();
// Review finding (PR 15): an upgrade that is a SILENT no-show was never struck, parked or counted, so it
// was recast at every give-up forever (12x/minute), and a force/batch run never ended. Now: after three in
// a row the upgrade alone is parked; the family is not blacklisted and its lower level still refreshes.
private static void UpgradeNoShowsParkUpgrade()
{
int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI");
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeCreature)] = (340, 2);
h.R.Live(SixRegistry(cem, 3000));
int seven = h.Beats(60, id => FamilyOf(id) == cem && LevelOf(id) == 7);
Check.True(seven != 0, "CEM 7 is sent over the live VI");
Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows");
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "sent three times, not a fourth: the upgrade is parked");
Check.False(Parked(h.R, cem), "the family itself is not parked");
// Nothing more goes out for it, and the run (the batch the upgrade started) ends.
h.Beats(150, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == seven), 3, "still three after 150 more beats");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends");
Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending");
// The level it was cast over runs low: a normal refresh goes out (not counted as an upgrade).
int upgrades = h.R.B.BuffUpgrades;
h.R.Live(SixRegistry(cem, 100));
Check.True(h.Beats(150, id => FamilyOf(id) == cem) != 0, "the lower level running low is recast while the upgrade is parked");
Check.Eq(h.R.B.BuffUpgrades, upgrades, "and that cast is not an upgrade");
Check.False(Parked(h.R, cem), "the family is still not parked");
}
// The item spell twin (armor lost on death / weapon swapped, its lower record still unexpired).
private static void UpgradeArmorNoChatParksUpgrade()
{
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeItem)] = (340, 2);
int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7);
Check.True(item7 != 0, "an item spell is upgraded to 7: " + NameOf(item7));
int fam = FamilyOf(item7);
Check.Eq(FailTimes(h, item7, 3), 3, "three no-chat give-ups");
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "sent three times, not a fourth");
Check.False(Parked(h.R, fam), "the family itself is not parked");
h.Beats(150, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), 3, "still three after 150 more beats");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the run ends");
// Its VI record runs low: the family is recast (a normal refresh, not an upgrade).
int upgrades = h.R.B.BuffUpgrades;
object rec = ((System.Collections.IDictionary)Fld<object>(h.R.B, "_itemSpellTimers"))[fam]!;
rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(100));
Check.True(h.Beats(60, id => FamilyOf(id) == fam) != 0, "running low: recast while the upgrade is parked");
Check.Eq(h.R.B.BuffUpgrades, upgrades, "not an upgrade");
Check.False(Parked(h.R, fam), "the family is not parked");
// The park is time-boxed: once it ends the upgrade is tried again.
h.R.B.CancelBuffing();
rec.GetType().GetField("ExpiresAt")!.SetValue(rec, DateTime.Now.AddSeconds(3000));
((System.Collections.IDictionary)Fld<object>(h.R.B, "_upgradeParkedUntil"))[fam] = DateTime.Now.AddSeconds(-1);
Check.True(h.Beats(80, id => id == item7) != 0, "after the park ends the upgrade is cast again");
}
// An explicit force run with an upgrade the server never answers: parked after three, the run ends.
private static void UpgradeNoShowInRunEnds()
{
int cem = FamilyOfBuff("Creature Enchantment Mastery Self VI");
var h = new BeatRig(300);
h.R.Live(("Strength Self I", 3000));
h.R.B.ForceFullRebuff();
int n = 0;
int seven = h.Beats(150, id => { if (++n == 3) FakeHost.Skills[(Player, STypeCreature)] = (340, 2); return FamilyOf(id) == cem && LevelOf(id) == 7; });
Check.True(seven != 0, "CEM 7 is sent in the run, over the VI it cast");
Check.Eq(FailTimes(h, seven, 3), 3, "three no-shows");
h.Beats(200, _ => false);
// The registry here never shows the run's VIs, so once the upgrade is parked CEM is cast as an ordinary
// buff with no timer, and the usual two-strike no-show park ends that: three upgrade sends + at most two.
int sends = FakeHost.Casts.Count(c => c.SpellId == seven);
Check.True(sends <= 3 + 2, $"bounded: {sends} sends of CEM 7");
Check.False(h.R.B.GetStateSnapshot().IsForceRebuffing, "the force run ends (it kept buffing's priority for good)");
Check.Eq(h.R.B.PendingSpellId, 0, "nothing pending");
}
// Confirmed upgrades are unchanged: they land, and they reset the count (the next upgrade starts from zero).
private static void UpgradeConfirmedResetsNoShows()
{
var h = new BeatRig(300);
h.FirstRun();
FakeHost.Skills[(Player, STypeItem)] = (340, 2);
int item7 = h.Beats(80, id => BuffManager.IsItemEnchantment(NameOf(id)) && LevelOf(id) == 7);
Check.True(item7 != 0, "an item spell is upgraded to 7");
int fam = FamilyOf(item7);
Check.Eq(FailTimes(h, item7, 2), 2, "two no-chat give-ups");
Check.Eq(h.R.B.PendingSpellId, item7, "sent again");
Check.True(Has(h.R.B, "_upgradeNoShowCounts", fam), "two are counted");
h.R.B.OnChatWindowText($"You cast {NameOf(item7)} on Rune Robe", 7); // it lands
Check.False(Has(h.R.B, "_upgradeNoShowCounts", fam), "the count is reset by the landing");
Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "nothing parked");
int sends = FakeHost.Casts.Count(c => c.SpellId == item7);
h.Beats(60, _ => false);
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == item7), sends, "landed at 7: not cast again");
// The record falls back to VI (armor swapped): the upgrade gets a full three tries again.
object rec = ((System.Collections.IDictionary)Fld<object>(h.R.B, "_itemSpellTimers"))[fam]!;
rec.GetType().GetField("SpellLevel")!.SetValue(rec, 6);
Check.True(h.Beats(80, id => id == item7) != 0, "the upgrade is cast again");
Check.Eq(FailTimes(h, item7, 2), 2, "two more no-shows");
Check.Eq(h.R.B.PendingSpellId, item7, "not parked: sent again after the second");
Check.False(Has(h.R.B, "_upgradeParkedUntil", fam), "the count started from zero");
}
// Cancelling the buff step left the pending upgrade behind.
private static void UpgradeCancelEndsPending()
{
var (rig, seven) = PendingCem7();
Check.True(seven != 0 && rig.B.PendingSpellId == seven, "CEM 7 is pending");
Check.Eq(Fld<int>(rig.B, "_pendingUpgradeSpellId"), seven, "as an upgrade");
rig.B.CancelBuffing();
Check.Eq(rig.B.PendingSpellId, 0, "cancelled");
Check.Eq(Fld<int>(rig.B, "_pendingUpgradeSpellId"), 0, "the upgrade is no longer pending");
}
// No limit and no rest, through OnHeartbeat: an always-fizzling CEM 7 is sent on
// every beat (one per answer), the late VI line confirms nothing, and nothing goes out unanswered.
private static void UpgradeCapViaHeartbeat()
@ -1637,8 +1772,15 @@ internal static class BuffTests
Check.False(rig.B.GetStateSnapshot().IsForceRebuffing, "/ra buff cancel ends it");
FakeHost.Chat.Clear();
int kitRuns = rig.B.KitComputations;
Cmd("skipped");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers");
Check.Eq(FakeHost.Chat.Count, 0, "/ra buff skipped only queues the report: the command thread builds nothing and says nothing");
Check.Eq(rig.B.KitComputations, kitRuns, "and never touches the pump's weapon-kit state");
rig.B.OnHeartbeat();
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter")), "/ra buff skipped answers from the next heartbeat");
FakeHost.Chat.Clear();
rig.B.OnHeartbeat();
Check.Eq(FakeHost.Chat.Count, 0, "once per request");
FakeHost.Chat.Clear();
Cmd();
Check.True(FakeHost.Chat.Any(c => c.Contains("/ra buff force")), "no word: the help");
@ -1751,7 +1893,8 @@ internal static class BuffTests
Check.True(lines[0].Contains("skill untrained: ") && lines[0].Contains("Heavy Weapon"), "it names the untrained mastery and why: " + lines[0]);
Check.True(lines[0].Contains("no melee or missile weapon listed: Blood Drinker"), "and the weapon aura and why: " + lines[0]);
Check.False(lines[0].Contains("Spirit Drinker"), "but not what stays");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips")), "the same line goes to chat");
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("no melee or missile weapon listed")), "a line goes to chat for the aura");
Check.False(FakeHost.Chat.Any(c => c.Contains("Buff run skips") && c.Contains("skill untrained")), "but the untrained skill stays out of the chat line");
Check.True(rig.B.FilterSkipSummary().Contains("Swift Killer"), "the settings page reads the same list");
// The automatic batch logs it too, once.
@ -1769,6 +1912,27 @@ internal static class BuffTests
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:")), 0, "nothing skipped: no line");
}
// An untrained skill is the normal state of most characters. It must not print a chat line at every buff run.
private static void UntrainedSkillIsQuiet()
{
var rig = SuiteRig(MeleeItem, WandItem);
FakeHost.Skills[(Player, SkillHeavy)] = (10, 1); // untrained, and nothing else is skipped
rig.Live(("Strength Self I", 3000));
rig.B.ForceFullRebuff();
Check.True(rig.B.FilterSkips.Count > 0 && rig.B.FilterSkips.All(s => s.Reason == "skill untrained"), "only untrained skills are skipped");
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "no chat line for untrained skills alone");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] filter skips:") && l.Contains("skill untrained")), 1, "the log keeps it");
Check.True(rig.B.FilterSkipSummary().Contains("skill untrained: ") && rig.B.FilterSkipSummary().Contains("Heavy Weapon"), "the Buffing page summary keeps it");
rig.B.RequestSkipReport();
rig.B.OnHeartbeat();
Check.True(FakeHost.Chat.Any(c => c.Contains("Buff filter skips: ") && c.Contains("skill untrained")), "so does /ra buff skipped");
// A later run stays quiet in chat too.
FakeHost.Chat.Clear();
rig.B.ForceFullRebuff();
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Buff run skips")), 0, "still quiet");
}
private static void KitEdgeCases()
{
// A listed item the cache keeps unclassified (a Misc-typed thing): nothing is filtered.

View file

@ -28,6 +28,8 @@ internal static class CombatHookTests
public static void Register(Runner r)
{
r.Add("combat hook: the decided spell reaches the cast (hook off: RynthAi's bolt)", DecidedSpellIsCast);
r.Add("combat hook: a rule with no attack shapes enabled is not asked and not cast at, script or not", ScriptRespectsNoAttackShapes);
r.Add("combat hook: shutdown clears the UseDone reader (it captured the host)", ShutdownDropsUseDoneReader);
r.Add("combat hook: a decline casts RynthAi's own spell the same tick", DeclineGoesNative);
r.Add("combat hook: no answer by the deadline - RynthAi's spell, the timeout logged once a minute", TimeoutGoesNative);
r.Add("combat hook: a lapsed lease is native; another owner is refused while the lease is live", LeaseExpiry);
@ -236,6 +238,45 @@ internal static class CombatHookTests
Check.Eq((next.LastSeq, next.LastSpell, next.LastTarget), (req.Seq, (uint)drain, (uint)Target), "ctx.last is the previous cast");
});
// A rule with every attack shape off means no offensive cast at that monster; a script's attack is no exception.
private static void ScriptRespectsNoAttackShapes() => Guard(() =>
{
int drain = Id("Drain Health Other V");
var off = new AttackRig();
off.S.MonsterRules.Clear();
off.S.MonsterRules.Add(new MonsterRule { Name = "Default", DamageType = "Fire", UseBolt = false, UseArc = false, UseStreak = false, UseRing = false, UseBlast = false, UseWall = false });
Claim(Atk);
off.Attack();
Check.Eq(CombatHook.Attack.Opened, 0, "no shapes: the script is not even asked");
Check.Eq(off.C.LastCombatSkipReason, "no-attack-shapes", "skipped for the rule");
Check.False(off.C.ScriptHeld, "and not held for an answer");
Check.Eq(FakeHost.Casts.Count, 0, "nothing cast");
// Control: the same script with a shape on is asked and its spell is cast.
var on = new AttackRig();
Claim(Atk);
ScriptCast(on, drain);
Check.Eq(CombatHook.Attack.Opened, 1, "a shape on: the script is asked");
Check.True(FakeHost.Casts.Any(c => c.SpellId == drain), "and its spell is cast");
});
// The UseDone reader the plugin installs captures its host; a shut-down plugin must not keep it.
private static void ShutdownDropsUseDoneReader() => Guard(() =>
{
CombatHook.LastUseDone = () => (1, 0u);
CombatHookInterface.Shutdown(); // PluginExports.Shutdown calls it for every unload
Check.Null(CombatHook.LastUseDone, "the exported shutdown clears the reader");
FakeHost.Reset();
var host = FakeHost.Create(Player);
var plugin = new RynthAiPlugin();
PacerEdgeTests.SetHost(plugin, host);
CombatHook.LastUseDone = () => (1, 0u);
plugin.Shutdown();
Check.Null(CombatHook.LastUseDone, "and so does the plugin's own Shutdown");
});
private static void DeclineGoesNative() => Guard(() =>
{
var rig = new AttackRig();

View file

@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
@ -41,6 +42,9 @@ internal static class CorpseCloseTests
r.Add("corpse close: the next corpse is opened without closing the finished one; its late close doesn't disturb the new open", NextCorpseWithoutClose);
r.Add("corpse close: a held-back close is sent when no other corpse is opened in time, and when the macro stops", DeferredCloseFallback);
r.Add("loot pickup: a pickup that merges into a pack stack is confirmed when the stack grows, not after 4 s", StackMergeConfirmed);
r.Add("loot timeout: a pickup held for a cast's answer does not time the corpse out; the pickup goes on the answer", HeldPickupKeepsCorpseClock);
r.Add("loot timeout: an unheld stall (nothing to take, nothing held) still times the corpse out", UnheldStallStillTimesOut);
r.Add("corpse close: the close is held back only when the next corpse can be claimed now (not while buffing), and a hold that starts later ends the wait", DeferredCloseNeedsClaimableCorpse);
}
private static long _now;
@ -54,6 +58,21 @@ internal static class CorpseCloseTests
finally { RynthAiPlugin.CorpseClock = old; }
}
/// <summary>The pacer (and the audits whose stop / use times it reads) on the same hand-moved clock as the loot.</summary>
private static void PacerOn()
{
ActionPacer.Reset(); ActionPacer.Enabled = true; ActionPacer.NowMs = () => _now;
MoveAudit.Reset(); MoveAudit.NowMs = () => _now;
UseAudit.NowMs = () => _now;
}
private static void PacerOff()
{
ActionPacer.Enabled = false; ActionPacer.Reset(); ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset(); MoveAudit.NowMs = () => Environment.TickCount64;
UseAudit.NowMs = () => Environment.TickCount64;
}
private static void Corpse(uint id, float dx)
{
FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone";
@ -227,6 +246,101 @@ internal static class CorpseCloseTests
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "the last corpse is closed at once");
});
// A pickup is refused (ACE: YoureTooBusy) while the server owes an answer to a cast, so it waits
// (ActionPacer.Outstanding). The corpse's own clock (LootCorpseTimeoutMs) used to keep running
// through that wait, and the first tick after the answer abandoned an OPENED corpse, which gets
// the 30-minute completed mark: its loot was skipped.
private static void HeldPickupKeepsCorpseClock() => Clocked(() =>
{
World(twoCorpses: false);
FakeHost.ServerGates = true; // GetUseDoneSeq, GetCastBusyState
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 2000;
PacerOn();
try
{
bot.Create(CorpseA, GemA);
bot.Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
// A cast goes out and has no answer yet when the contents arrive: the pickup waits for it,
// two and a half corpse timeouts, still inside the pacer's own limit (CastMaxMs, 7 s).
ActionPacer.Begin(host, PacedKind.Cast, 0, "Bloodstone Bolt VII", "Combat", FakeHost.UseDoneSeq);
bot.TickFor(5_000);
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "no pickup while the cast is unanswered");
Check.True(Logged("pickup waits - the server still owes an answer"), "the hold is logged");
Check.False(Logged("abandoning corpse"), "the corpse is not abandoned while the pickup is held");
Check.Eq(bot.Get<int>("_openedContainerId"), unchecked((int)CorpseA), "and stays the open corpse");
FakeHost.UseDone(0); // the cast is answered
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == GemA); i++) { _now += 20; bot.Tick(); }
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == GemA), "the pickup goes on the answer");
FakeHost.Containers[GemA] = Player;
for (int i = 0; i < 200 && !bot.Completed(CorpseA); i++) { _now += 20; bot.Tick(); }
Check.True(bot.Completed(CorpseA), "and the corpse is completed by its loot, not by the timeout");
Check.False(Logged("abandoning corpse"), "never abandoned");
}
finally { PacerOff(); }
});
private static void UnheldStallStillTimesOut() => Clocked(() =>
{
World(twoCorpses: false);
FakeHost.ServerGates = true;
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.S.LootCorpseTimeoutMs = 2000;
bot.S.LootEmptyCorpseMs = 60_000; // the corpse neither shows items nor is called empty: a stall
PacerOn();
try
{
bot.Create(CorpseA); // the gem is never seen
bot.Tick();
Check.True(FakeHost.Uses.Contains(CorpseA), "corpse A is opened");
FakeHost.UseDone(0);
FakeHost.GroundContainer = CorpseA;
bot.P.OnViewObjectContents(CorpseA);
bot.TickFor(1_500);
Check.False(Logged("abandoning corpse"), "inside the timeout");
bot.TickFor(1_000);
Check.True(Logged("abandoning corpse") && Logged("(timeout)"), "an unheld stall is still abandoned on the timeout");
}
finally { PacerOff(); }
});
private static void DeferredCloseNeedsClaimableCorpse() => Clocked(() =>
{
// The next-corpse test itself: B is in range and A is done. Buffing holds every claim, so
// there is nothing to wait for.
World(twoCorpses: true);
var host = FakeHost.Create(Player);
var bot = new Bot(host);
bot.Create(CorpseA, CorpseB, GemA, GemB);
bot.Get<Dictionary<int, long>>("_completedCorpses")[unchecked((int)CorpseA)] = _now;
bool Other() => (bool)typeof(RynthAiPlugin).GetMethod("OtherCorpseToLoot", Any)!.Invoke(bot.P, new object[] { unchecked((int)CorpseA) })!;
Check.True(Other(), "B is in range and claimable: the close is worth deferring");
bot.S.BotAction = "Buffing";
Check.False(Other(), "buffing holds every claim: no deferral");
bot.S.BotAction = "Default";
Check.True(Other(), "and it is back once the hold ends");
// A hold that starts while the close is deferred ends the wait at once (not after 3 s).
World(twoCorpses: true);
var host2 = FakeHost.Create(Player);
var bot2 = new Bot(host2);
bot2.Create(CorpseA, CorpseB, GemA, GemB);
LootCorpseA(bot2);
Check.Eq(FakeHost.Closes.Count, 0, "held back while B can be claimed");
bot2.S.BotAction = "Buffing";
_now += 20; bot2.Tick(BotActivity.Looting);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{CorpseA:X8}", "buffing began: A is closed at once, once");
Check.True(Logged("the next corpse can't be claimed now"), "and the reason is logged");
});
private static void StackMergeConfirmed() => Clocked(() =>
{
World(twoCorpses: false);

Some files were not shown because too many files have changed in this diff Show more