diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index b9d250b..0a64eec 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -3594,13 +3594,23 @@ public partial class CombatManager : IDisposable
return any ? CreatureWeakness.FromAppraisal(m) : null;
}
+ ///
+ /// Optional UtilityBelt damage seed lookup (wcid, name) → damage types best first, or null.
+ /// Set by the plugin when the seed store loads; null (default) leaves the ranking as before.
+ /// Called on the combat thread.
+ ///
+ internal Func?>? MobSeedLookup { get; set; }
+
/// The same by wcid and name; (optional) reads a live creature type.
internal CreatureWeakness.Ranking? WeaknessFor(uint wcid, string? name, int objectId = 0)
{
name ??= "";
int ctype = CreatureTypeOf(wcid, name, objectId);
string learned = wcid != 0 ? _damageStore?.GetBestElement(wcid) ?? "" : "";
- return CreatureWeakness.Rank(wcid, name, ctype, learned);
+ IReadOnlyList? seeded = null;
+ try { seeded = MobSeedLookup?.Invoke(wcid, name); }
+ catch { seeded = null; } // a bad seed file must never stop element choice
+ return CreatureWeakness.Rank(wcid, name, ctype, learned, seeded);
}
// Server replies seen when the last combat wield was sent (UseDone / WeenieError sequence).
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
index b0fdbbe..cbea3c9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
@@ -60,6 +60,14 @@ internal sealed class PetManager
// get parked so we advance to the next configured essence instead of looping.
private readonly Dictionary _deviceCooldownUntil = new();
+ // Essences the server just confirmed full ("You add the spirit…" / "…already full"). Until a
+ // summon reports "not enough charges", their Structure read is not trusted: the cached value
+ // can still be the empty 0 from the last appraisal, which re-issued the refill in a loop
+ // (spirit use → peace mode → clap) on 2026-10-04.
+ private readonly Dictionary _confirmedFullUntil = new();
+ // Refills issued per essence inside RefillLoopWindowMs; a third one parks the essence.
+ private readonly Dictionary _refillAttempts = new();
+
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
// by name; it is never itself a summon device.
private const string EncapsulatedSpiritName = "Encapsulated Spirit";
@@ -69,12 +77,36 @@ internal sealed class PetManager
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
private const long DeviceNoSpiritCooldownMs = 15_000;
+ private const long ConfirmedFullTrustMs = 30 * 60_000;
+ private const long RefillLoopWindowMs = 120_000;
+ private const int RefillLoopMaxAttempts = 2;
+ private const long RefillLoopParkMs = 300_000;
private string _playerName = string.Empty;
private long _playerNameAt;
private static long NowMs => Environment.TickCount64;
+ ///
+ /// Optional ILT Hub hook: when it returns true an EMPTY essence is used anyway, because
+ /// the server's Summon Essence Refill Charm refills it from banked pyreals on use.
+ /// Null (default) keeps the retail behaviour (spirit refill or park).
+ ///
+ public Func? AllowSummonOnEmpty { get; set; }
+
+ ///
+ /// Optional ILT Hub hook: while it returns true no combat summon is started (e.g. the
+ /// healing-pet helper has its heal pet out). Null (default) never holds.
+ ///
+ public Func? HoldSummons { get; set; }
+
+ ///
+ /// Optional ILT Hub hook, called when a pet already holds the slot and monsters are near.
+ /// Returns true after dismissing a non-combat (cosmetic) pet so a combat pet can follow.
+ /// Null (default) leaves whatever pet is out alone.
+ ///
+ public Func? YieldPetForCombat { get; set; }
+
public PetManager(RynthCoreHost host, LegacyUiSettings settings,
WorldObjectCache objectCache, CombatManager? combat,
CharacterSkills? skills)
@@ -113,7 +145,7 @@ internal sealed class PetManager
bool spiritGone = _activeSpiritId != 0 && _objectCache[_activeSpiritId] == null;
if (spiritGone || DeviceHasCharges(_activeDeviceId))
{
- _host.Log($"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
+ RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
GoIdle();
}
}
@@ -122,7 +154,7 @@ internal sealed class PetManager
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
- _host.Log($"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
+ 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
@@ -158,7 +190,12 @@ internal sealed class PetManager
// Drop to Idle; the next think tick reads Structure==0 and refills it.
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
{
- _host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
+ RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
+ _confirmedFullUntil.Remove(_activeDeviceId); // really empty now — a refill is due
+ // 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;
GoIdle();
return;
}
@@ -169,9 +206,20 @@ internal sealed class PetManager
{
// "You add the spirit to the essence." (success) / "This essence is
// already full." (our Structure read was stale — also done).
- if (text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase)
- || text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase))
+ bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase);
+ bool full = text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
+ if (added || full)
{
+ int device = _activeDeviceId;
+ if (device != 0)
+ {
+ _confirmedFullUntil[device] = NowMs + ConfirmedFullTrustMs;
+ // Refresh the cached Structure so the roster / HUD and later reads agree.
+ if (_host.HasRequestId) _host.RequestId(unchecked((uint)device));
+ }
+ RynthLog.Write(LogCat.Pets, added
+ ? $"[RynthAi] Pet: refill complete (essence 0x{(uint)device:X8}, server confirmed)."
+ : $"[RynthAi] Pet: essence 0x{(uint)device:X8} is already full; charge read was stale.");
GoIdle();
}
}
@@ -183,7 +231,14 @@ internal sealed class PetManager
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
- if (IsPetActive()) return;
+ if (IsPetActive())
+ {
+ // 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;
+ return;
+ }
+ if (HoldSummons?.Invoke() == true) return;
// Only summon when mobs are near (the user's trigger).
if (!MonstersNearby()) return;
@@ -203,6 +258,13 @@ internal sealed class PetManager
int charges = ReadCharges(deviceId); // -1 = unreadable
+ // The server said this essence is full since the read went stale — summon from it.
+ if (charges == 0 && _confirmedFullUntil.TryGetValue(deviceId, out long trustUntil))
+ {
+ if (now < trustUntil) charges = -1;
+ else _confirmedFullUntil.Remove(deviceId);
+ }
+
if (charges != 0)
{
// Has charges (or unreadable → attempt; an empty one is rejected
@@ -211,12 +273,22 @@ internal sealed class PetManager
return;
}
- // charges == 0 → empty. Auto-refill from an Encapsulated Spirit.
+ // charges == 0 → empty. ILT shards with an active pyreal-refill charm refill
+ // the essence server-side on use, so summon straight away.
+ if (AllowSummonOnEmpty?.Invoke() == true)
+ {
+ IssueSummon(deviceId, charges);
+ return;
+ }
+
+ // Otherwise auto-refill from an Encapsulated Spirit.
if (_settings.PetAutoRefill)
{
int spiritId = FindEncapsulatedSpirit();
if (spiritId != 0)
{
+ if (RefillLoopDetected(deviceId, now))
+ continue;
IssueRefill(deviceId, spiritId);
return;
}
@@ -239,7 +311,7 @@ internal sealed class PetManager
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
- _host.Log($"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
+ RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}
@@ -251,10 +323,37 @@ internal sealed class PetManager
_activeDeviceId = deviceId;
_activeSpiritId = spiritId;
_actionIssuedAt = NowMs;
- _host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
+ RecordRefillAttempt(deviceId, _actionIssuedAt);
+ RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
}
+ /// Counts refills per essence inside .
+ private void RecordRefillAttempt(int deviceId, long now)
+ {
+ if (_refillAttempts.TryGetValue(deviceId, out var a) && now - a.WindowStart < RefillLoopWindowMs)
+ _refillAttempts[deviceId] = (a.Count + 1, a.WindowStart);
+ else
+ _refillAttempts[deviceId] = (1, now);
+ }
+
+ ///
+ /// True (and the essence parked) when it was already refilled
+ /// times in the window without becoming usable — the charge read is stale or the refill is
+ /// failing, and repeating it only burns spirits and forces peace mode.
+ ///
+ private bool RefillLoopDetected(int deviceId, long now)
+ {
+ if (!_refillAttempts.TryGetValue(deviceId, out var a) || now - a.WindowStart >= RefillLoopWindowMs)
+ return false;
+ if (a.Count < RefillLoopMaxAttempts)
+ return false;
+ _deviceCooldownUntil[deviceId] = now + RefillLoopParkMs;
+ _refillAttempts.Remove(deviceId);
+ RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} refilled {a.Count}x in {(now - a.WindowStart) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
+ return true;
+ }
+
private void GoIdle()
{
_state = PetState.Idle;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs
index e0dc966..c16841d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs
@@ -8,6 +8,9 @@ namespace RynthCore.Plugin.RynthAi;
public static class SpellDatabase
{
private static readonly Dictionary _spellNames = new();
+ // Family + difficulty (power) per spell id, from SpellData.txt columns 3 and 7.
+ // Used by the Mag-style item info spell filter (cantrip / aura tiers).
+ private static readonly Dictionary _spellMeta = new();
private static bool _loaded = false;
private static readonly Dictionary _builtinSpells = new Dictionary
@@ -38,6 +41,7 @@ public static class SpellDatabase
public static void Load(Action? log = null)
{
_spellNames.Clear();
+ _spellMeta.Clear();
_loaded = false;
try
@@ -59,7 +63,13 @@ public static class SpellDatabase
if (string.IsNullOrWhiteSpace(line)) continue;
string[] columns = line.Split('\t');
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
+ {
_spellNames[spellId] = columns[1].Trim();
+ if (columns.Length >= 7
+ && int.TryParse(columns[2].Trim(), out int family)
+ && int.TryParse(columns[6].Trim(), out int difficulty))
+ _spellMeta[spellId] = (family, difficulty);
+ }
}
_loaded = _spellNames.Count > 0;
@@ -77,6 +87,24 @@ public static class SpellDatabase
return $"Unknown Spell ({spellId})";
}
+ /// Spell family and difficulty (power). False when the spell isn't in SpellData.txt.
+ public static bool TryGetSpellMeta(int spellId, out int family, out int difficulty)
+ {
+ if (_spellMeta.TryGetValue(spellId, out var meta))
+ {
+ family = meta.Family;
+ difficulty = meta.Difficulty;
+ return true;
+ }
+ family = 0;
+ difficulty = 0;
+ return false;
+ }
+
+ /// True when the spell id is in the embedded table or the built-in recall list.
+ public static bool HasSpell(int spellId) =>
+ _spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
+
public static string GetSpellNameOrId(int spellId)
{
if (_spellNames.TryGetValue(spellId, out string? name)) return name;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
index a54df62..7021c47 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
@@ -601,17 +601,14 @@ public class WorldObjectCache
return;
}
- // Non-creature with a position — could be equipped item on 0x8000 range
- // or static world object; classify by type flags
- if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0)
- {
- // Item with a world position = equipped or ground-dropped
- cls = ClassifyItem(uid, typeFlags);
- _inventory.Add(id);
- _landscape.Remove(id);
- _byId[id] = Make(id, name, cls);
+ // Non-creature with a known type: classify it by its ItemType flags and place it
+ // by ownership. Only weapons/armor/casters/containers were accepted here before,
+ // so keys, gems, spell components, food and misc fell through to Unknown
+ // landscape (never inventory) and ReclassifyUnknownDynamics re-probed them
+ // every 2 s forever.
+ AcObjectClass typedCls = ClassifyItem(uid, typeFlags);
+ if (typedCls != AcObjectClass.Unknown && PlaceTypedObject(uid, id, name, typedCls, typeFlags))
return;
- }
}
else if (uid >= 0x80000000u)
{
@@ -660,6 +657,83 @@ public class WorldObjectCache
}
}
+ ///
+ /// Places a positioned, non-creature object whose ItemType resolved to a real class.
+ /// Must be called under .
+ ///
+ /// - Portals / lifestones → landscape with their real class.
+ /// - Dynamic objects owned by the player (wielded, in the main pack, or in a side pack) → inventory.
+ /// - Other dynamic objects (ground drops, corpse / chest contents) → landscape with the item class.
+ /// - Ownership unreadable → gear-like types go to inventory, the rest to landscape.
+ /// - Static non-fixture, non-container objects (doors, signs) → returns false; the caller keeps them Unknown scenery.
+ ///
+ /// Returns true when the object was placed and recorded in .
+ ///
+ private bool PlaceTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
+ {
+ bool isFixture = cls is AcObjectClass.Portal or AcObjectClass.Lifestone;
+ bool isDynamic = uid >= 0x80000000u;
+
+ bool toInventory;
+ if (isFixture)
+ {
+ toInventory = false;
+ }
+ else if (!isDynamic)
+ {
+ // Chests are static containers; other static objects stay Unknown scenery.
+ if ((typeFlags & ItemTypeContainer) == 0)
+ return false;
+ toInventory = false;
+ }
+ else
+ {
+ bool owned = IsOwnedByPlayer(id, out bool ownershipKnown);
+ toInventory = ownershipKnown
+ ? owned
+ : (typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0;
+ }
+
+ _classifyRetry.Remove(uid);
+ _reclassifySkipState.Remove(uid);
+ if (toInventory)
+ {
+ if (_inventory.Add(id)) _inventoryDirty = true;
+ _landscape.Remove(id);
+ }
+ else
+ {
+ if (_inventory.Remove(id)) _inventoryDirty = true;
+ _landscape.Add(id);
+ }
+ _byId[id] = Make(id, name, cls);
+ TraceClassify(uid, name.Length > 0, true, true, typeFlags, toInventory ? $"typed->{cls}(inv)" : $"typed->{cls}(land)");
+ return true;
+ }
+
+ ///
+ /// True when the object is wielded by the player, sits in the player's main pack, or sits in
+ /// a side pack whose container is the player. is false when the
+ /// player id isn't set yet or the ownership read failed.
+ ///
+ private bool IsOwnedByPlayer(int id, out bool known)
+ {
+ known = false;
+ if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
+ return false;
+
+ known = true;
+ uint container = unchecked((uint)containerId);
+ uint wielder = unchecked((uint)wielderId);
+ if (wielder == _playerId || container == _playerId)
+ return true;
+
+ // One level of nesting covers side packs (AC doesn't allow packs inside packs).
+ return container != 0
+ && TryGetOwnership(containerId, out int outer, out _, out _)
+ && unchecked((uint)outer) == _playerId;
+ }
+
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
private const uint BfCorpse = 0x2000;
@@ -725,6 +799,7 @@ public class WorldObjectCache
List? toPromote = null;
List? toCorpse = null;
List<(int id, string name, AcObjectClass cls)>? statics = null;
+ List<(int Id, uint Flags)>? toType = null; // Unknowns whose ItemType is now a real item class
foreach (int id in _landscape)
{
uint uid = unchecked((uint)id);
@@ -771,14 +846,21 @@ public class WorldObjectCache
// immediate signal that doesn't wait on qualities/appraisal). This
// second path is what rescues a login mob within 2s if it slipped
// to Unknown before its weenie/combat-state was readable.
- bool isCreature = _host.TryGetItemType(uid, out uint typeFlags)
- && (typeFlags & ItemTypeCreature) != 0;
+ bool gotType = _host.TryGetItemType(uid, out uint typeFlags);
+ bool isCreature = gotType && (typeFlags & ItemTypeCreature) != 0;
if (!isCreature
&& _host.HasObjectIsAttackable
&& _host.ObjectIsAttackable(uid))
isCreature = true;
if (!isCreature)
{
+ // Type known now (or arrived late): place it as a real item instead of
+ // re-probing it every pass. Applied after the loop: placing mutates _landscape.
+ if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown)
+ {
+ (toType ??= new()).Add((id, typeFlags));
+ continue;
+ }
DiagLogReclassifySkip(uid, wo.Name);
continue;
}
@@ -832,10 +914,27 @@ public class WorldObjectCache
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse");
}
+ if (toType != null)
+ {
+ int placed = 0, toInv = 0;
+ foreach (var (id, flags) in toType)
+ {
+ if (!_byId.TryGetValue(id, out var wo)) continue;
+ uint uid = unchecked((uint)id);
+ // An Unknown result would be re-queued every pass, so leave it to the skip diag.
+ AcObjectClass cls = ClassifyItem(uid, flags);
+ if (cls == AcObjectClass.Unknown || !PlaceTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
+ placed++;
+ if (_inventory.Contains(id)) toInv++;
+ }
+ _host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {placed} Unknown object(s) as items ({toInv} into inventory)");
+ }
+
// DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted
// this pass. Confirms ReclassifyUnknownDynamics is running and engine signals
// keep failing for the stuck uids (vs. them never reaching _landscape at all).
if (toPromote == null
+ && toType == null
&& _reclassifySkipState.Count > 0
&& _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries)
{
@@ -1035,6 +1134,13 @@ public class WorldObjectCache
: defaultValue;
}
+ ///
+ /// True when ownership is readable and the object has neither a container nor a wielder,
+ /// so it lies loose in the world. Unreadable ownership is false (a pack item is never a ground drop).
+ ///
+ public bool IsOnGround(int id)
+ => TryGetOwnership(id, out int containerId, out int wielderId, out _) && containerId == 0 && wielderId == 0;
+
public int GetContainerId(int id)
{
if (!TryGetOwnership(id, out int containerId, out _, out _))
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
index 0e7da6c..ea81fb0 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
@@ -530,16 +530,25 @@ public sealed partial class RynthAiPlugin
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters))
return;
- if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
+ // A ground pickup already sent finishes before a corpse is claimed.
+ if (GroundPickupInFlight)
{
- // No corpses in range. STEP 4: nothing to release. The "Looting"
- // string used to be held here from a just-completed corpse and
- // had to be handed back so nav could resume; now HasLootWork
- // simply stops returning true and the arbiter moves on by itself
- // on the next tick.
+ TickGroundLoot(settings, maxMeters);
return;
}
+ if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
+ {
+ // No corpses in range. Loose ground items that match the loot profile
+ // get their turn here; HasLootWork keeps Looting while any remain.
+ TickGroundLoot(settings, maxMeters);
+ return;
+ }
+
+ // A corpse outranks an unsent ground claim.
+ if (_groundTargetId != 0)
+ ResetGroundLoot(clearCaches: false);
+
if (corpse == null)
return;
@@ -1571,7 +1580,7 @@ public sealed partial class RynthAiPlugin
if (maxMeters <= 0.25)
return false;
- return HasUnlootedCorpsesInRange(maxMeters);
+ return HasUnlootedCorpsesInRange(maxMeters) || HasGroundLootWork(settings);
}
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs
index bf64950..ceeee93 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureWeakness.cs
@@ -58,10 +58,19 @@ internal static class CreatureWeakness
///
/// The elements that hurt this monster most, or null when nothing is known. Order of
/// sources: the server table (wcid + name), then what the Damage tab learned
- /// () ahead of the creature-type ranking, then the type
- /// ranking alone. 0 = unknown (the name keywords decide).
+ /// () ahead of the creature-type ranking, then the
+ /// UtilityBelt damage seed (, best first) ahead of the type
+ /// ranking, then the type ranking alone. 0 = unknown
+ /// (the name keywords decide).
///
- public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest)
+ ///
+ /// Damage types other players landed best on this monster (Monster Editor "Import UB
+ /// damage insights"), best first; null or empty = no seed. It reflects what players
+ /// owned as much as the monster's weakness, so it never outranks the server table or
+ /// this character's learned element; it only beats the generic creature-type average.
+ ///
+ public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest,
+ IReadOnlyList? seeded = null)
{
EnsureLoaded();
name ??= "";
@@ -86,11 +95,36 @@ internal static class CreatureWeakness
if (!e.Element.Equals(learned, StringComparison.OrdinalIgnoreCase)) r.Order.Add(e);
return r;
}
+ Ranking? seed = SeedRanking(seeded, type);
+ if (seed != null)
+ return seed;
if (type != null)
return new Ranking { Source = Pretty(type.Name) + " type", Order = new(type.Order) };
return null;
}
+ ///
+ /// The seed's elements (normalised, de-duplicated, no multiplier: only the order is known),
+ /// then the creature type's remaining elements. Null when the seed names no element.
+ ///
+ private static Ranking? SeedRanking(IReadOnlyList? seeded, TypeInfo? type)
+ {
+ if (seeded == null || seeded.Count == 0) return null;
+ var r = new Ranking();
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (string raw in seeded)
+ {
+ string e = Normalize(raw);
+ if (e.Length > 0 && seen.Add(e)) r.Order.Add((e, double.NaN));
+ }
+ if (r.Order.Count == 0) return null;
+ r.Source = type != null ? $"UB seed, then {Pretty(type.Name)} type" : "UB seed";
+ if (type != null)
+ foreach (var e in type.Order)
+ if (seen.Add(e.Element)) r.Order.Add(e);
+ return r;
+ }
+
///
/// The creature type the world-database table gives this monster (0 = not in it). Same match
/// as : the wcid's row when its name agrees (or no name is given); no wcid,
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/UbMobSeedStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/UbMobSeedStore.cs
new file mode 100644
index 0000000..827ae57
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/UbMobSeedStore.cs
@@ -0,0 +1,128 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.Json;
+using RynthCore.CreatureSeed;
+using RynthCore.Install;
+
+namespace RynthCore.Plugin.RynthAi.CreatureData;
+
+///
+/// Read-only view of the UtilityBelt damage-type seed (),
+/// produced by the Monster Editor's "Import UB damage insights".
+/// File: <SuiteDir>\RynthAi\CreatureData\ub-mob-seed.json.
+///
+/// Used only as a fallback for the "Auto" damage type when a monster has no appraised
+/// resists: it ranks damage types by what players actually landed on that monster, which
+/// reflects what they owned as much as the monster's weakness. Never written by the plugin
+/// and never fed into the per-character .
+///
+/// Lookups are made from the combat thread only; the lock guards the occasional reload.
+///
+internal sealed class UbMobSeedStore
+{
+ /// Minimum time between file-change checks (the editor may rewrite the seed while playing).
+ private static readonly TimeSpan ReloadCheckInterval = TimeSpan.FromSeconds(15);
+
+ private readonly object _lock = new();
+ private readonly Dictionary _byWcid = new();
+ private readonly Dictionary _byName = new(StringComparer.OrdinalIgnoreCase);
+ private DateTime _loadedWriteUtc = DateTime.MinValue;
+ private DateTime _nextCheckUtc = DateTime.MinValue;
+
+ private static string FilePath =>
+ Path.Combine(RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
+
+ /// Number of seeded monsters currently loaded (wcid + name-only).
+ public int Count { get { lock (_lock) return _byWcid.Count + CountNameOnly(); } }
+
+ /// Loads (or reloads) the seed when the file changed. Safe to call often.
+ public void Load()
+ {
+ lock (_lock)
+ {
+ _nextCheckUtc = DateTime.UtcNow + ReloadCheckInterval;
+ string path = FilePath;
+ if (!File.Exists(path))
+ {
+ Clear();
+ return;
+ }
+
+ DateTime writeUtc;
+ try { writeUtc = File.GetLastWriteTimeUtc(path); }
+ catch { return; }
+ if (writeUtc == _loadedWriteUtc) return;
+
+ try
+ {
+ var seed = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.UbMobSeedFile);
+ Clear();
+ _loadedWriteUtc = writeUtc;
+ if (seed == null || seed.Version > UbMobSeedFile.CurrentVersion) return;
+
+ foreach (var e in seed.Entries)
+ {
+ if (e.Elements == null || e.Elements.Count < 2) continue;
+ if (e.Wcid != 0) _byWcid[e.Wcid] = e;
+ IndexName(e);
+ }
+ }
+ catch
+ {
+ // Corrupt or mid-write file: keep whatever was loaded before and retry on the next check.
+ }
+ }
+ }
+
+ ///
+ /// Ranked damage types (best first) for a monster: exact wcid first, then name.
+ /// Returns false when the seed has nothing comparable for it.
+ ///
+ public bool TryGetRanked(uint wcid, string? name, out IReadOnlyList ranked)
+ {
+ lock (_lock)
+ {
+ // Checked under the lock: DateTime reads are not atomic on x86. Monitor is re-entrant.
+ if (DateTime.UtcNow >= _nextCheckUtc) Load();
+
+ UbMobSeedEntry? entry = null;
+ if (wcid != 0) _byWcid.TryGetValue(wcid, out entry);
+ if (entry == null && !string.IsNullOrWhiteSpace(name)) _byName.TryGetValue(name.Trim(), out entry);
+
+ ranked = entry?.Elements ?? (IReadOnlyList)Array.Empty();
+ return entry != null;
+ }
+ }
+
+ ///
+ /// Name index: a wcid entry beats a name-only one; among equals the most-hit entry wins
+ /// (tier variants share a name, so the busiest variant is the best guess).
+ ///
+ private void IndexName(UbMobSeedEntry e)
+ {
+ if (string.IsNullOrWhiteSpace(e.Name)) return;
+ string key = e.Name.Trim();
+ if (_byName.TryGetValue(key, out var existing))
+ {
+ bool existingHasWcid = existing.Wcid != 0, newHasWcid = e.Wcid != 0;
+ if (existingHasWcid && !newHasWcid) return;
+ if (existingHasWcid == newHasWcid && existing.TotalHits >= e.TotalHits) return;
+ }
+ _byName[key] = e;
+ }
+
+ private int CountNameOnly()
+ {
+ int n = 0;
+ foreach (var e in _byName.Values) if (e.Wcid == 0) n++;
+ return n;
+ }
+
+ private void Clear()
+ {
+ _byWcid.Clear();
+ _byName.Clear();
+ _loadedWriteUtc = DateTime.MinValue;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs
new file mode 100644
index 0000000..5ec962d
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/RynthLog.cs
@@ -0,0 +1,1057 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using RynthCore.PluginSdk;
+using RynthCore.Install;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// One trace category per RynthAi function. Each category can be traced
+/// independently (/ra trace <cat> on) into its own daily file under
+/// Logs\Diagnostics\Trace, mirroring UtilityBelt's per-feature trace toggles.
+///
+internal enum LogCat
+{
+ // ── Core / macro systems ───────────────────────────────────────────────
+ General,
+ Commands,
+ Combat,
+ Buffing,
+ Pets,
+ WorldCache,
+ Navigation,
+ Doors,
+ Jumper,
+ Looting,
+ Inventory,
+ Salvage,
+ Vendor,
+ ManaStones,
+ Meta,
+ Expressions,
+ Quests,
+ Crafting,
+ Raycast,
+ Radar,
+ UI,
+ Remote,
+ Chat,
+ Huds,
+
+ // ── ILT Hub (IltHub/) ──────────────────────────────────────────────────
+ IltHub,
+ IltOptions,
+ IltChat,
+ IltStore,
+ IltBanking,
+ IltPets,
+ IltQuests,
+ IltProgression,
+ IltRates,
+ IltGear,
+ IltGames,
+}
+
+///
+/// Persisted diagnostics switches (Logs\Diagnostics\diagnostics.json).
+/// Fields (not properties) so the source-generated
+/// (IncludeFields) round-trips them without reflection under NativeAOT.
+///
+internal sealed class RynthLogConfig
+{
+ /// Echo trace + exception lines to the in-game chat window (UB's "debug" switch).
+ public bool DebugToChat;
+
+ /// Mirror every line into the daily RynthAi log file.
+ public bool FileLogAll = true;
+
+ ///
+ /// Category names (see ) with tracing enabled. Kept in sync with
+ /// (every category at Trace or Info); only read when
+ /// is empty (diagnostics.json written by an older RynthAi).
+ ///
+ public List Traces = new();
+
+ ///
+ /// Per-category trace level (Off / Trace / Info) for every . Rewritten on
+ /// every load with the full category list and descriptions so the launcher can edit it.
+ ///
+ public List Categories = new();
+
+ /// Delete diagnostics files older than this many days.
+ public int RetainDays = 7;
+
+ /// Roll a log file to a new numbered part once it exceeds this size (MB).
+ public int MaxFileMb = 10;
+
+ /// Keep at most this many files per diagnostics folder (oldest pruned first).
+ public int MaxFiles = 30;
+
+ ///
+ /// Per-event log levels for the named key events in . Rewritten on every
+ /// load with the full catalog (new events at their defaults, fresh descriptions), so the launcher
+ /// can list and edit every event without its own copy of the catalog.
+ ///
+ public List Events = new();
+}
+
+/// Where a named key event is written (see ).
+internal enum LogEventLevel
+{
+ /// Not recorded at all.
+ Off = 0,
+ /// Only in the category trace file, and only while that category is traced.
+ Trace = 1,
+ /// Normal log: engine log + daily RynthAi file (+ trace file when traced).
+ Info = 2,
+}
+
+///
+/// One persisted key-event switch in diagnostics.json. Only is read back;
+/// the other fields are informational for the launcher and are refreshed from the catalog on load.
+///
+internal sealed class LogEventSetting
+{
+ /// Stable event id, e.g. "IltHub.Login".
+ public string Key = string.Empty;
+
+ /// "Info", "Trace" or "Off" (case-insensitive; anything else falls back to the default).
+ public string Level = nameof(LogEventLevel.Info);
+
+ /// Default level for this event (informational).
+ public string Default = nameof(LogEventLevel.Info);
+
+ /// Owning name (informational; picks the trace file).
+ public string Category = string.Empty;
+
+ /// Human-readable description shown by the launcher.
+ public string Description = string.Empty;
+}
+
+///
+/// One persisted category trace switch in diagnostics.json. decides where
+/// the category's lines go: Off → dropped, Trace → the category trace
+/// file, Info → the trace file AND the normal log. Normal lines are
+/// unaffected. Only is read back.
+///
+internal sealed class LogCategorySetting
+{
+ /// name, e.g. "Combat".
+ public string Name = string.Empty;
+
+ /// "Off", "Trace" or "Info" (case-insensitive; anything else reads as Off).
+ public string Level = nameof(LogEventLevel.Off);
+
+ /// Human-readable description shown by the launcher.
+ public string Description = string.Empty;
+}
+
+///
+/// Catalog of named key events. Each one has its own configurable level, so a milestone like
+/// "Hub login" can show in the normal log while the surrounding detail stays trace-only.
+/// Add new events here; the launcher picks them up from diagnostics.json automatically.
+///
+internal static class LogEvents
+{
+ // ── ILT Hub ────────────────────────────────────────────────────────────
+ public const string IltLogin = "IltHub.Login";
+ public const string IltWorldCheck = "IltHub.WorldCheck";
+ public const string IltOptionsRefreshStart = "IltHub.OptionsRefreshStart";
+ public const string IltOptionsRefreshed = "IltHub.OptionsRefreshed";
+ public const string IltWindowShown = "IltHub.WindowShown";
+ public const string IltWindowHidden = "IltHub.WindowHidden";
+ public const string IltCommand = "IltHub.Command";
+ public const string IltConfirmation = "IltHub.Confirmation";
+ public const string IltLogout = "IltHub.Logout";
+
+ /// Catalog entry: key, owning category, default level, launcher description.
+ internal readonly record struct Definition(string Key, LogCat Category, LogEventLevel Default, string Description);
+
+ /// Every known event, in launcher display order.
+ internal static readonly Definition[] Catalog =
+ {
+ new(IltLogin, LogCat.IltHub, LogEventLevel.Info, "ILT Hub: character logged in (character and world)."),
+ new(IltWorldCheck, LogCat.IltOptions, LogEventLevel.Info, "ILT Hub: login world check (ILT-like world or skipped)."),
+ new(IltOptionsRefreshStart, LogCat.IltOptions, LogEventLevel.Trace, "ILT Hub: server options refresh started."),
+ new(IltOptionsRefreshed, LogCat.IltOptions, LogEventLevel.Info, "ILT Hub: server options refreshed (source and on/off counts)."),
+ new(IltWindowShown, LogCat.IltHub, LogEventLevel.Info, "ILT Hub: Hub window shown."),
+ new(IltWindowHidden, LogCat.IltHub, LogEventLevel.Trace, "ILT Hub: Hub window hidden."),
+ new(IltCommand, LogCat.IltHub, LogEventLevel.Trace, "ILT Hub: /ra hub and /ra quests commands."),
+ new(IltConfirmation, LogCat.IltHub, LogEventLevel.Trace, "ILT Hub: chat confirmations requested, confirmed or expired."),
+ new(IltLogout, LogCat.IltHub, LogEventLevel.Trace, "ILT Hub: logout (features stopped)."),
+ };
+
+ /// Launcher description for each trace category.
+ internal static string DescribeCategory(LogCat cat) => cat switch
+ {
+ LogCat.General => "Uncategorised RynthAi lines.",
+ LogCat.Commands => "/ra chat commands and remote commands.",
+ LogCat.Combat => "Combat: targeting, attacks, spells, wield gates.",
+ LogCat.Buffing => "Buffing: buff timers, rebuff decisions, casts.",
+ LogCat.Pets => "Pet summoning and upkeep.",
+ LogCat.WorldCache => "World object cache: classification and ownership.",
+ LogCat.Navigation => "Navigation: routes, waypoints, movement state.",
+ LogCat.Doors => "Door detection and opening.",
+ LogCat.Jumper => "Jump commands.",
+ LogCat.Looting => "Corpse looting and loot rules.",
+ LogCat.Inventory => "Inventory: AutoStack, AutoCram, equip.",
+ LogCat.Salvage => "Salvage combining and use.",
+ LogCat.Vendor => "AutoVendor buy/sell.",
+ LogCat.ManaStones => "Mana stone use and recharging.",
+ LogCat.Meta => "Meta (VTank-style) state machine and actions.",
+ LogCat.Expressions => "Meta expression evaluation.",
+ LogCat.Quests => "Quest tracking.",
+ LogCat.Crafting => "Missile ammo crafting.",
+ LogCat.Raycast => "Line-of-sight raycasts and geometry loading.",
+ LogCat.Radar => "Radar window.",
+ LogCat.UI => "RynthAi UI windows and panels.",
+ LogCat.Remote => "Remote control (launcher/Avalonia commands).",
+ LogCat.Chat => "Chat parsing and chat diagnostics.",
+ LogCat.Huds => "Floating HUDs: item counts, Mini Remote, icons.",
+ LogCat.IltHub => "ILT Hub: window, login/logout, commands.",
+ LogCat.IltOptions => "ILT Hub: server options.",
+ LogCat.IltChat => "ILT Hub: chat parsing.",
+ LogCat.IltStore => "ILT Hub: store.",
+ LogCat.IltBanking => "ILT Hub: banking.",
+ LogCat.IltPets => "ILT Hub: pets.",
+ LogCat.IltQuests => "ILT Hub: quests.",
+ LogCat.IltProgression => "ILT Hub: progression.",
+ LogCat.IltRates => "ILT Hub: rates.",
+ LogCat.IltGear => "ILT Hub: gear.",
+ LogCat.IltGames => "ILT Hub: games.",
+ _ => cat.ToString(),
+ };
+}
+
+///
+/// Central RynthAi logging / debugging facility, modelled on UtilityBelt's Logger:
+///
+/// - — normal log line: engine log (as before) + daily rynthai_*.txt
+/// + the category trace file when that category is being traced.
+/// - — verbose line, only recorded when the category is traced; optionally
+/// echoed to chat when is on.
+/// - — full stack trace into exceptions_*.txt with per-signature
+/// throttling so a per-frame fault can't fill the disk.
+///
+/// Thread-safe: callable from the pump thread, the ImGui render thread and background tasks.
+/// Chat echo is queued and drained on the pump thread by .
+///
+internal static class RynthLog
+{
+ /// Default diagnostics root (inside the RynthAi data folder the installer creates).
+ public static readonly string DefaultDirectory = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"Logs\Diagnostics");
+
+ // ── Exception throttling (same budgets as UB's Logger) ────────────────
+ private static readonly TimeSpan ExceptionBurstWindow = TimeSpan.FromSeconds(5);
+ private const int MaxExceptionsPerSignaturePerDay = 25;
+ private const int MaxExceptionsPerDay = 500;
+
+ /// Upper bound on chat echo lines drained per tick (prevents chat floods).
+ private const int MaxChatLinesPerPump = 20;
+
+ /// Upper bound on queued chat echo lines; extra lines are dropped (files still get them).
+ private const int MaxQueuedChatLines = 200;
+
+ private static readonly object FileLock = new();
+ private static readonly object ConfigLock = new();
+ private static readonly Dictionary Writers = new(StringComparer.OrdinalIgnoreCase);
+ private static readonly Dictionary RollParts = new(StringComparer.OrdinalIgnoreCase);
+ private static readonly Dictionary ExceptionSignatures = new();
+ private static readonly ConcurrentQueue ChatQueue = new();
+
+ // Per-category trace level as (int)LogEventLevel, indexed by (int)LogCat. Volatile reads are
+ // enough — changes are rare, reads are hot. Off = not traced, Trace = trace file, Info = trace
+ // file + normal log.
+ private static readonly int[] CategoryLevels = new int[Enum.GetValues().Length];
+
+ // Key-event levels and categories. Replaced wholesale on load (never mutated after publish),
+ // so hot-path readers on any thread can use them without a lock.
+ private static volatile Dictionary _eventLevels = BuildDefaultEventLevels();
+ private static readonly Dictionary EventCategories = BuildEventCategories();
+
+ /// How often checks diagnostics.json for edits made by the launcher.
+ private const long ConfigPollIntervalMs = 2000;
+ private static long _nextConfigPollAt;
+ private static DateTime _configStampUtc = DateTime.MinValue;
+
+ private static RynthCoreHost? _host;
+ private static RynthLogConfig _config = new();
+ private static string _directory = DefaultDirectory;
+ private static string _openDay = string.Empty;
+ private static int _exceptionsToday;
+ private static bool _handlersRegistered;
+ private static bool _dirty;
+
+ /// Folder holding rynthai_*.txt, exceptions_*.txt and diagnostics.json.
+ public static string Directory => _directory;
+
+ /// Folder holding per-category {Category}_*.txt trace files.
+ public static string TraceDirectory => Path.Combine(_directory, "Trace");
+
+ /// When true, trace and exception lines are echoed to chat (UB's global debug).
+ public static bool DebugToChat
+ {
+ get => _config.DebugToChat;
+ set { lock (ConfigLock) { SyncFromDiskIfChanged(); _config.DebugToChat = value; SaveConfig(); } }
+ }
+
+ /// When true, every line is mirrored to the daily RynthAi log file.
+ public static bool FileLogAll
+ {
+ get => _config.FileLogAll;
+ set { lock (ConfigLock) { SyncFromDiskIfChanged(); _config.FileLogAll = value; SaveConfig(); } }
+ }
+
+ ///
+ /// Binds the logger to the plugin host, loads persisted switches, prunes old files and
+ /// installs the global unhandled-exception hooks. Safe to call more than once.
+ ///
+ public static void Init(RynthCoreHost host, string? directory = null)
+ {
+ _host = host;
+ _directory = string.IsNullOrWhiteSpace(directory) ? DefaultDirectory : directory;
+
+ try
+ {
+ System.IO.Directory.CreateDirectory(_directory);
+ System.IO.Directory.CreateDirectory(TraceDirectory);
+ }
+ catch { /* folder is created lazily on first write as a fallback */ }
+
+ // Write the merged catalog back when it changed so the launcher can list every event.
+ if (LoadConfig()) SaveConfig();
+ Prune();
+ RegisterGlobalHandlers();
+ }
+
+ // ═════════════════════════════════════════════════════════════════════
+ // Public logging API
+ // ═════════════════════════════════════════════════════════════════════
+
+ ///
+ /// Normal log line. Always goes to the engine log (unchanged behaviour), plus the daily
+ /// RynthAi file and — if the category is traced — the category's trace file.
+ /// lines are re-routed by their "[Prefix]" when one is recognised.
+ ///
+ public static void Write(LogCat cat, string message)
+ {
+ if (string.IsNullOrEmpty(message)) return;
+ if (cat == LogCat.General) cat = CategoryFromPrefix(message);
+
+ try { _host?.Log(message); } catch { /* host gone during unload */ }
+
+ if (_config.FileLogAll)
+ AppendLine(DailyPath(_directory, "rynthai"), $"[{cat}] {message}");
+
+ if (IsTracing(cat))
+ AppendLine(DailyPath(TraceDirectory, cat.ToString()), "INFO " + message);
+ }
+
+ ///
+ /// Verbose diagnostic line. Recorded only when is traced, so call
+ /// sites can trace freely; guard expensive message building with .
+ /// When the category's level is Info the line is also promoted to the normal log
+ /// (engine log + daily RynthAi file).
+ ///
+ public static void Trace(LogCat cat, string message)
+ {
+ if (!IsTracing(cat) || string.IsNullOrEmpty(message)) return;
+
+ AppendLine(DailyPath(TraceDirectory, cat.ToString()), "TRACE " + message);
+ if (GetCategoryLevel(cat) == LogEventLevel.Info)
+ {
+ try { _host?.Log($"[RynthAi:{cat}] {message}"); } catch { /* host gone during unload */ }
+ if (_config.FileLogAll)
+ AppendLine(DailyPath(_directory, "rynthai"), $"[{cat}] TRACE {message}");
+ }
+ if (_config.DebugToChat) QueueChat($"[RynthAi:{cat}] {message}");
+ }
+
+ ///
+ /// Records an exception with its full stack trace. A one-line summary always goes to the
+ /// engine log; the detailed entry is throttled per signature (5 s burst window,
+ /// 25/signature/day, 500/day total) exactly like UB's Logger.LogException.
+ ///
+ public static void Exception(LogCat cat, Exception ex, string context = "")
+ {
+ if (ex == null) return;
+
+ string where = string.IsNullOrEmpty(context) ? cat.ToString() : $"{cat}/{context}";
+ string summary = $"[RynthAi] {where} error: {ex.GetType().Name}: {ex.Message}";
+ try { _host?.Log(summary); } catch { }
+
+ if (!ShouldRecordException(where, ex, out int repeat)) return;
+
+ var sb = new StringBuilder();
+ sb.Append("==== ").Append(where);
+ if (repeat > 1) sb.Append(" (occurrence ").Append(repeat).Append(" today)");
+ sb.AppendLine(" ====");
+ sb.Append(ex);
+ AppendLine(DailyPath(_directory, "exceptions"), sb.ToString(), flush: true);
+
+ if (IsTracing(cat))
+ AppendLine(DailyPath(TraceDirectory, cat.ToString()), "ERROR " + summary);
+ if (_config.DebugToChat) QueueChat(summary);
+ }
+
+ ///
+ /// Named key event (see ). Its configured level decides where it goes:
+ /// Info → (normal log), Trace → , Off → dropped.
+ /// Levels are set per event in diagnostics.json, editable from the launcher.
+ ///
+ public static void Event(string eventKey, string message)
+ {
+ if (string.IsNullOrEmpty(message)) return;
+ LogCat cat = EventCategories.TryGetValue(eventKey, out LogCat c) ? c : LogCat.General;
+ string line = $"[{eventKey}] {message}";
+ switch (GetEventLevel(eventKey))
+ {
+ case LogEventLevel.Info: Write(cat, line); break;
+ case LogEventLevel.Trace: Trace(cat, line); break;
+ }
+ }
+
+ /// Configured level for an event; unknown keys default to Info so nothing is silently lost.
+ public static LogEventLevel GetEventLevel(string eventKey)
+ => _eventLevels.TryGetValue(eventKey, out LogEventLevel l) ? l : LogEventLevel.Info;
+
+ ///
+ /// True when would record anything for this key right now. Use it to skip
+ /// building an expensive message.
+ ///
+ public static bool IsEventEnabled(string eventKey)
+ {
+ LogEventLevel level = GetEventLevel(eventKey);
+ if (level == LogEventLevel.Info) return true;
+ return level == LogEventLevel.Trace
+ && EventCategories.TryGetValue(eventKey, out LogCat cat) && IsTracing(cat);
+ }
+
+ /// True when the category is currently being traced (level Trace or Info; cheap; safe on hot paths).
+ public static bool IsTracing(LogCat cat) => GetCategoryLevel(cat) != LogEventLevel.Off;
+
+ /// Current trace level of a category (Off, Trace or Info).
+ public static LogEventLevel GetCategoryLevel(LogCat cat)
+ {
+ int i = (int)cat;
+ return (uint)i < (uint)CategoryLevels.Length
+ ? (LogEventLevel)System.Threading.Volatile.Read(ref CategoryLevels[i])
+ : LogEventLevel.Off;
+ }
+
+ /// Sets a category's trace level and persists the change.
+ public static void SetCategoryLevel(LogCat cat, LogEventLevel level)
+ {
+ int i = (int)cat;
+ if ((uint)i >= (uint)CategoryLevels.Length) return;
+ lock (ConfigLock)
+ {
+ SyncFromDiskIfChanged();
+ System.Threading.Volatile.Write(ref CategoryLevels[i], (int)level);
+ SaveConfig();
+ }
+ }
+
+ ///
+ /// Enables/disables tracing for a single category and persists the change. Enabling keeps a
+ /// category that is already at Info (promoted to the normal log) at Info.
+ ///
+ public static void SetTracing(LogCat cat, bool enabled)
+ {
+ int i = (int)cat;
+ if ((uint)i >= (uint)CategoryLevels.Length) return;
+ lock (ConfigLock)
+ {
+ SyncFromDiskIfChanged();
+ ApplyTracing(i, enabled);
+ SaveConfig();
+ }
+ }
+
+ /// Enables/disables tracing for every category whose name starts with (empty = all).
+ public static int SetTracingByPrefix(string prefix, bool enabled)
+ {
+ int changed = 0;
+ lock (ConfigLock)
+ {
+ SyncFromDiskIfChanged();
+ foreach (LogCat cat in Enum.GetValues())
+ {
+ if (prefix.Length > 0 && !cat.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
+ ApplyTracing((int)cat, enabled);
+ changed++;
+ }
+ SaveConfig();
+ }
+ return changed;
+ }
+
+ /// On → Trace unless already traced; off → Off.
+ private static void ApplyTracing(int index, bool enabled)
+ {
+ int current = System.Threading.Volatile.Read(ref CategoryLevels[index]);
+ int next = !enabled ? (int)LogEventLevel.Off
+ : current == (int)LogEventLevel.Off ? (int)LogEventLevel.Trace : current;
+ System.Threading.Volatile.Write(ref CategoryLevels[index], next);
+ }
+
+ ///
+ /// Every category as "Name=Level" joined by ',', in enum order (Level: 0 Off, 1 Trace, 2 Info).
+ /// The engine Settings panel's Diagnostics tab draws its checkbox grid from this.
+ ///
+ public static string FormatCategoryLevels()
+ {
+ var sb = new StringBuilder();
+ foreach (LogCat cat in Enum.GetValues())
+ {
+ if (sb.Length > 0) sb.Append(',');
+ sb.Append(cat).Append('=').Append((int)GetCategoryLevel(cat));
+ }
+ return sb.ToString();
+ }
+
+ ///
+ /// Applies a string. Unknown names and bad levels are
+ /// skipped, categories not listed keep their level, and diagnostics.json is written once,
+ /// only when something changed. Returns the number of categories changed.
+ ///
+ public static int ApplyCategoryLevels(string? levels)
+ {
+ if (string.IsNullOrWhiteSpace(levels)) return 0;
+ int changed = 0;
+ lock (ConfigLock)
+ {
+ SyncFromDiskIfChanged();
+ foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ int eq = entry.IndexOf('=');
+ if (eq <= 0 || !TryParseCategory(entry[..eq], out LogCat cat)) continue;
+ if (!int.TryParse(entry[(eq + 1)..], out int level) || !Enum.IsDefined((LogEventLevel)level)) continue;
+ int i = (int)cat;
+ if (System.Threading.Volatile.Read(ref CategoryLevels[i]) == level) continue;
+ System.Threading.Volatile.Write(ref CategoryLevels[i], level);
+ changed++;
+ }
+ if (changed > 0) SaveConfig();
+ }
+ return changed;
+ }
+
+ /// Parses a category name case-insensitively (e.g. "ilthub", "Combat").
+ public static bool TryParseCategory(string name, out LogCat cat)
+ => Enum.TryParse(name, ignoreCase: true, out cat) && Enum.IsDefined(cat);
+
+ /// All categories currently being traced.
+ public static List TracedCategories()
+ {
+ var list = new List();
+ foreach (LogCat cat in Enum.GetValues())
+ if (IsTracing(cat)) list.Add(cat);
+ return list;
+ }
+
+ // ═════════════════════════════════════════════════════════════════════
+ // Lifecycle
+ // ═════════════════════════════════════════════════════════════════════
+
+ ///
+ /// Pump-thread housekeeping, called once per OnTick: drains queued chat echo lines and
+ /// flushes buffered file writes so a crash loses at most one tick of log output.
+ ///
+ public static void Pump()
+ {
+ // RynthCoreHost is a struct; unwrap the nullable copy before calling into it.
+ if (!ChatQueue.IsEmpty && _host is RynthCoreHost host)
+ {
+ for (int n = 0; n < MaxChatLinesPerPump && ChatQueue.TryDequeue(out string? line); n++)
+ {
+ try { if (host.HasWriteToChat) host.WriteToChat(line, 1); } catch { }
+ }
+ }
+
+ if (_dirty) Flush();
+
+ // Pick up event-level / trace edits the launcher wrote while the game is running.
+ long now = Environment.TickCount64;
+ if (now >= _nextConfigPollAt)
+ {
+ _nextConfigPollAt = now + ConfigPollIntervalMs;
+ ReloadConfigIfChangedOnDisk();
+ }
+ }
+
+ /// Reloads diagnostics.json when its timestamp differs from our last load/save.
+ private static void ReloadConfigIfChangedOnDisk()
+ {
+ try
+ {
+ if (!File.Exists(ConfigPath)) return;
+ if (File.GetLastWriteTimeUtc(ConfigPath) == _configStampUtc) return;
+ lock (ConfigLock)
+ {
+ if (LoadConfig()) SaveConfig();
+ }
+ try { _host?.Log("[RynthAi] diagnostics.json changed on disk - category and event log levels reloaded."); } catch { }
+ }
+ catch
+ {
+ // A half-written file is retried on the next poll.
+ }
+ }
+
+ /// Flushes every open log writer to disk.
+ public static void Flush()
+ {
+ lock (FileLock)
+ {
+ foreach (var w in Writers.Values)
+ {
+ try { w.Flush(); } catch { }
+ }
+ _dirty = false;
+ }
+ }
+
+ /// Flushes and closes every log file (plugin unload / logout).
+ public static void Shutdown()
+ {
+ lock (FileLock)
+ {
+ foreach (var w in Writers.Values)
+ {
+ try { w.Flush(); w.Dispose(); } catch { }
+ }
+ Writers.Clear();
+ _dirty = false;
+ }
+ }
+
+ ///
+ /// Deletes diagnostics files older than and trims each
+ /// folder to . Only touches *.txt files under the
+ /// diagnostics folders, never other RynthAi data.
+ ///
+ public static int Prune()
+ {
+ int removed = 0;
+ lock (FileLock)
+ {
+ removed += PruneFolder(_directory);
+ removed += PruneFolder(TraceDirectory);
+ }
+ return removed;
+ }
+
+ /// Human-readable status lines for /ra trace status and /ra logs.
+ public static IEnumerable StatusLines()
+ {
+ var traced = TracedCategories();
+ yield return $"[RynthAi] Debug-to-chat: {(DebugToChat ? "ON" : "off")} File log: {(FileLogAll ? "ON" : "off")}";
+ yield return traced.Count == 0
+ ? "[RynthAi] Tracing: (none)"
+ : "[RynthAi] Tracing: " + string.Join(", ", traced);
+ yield return $"[RynthAi] Logs: {_directory} (retain {_config.RetainDays} d, roll at {_config.MaxFileMb} MB)";
+ }
+
+ // ═════════════════════════════════════════════════════════════════════
+ // Internals
+ // ═════════════════════════════════════════════════════════════════════
+
+ ///
+ /// Maps the "[Prefix]" convention used by existing plugin log lines onto a category so
+ /// that, e.g., "[BuffDiag] …" lands in the Buffing trace without touching the call site.
+ ///
+ private static LogCat CategoryFromPrefix(string message)
+ {
+ if (message.Length < 3 || message[0] != '[') return LogCat.General;
+
+ if (Starts(message, "[Buff")) return LogCat.Buffing;
+ if (Starts(message, "[MetaCast") || Starts(message, "[Meta")) return LogCat.Meta;
+ if (Starts(message, "[Combat") || Starts(message, "[WieldGate") || Starts(message, "[Hazard")
+ || Starts(message, "[Kill") || Starts(message, "[ScanTele") || Starts(message, "[RynthAi combat"))
+ return LogCat.Combat;
+ if (Starts(message, "[Equip") || Starts(message, "[RynthAi dumpinv")) return LogCat.Inventory;
+ if (Starts(message, "[LOS") || Starts(message, "[Raycast") || Starts(message, "[GeoLoader")) return LogCat.Raycast;
+ if (Starts(message, "[Jumper")) return LogCat.Jumper;
+ if (Starts(message, "[ChatDiag") || Starts(message, "[RynthChat")) return LogCat.Chat;
+ if (Starts(message, "[Reclassify") || Starts(message, "[Classify")) return LogCat.WorldCache;
+ if (Starts(message, "[RynthAi navstate") || Starts(message, "[Nav")) return LogCat.Navigation;
+ if (Starts(message, "[IltHub")) return LogCat.IltHub;
+ return LogCat.General;
+ }
+
+ private static bool Starts(string s, string prefix) => s.StartsWith(prefix, StringComparison.Ordinal);
+
+ /// Builds {folder}\{stem}_yyyy-MM-dd.txt, with a numbered suffix once the day's file has rolled.
+ private static string DailyPath(string folder, string stem)
+ {
+ string key = folder + "|" + stem;
+ string day = DateTime.Now.ToString("yyyy-MM-dd");
+ int part;
+ lock (FileLock) part = RollParts.TryGetValue(key + "|" + day, out int p) ? p : 0;
+ string name = part == 0 ? $"{stem}_{day}.txt" : $"{stem}_{day}_{part}.txt";
+ return Path.Combine(folder, name);
+ }
+
+ /// Appends a timestamped line, rolling the file when it passes the size cap.
+ private static void AppendLine(string path, string text, bool flush = false)
+ {
+ try
+ {
+ lock (FileLock)
+ {
+ RollDayIfNeeded();
+
+ if (!Writers.TryGetValue(path, out var writer))
+ {
+ writer = OpenWriter(path);
+ Writers[path] = writer;
+ }
+
+ writer.Write(DateTime.Now.ToString("HH:mm:ss.fff"));
+ writer.Write(' ');
+ writer.WriteLine(text);
+ _dirty = true;
+ if (flush) writer.Flush();
+
+ long cap = Math.Max(1, _config.MaxFileMb) * 1024L * 1024L;
+ if (writer.BaseStream.Length > cap) Roll(path, writer);
+ }
+ }
+ catch
+ {
+ // Logging must never throw into gameplay code (disk full, file locked, etc.).
+ }
+ }
+
+ ///
+ /// Opens the writer for . Each file has one writing process: two
+ /// clients appending to one file each keep their own end-of-file offset and overwrite each
+ /// other's lines. When another client already holds the file, this process writes
+ /// {name}.{pid}.txt beside it instead (the engine's logs are per process the same way).
+ ///
+ private static StreamWriter OpenWriter(string path)
+ {
+ string folder = Path.GetDirectoryName(path)!;
+ System.IO.Directory.CreateDirectory(folder);
+ FileStream stream;
+ try
+ {
+ // FileShare.Read: readers (the launcher, editors) are fine; a second writer is refused.
+ stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
+ }
+ catch (IOException)
+ {
+ string own = Path.Combine(folder,
+ $"{Path.GetFileNameWithoutExtension(path)}.{Environment.ProcessId}{Path.GetExtension(path)}");
+ stream = new FileStream(own, FileMode.Append, FileAccess.Write, FileShare.Read);
+ }
+ return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = false };
+ }
+
+ /// Closes an oversized file and bumps its part number so the next write opens a fresh file.
+ private static void Roll(string path, StreamWriter writer)
+ {
+ try { writer.Flush(); writer.Dispose(); } catch { }
+ Writers.Remove(path);
+
+ string file = Path.GetFileNameWithoutExtension(path);
+ string day = DateTime.Now.ToString("yyyy-MM-dd");
+ int idx = file.IndexOf("_" + day, StringComparison.Ordinal);
+ string stem = idx > 0 ? file[..idx] : file;
+ string key = Path.GetDirectoryName(path) + "|" + stem + "|" + day;
+ RollParts[key] = (RollParts.TryGetValue(key, out int p) ? p : 0) + 1;
+ }
+
+ /// Closes yesterday's writers at midnight so new lines go to the new day's files.
+ private static void RollDayIfNeeded()
+ {
+ string day = DateTime.Now.ToString("yyyy-MM-dd");
+ if (day == _openDay) return;
+
+ foreach (var w in Writers.Values)
+ {
+ try { w.Flush(); w.Dispose(); } catch { }
+ }
+ Writers.Clear();
+ RollParts.Clear();
+ ExceptionSignatures.Clear();
+ _exceptionsToday = 0;
+ _openDay = day;
+ }
+
+ /// Per-signature exception throttle (UB budgets). Returns false when the entry should be skipped.
+ private static bool ShouldRecordException(string where, Exception ex, out int occurrence)
+ {
+ occurrence = 0;
+ lock (FileLock)
+ {
+ RollDayIfNeeded();
+ if (_exceptionsToday >= MaxExceptionsPerDay) return false;
+
+ string topFrame = ex.StackTrace?.Split('\n')[0].Trim() ?? string.Empty;
+ string signature = $"{where}|{ex.GetType().FullName}|{topFrame}";
+ DateTime now = DateTime.Now;
+
+ if (ExceptionSignatures.TryGetValue(signature, out var seen))
+ {
+ if (seen.count >= MaxExceptionsPerSignaturePerDay) return false;
+ // Repeats inside the burst window are dropped: a per-frame fault yields one entry per window.
+ if (now - seen.lastAt < ExceptionBurstWindow) return false;
+ occurrence = seen.count + 1;
+ }
+ else
+ {
+ occurrence = 1;
+ }
+
+ ExceptionSignatures[signature] = (now, occurrence);
+ _exceptionsToday++;
+ return true;
+ }
+ }
+
+ /// Hooks AppDomain / TaskScheduler so faults outside our try/catch blocks are still recorded.
+ private static void RegisterGlobalHandlers()
+ {
+ if (_handlersRegistered) return;
+ _handlersRegistered = true;
+
+ AppDomain.CurrentDomain.UnhandledException += (_, e) =>
+ {
+ if (e.ExceptionObject is Exception ex) Exception(LogCat.General, ex, "UnhandledException");
+ Flush();
+ };
+ TaskScheduler.UnobservedTaskException += (_, e) =>
+ {
+ Exception(LogCat.General, e.Exception, "UnobservedTaskException");
+ e.SetObserved();
+ };
+ }
+
+ /// Queues a chat echo line for the pump thread (WriteToChat is not render-thread safe).
+ private static void QueueChat(string line)
+ {
+ if (ChatQueue.Count < MaxQueuedChatLines) ChatQueue.Enqueue(line);
+ }
+
+ /// Removes old/excess *.txt files from one diagnostics folder. Caller holds .
+ private static int PruneFolder(string folder)
+ {
+ int removed = 0;
+ try
+ {
+ if (!System.IO.Directory.Exists(folder)) return 0;
+
+ var files = new List(new DirectoryInfo(folder).GetFiles("*.txt"));
+ files.Sort((a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc)); // newest first
+ DateTime cutoff = DateTime.UtcNow.AddDays(-Math.Max(1, _config.RetainDays));
+
+ for (int i = 0; i < files.Count; i++)
+ {
+ var f = files[i];
+ bool tooOld = f.LastWriteTimeUtc < cutoff;
+ bool overCount = i >= Math.Max(5, _config.MaxFiles);
+ if (!tooOld && !overCount) continue;
+ if (Writers.ContainsKey(f.FullName)) continue; // never delete a file we're writing
+
+ try { f.Delete(); removed++; } catch { }
+ }
+ }
+ catch { }
+ return removed;
+ }
+
+ private static string ConfigPath => Path.Combine(_directory, "diagnostics.json");
+
+ ///
+ /// Loads persisted switches; missing or corrupt files fall back to defaults. Merges the event
+ /// catalog into and returns true when that changed the
+ /// config (new events, refreshed descriptions, dropped stale keys), so the caller can save it.
+ ///
+ private static bool LoadConfig()
+ {
+ lock (ConfigLock)
+ {
+ try
+ {
+ if (File.Exists(ConfigPath))
+ {
+ _configStampUtc = File.GetLastWriteTimeUtc(ConfigPath);
+ string json = File.ReadAllText(ConfigPath);
+ _config = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.RynthLogConfig) ?? new RynthLogConfig();
+ }
+ }
+ catch
+ {
+ _config = new RynthLogConfig();
+ }
+
+ _config.Traces ??= new List();
+ bool categoriesChanged = MergeCategoryLevels();
+ bool eventsChanged = MergeEventCatalog();
+ return categoriesChanged || eventsChanged;
+ }
+ }
+
+ ///
+ /// Publishes the per-category levels from (or, for a file
+ /// from an older RynthAi with no Categories list, from ) and
+ /// rebuilds the Categories list in enum order with fresh descriptions. Returns true when the
+ /// persisted list needs rewriting. Caller holds .
+ ///
+ private static bool MergeCategoryLevels()
+ {
+ var levels = new int[CategoryLevels.Length];
+ bool fromCategories = _config.Categories != null && _config.Categories.Count > 0;
+
+ if (fromCategories)
+ {
+ foreach (LogCategorySetting s in _config.Categories!)
+ {
+ if (s == null || !TryParseCategory(s.Name, out LogCat cat)) continue;
+ if (Enum.TryParse(s.Level, ignoreCase: true, out LogEventLevel lvl) && Enum.IsDefined(lvl))
+ levels[(int)cat] = (int)lvl;
+ }
+ }
+ else
+ {
+ foreach (string name in _config.Traces)
+ if (TryParseCategory(name, out LogCat cat)) levels[(int)cat] = (int)LogEventLevel.Trace;
+ }
+
+ for (int i = 0; i < levels.Length; i++)
+ System.Threading.Volatile.Write(ref CategoryLevels[i], levels[i]);
+
+ List rows = BuildCategoryRows();
+ bool changed = !fromCategories || _config.Categories!.Count != rows.Count;
+ for (int i = 0; !changed && i < rows.Count; i++)
+ {
+ LogCategorySetting? old = _config.Categories![i];
+ if (old == null || old.Name != rows[i].Name || old.Level != rows[i].Level || old.Description != rows[i].Description)
+ changed = true;
+ }
+ _config.Categories = rows;
+ return changed;
+ }
+
+ /// Snapshot of the live category levels as persisted rows, in enum order.
+ private static List BuildCategoryRows()
+ {
+ var rows = new List(CategoryLevels.Length);
+ foreach (LogCat cat in Enum.GetValues())
+ {
+ rows.Add(new LogCategorySetting
+ {
+ Name = cat.ToString(),
+ Level = GetCategoryLevel(cat).ToString(),
+ Description = LogEvents.DescribeCategory(cat),
+ });
+ }
+ return rows;
+ }
+
+ ///
+ /// Rebuilds in catalog order, keeping each saved level and
+ /// publishing the live level table. Returns true when the persisted list needs rewriting.
+ ///
+ private static bool MergeEventCatalog()
+ {
+ var saved = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (LogEventSetting e in _config.Events ?? new List())
+ if (e != null && !string.IsNullOrEmpty(e.Key)) saved[e.Key] = e;
+
+ bool changed = (_config.Events?.Count ?? 0) != LogEvents.Catalog.Length;
+ var merged = new List(LogEvents.Catalog.Length);
+ var levels = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ foreach (LogEvents.Definition def in LogEvents.Catalog)
+ {
+ LogEventLevel level = def.Default;
+ if (saved.TryGetValue(def.Key, out LogEventSetting? s)
+ && Enum.TryParse(s.Level, ignoreCase: true, out LogEventLevel parsed) && Enum.IsDefined(parsed))
+ level = parsed;
+ else
+ changed = true; // new event, or an unreadable level reset to its default
+
+ var row = new LogEventSetting
+ {
+ Key = def.Key,
+ Level = level.ToString(),
+ Default = def.Default.ToString(),
+ Category = def.Category.ToString(),
+ Description = def.Description,
+ };
+ if (s == null || s.Level != row.Level || s.Default != row.Default
+ || s.Category != row.Category || s.Description != row.Description)
+ changed = true;
+
+ merged.Add(row);
+ levels[def.Key] = level;
+ }
+
+ _config.Events = merged;
+ _eventLevels = levels;
+ return changed;
+ }
+
+ /// Default level table, used until diagnostics.json has been loaded.
+ private static Dictionary BuildDefaultEventLevels()
+ {
+ var d = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (LogEvents.Definition def in LogEvents.Catalog) d[def.Key] = def.Default;
+ return d;
+ }
+
+ /// Event key → owning category (fixed by the catalog).
+ private static Dictionary BuildEventCategories()
+ {
+ var d = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (LogEvents.Definition def in LogEvents.Catalog) d[def.Key] = def.Category;
+ return d;
+ }
+
+ ///
+ /// Persists the current switches (trace set and category rows are rebuilt from the live levels).
+ /// Mutators call first, so a launcher edit made since our
+ /// last load is adopted before this write rather than silently reverted.
+ ///
+ private static void SaveConfig()
+ {
+ // Toggles come from both the pump thread (/ra trace) and the render thread (Diagnostics tab).
+ lock (ConfigLock)
+ {
+ try
+ {
+ _config.Traces = TracedCategories().ConvertAll(c => c.ToString());
+ _config.Categories = BuildCategoryRows();
+ System.IO.Directory.CreateDirectory(_directory);
+ File.WriteAllText(ConfigPath, JsonSerializer.Serialize(_config, RynthAiJsonContext.Default.RynthLogConfig));
+ _configStampUtc = File.GetLastWriteTimeUtc(ConfigPath);
+ }
+ catch { }
+ }
+ }
+
+ ///
+ /// Reloads diagnostics.json when the launcher has written it since our last load/save, so the
+ /// mutation that follows starts from the launcher's values. Caller holds .
+ ///
+ private static void SyncFromDiskIfChanged()
+ {
+ try
+ {
+ if (File.Exists(ConfigPath) && File.GetLastWriteTimeUtc(ConfigPath) != _configStampUtc)
+ LoadConfig();
+ }
+ catch
+ {
+ // Unreadable file: keep our in-memory switches.
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs
index 6261eee..49e8d2c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardStore.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
@@ -23,7 +24,7 @@ namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardStore
{
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
- private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi\DungeonHazards";
+ private static readonly string Folder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"DungeonHazards");
private static string PathFor(uint landblockKey)
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs
index 6c207df..12be112 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonHazardSurfaces.cs
@@ -30,13 +30,14 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardSurfaces
{
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
- private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi";
+ private static readonly string Folder = RynthInstallPaths.RynthAiDir;
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
private static readonly object _gate = new();
diff --git a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs
new file mode 100644
index 0000000..2017b85
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs
@@ -0,0 +1,355 @@
+// GroundLootController.cs — picks up loose ground items that match the active loot profile
+// (UB-IT AutoGroundLoot, driven by RynthAi's own loot rules and corpse range).
+//
+// * Scan: every GroundScanIntervalMs, objects lying in the world (readable ownership with
+// no container / wielder, finite distance) within the corpse max range, minus scenery /
+// creatures / doors / corpses, are classified with the same ClassifyItemAgainstProfile
+// the corpse looter uses. Stat-gated rules get a server appraisal first (a few per scan),
+// then a best-effort classify once GroundAppraiseWaitMs passes.
+// * Pickup: only once the activity arbiter has handed the tick to Looting (HasLootWork sees
+// the matches, so navigation is already stopped). MoveItemExternal(item → player); ACE
+// walks the character to the item and picks it up. Confirmed when the item leaves the
+// ground, retried up to GroundMaxPickupAttempts, then put on a long cooldown.
+// * Corpses always win: ground loot only runs when no corpse is claimed or open.
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi;
+
+public sealed partial class RynthAiPlugin
+{
+ private const long GroundScanIntervalMs = 300;
+ /// Classify best-effort after waiting this long for an item's appraisal.
+ private const long GroundAppraiseWaitMs = 3_000;
+ /// Server move-to plus pickup animation must finish inside this window before a retry.
+ private const long GroundPickupVerifyMs = 5_000;
+ /// A claimed item whose pickup could never be sent (client stayed busy) is dropped after this.
+ private const long GroundClaimStallMs = 10_000;
+ /// Items that matched no rule are re-checked after this (profile edits, late appraisal).
+ private const long GroundLeaveCooldownMs = 60_000;
+ private const long GroundFailCooldownMs = 300_000;
+ private const int GroundMaxPickupAttempts = 3;
+ private const int GroundAppraisalsPerScan = 2;
+
+ private long _groundLastScanAt;
+ private int _groundMatchesInRange;
+ private int _groundTargetId;
+ private long _groundTargetSince;
+ private long _groundPickupRequestedAt;
+ private int _groundPickupAttempts;
+ private string _groundTargetName = string.Empty;
+ private string _groundTargetAction = string.Empty;
+ private string _groundTargetRule = string.Empty;
+ private bool _groundTargetIsSalvage;
+ /// id → ms before which the item is not re-evaluated (left, failed or gone).
+ private readonly Dictionary _groundSkipUntil = new();
+ /// id → ms of the first appraisal request (bounds the wait for stat data).
+ private readonly Dictionary _groundAppraiseAt = new();
+
+ /// A pickup request is out and not yet confirmed — corpse claims wait for it.
+ private bool GroundPickupInFlight => _groundTargetId != 0 && _groundPickupRequestedAt != 0;
+
+ /// Arbiter input: a claimed ground item, or matching ground items seen by the last scan.
+ private bool HasGroundLootWork(LegacyUiSettings settings)
+ => settings.EnableGroundLoot && (_groundTargetId != 0 || _groundMatchesInRange > 0);
+
+ ///
+ /// One ground-loot step (pump thread, called from TickCorpseOpening when no corpse is
+ /// claimed or open). Gating for macro / looting / buffing / combat is done by the caller.
+ ///
+ private void TickGroundLoot(LegacyUiSettings settings, double maxMeters)
+ {
+ if (!settings.EnableGroundLoot || _objectCache == null || _playerId == 0)
+ {
+ ResetGroundLoot(clearCaches: false);
+ return;
+ }
+
+ long now = CorpseNowMs;
+ if (_groundTargetId != 0)
+ {
+ TickGroundTarget(maxMeters, now);
+ return;
+ }
+
+ if (now - _groundLastScanAt < GroundScanIntervalMs)
+ return;
+ _groundLastScanAt = now;
+ PruneGroundCollections(now);
+
+ WorldObject? best = ScanGroundLoot(settings, maxMeters, now, out double bestDist,
+ out string action, out string rule, out bool salvage);
+ if (best == null)
+ return;
+
+ // HasLootWork reports the match; wait until the arbiter actually gives Looting the tick.
+ if (_activity != BotActivity.Looting)
+ return;
+
+ _groundTargetId = best.Id;
+ _groundTargetSince = now;
+ _groundPickupRequestedAt = 0;
+ _groundPickupAttempts = 0;
+ _groundTargetName = best.Name ?? string.Empty;
+ _groundTargetAction = action;
+ _groundTargetRule = rule;
+ _groundTargetIsSalvage = salvage;
+ if (!(_navStopIssued && _navStoppedFor == BotActivity.Looting))
+ StopNavFor(BotActivity.Looting);
+ LootDiag($"[RynthAi] Ground loot: claimed 0x{(uint)best.Id:X8} '{_groundTargetName}' dist={bestDist:F1}m [{action}] rule='{rule}'.");
+ TryRequestGroundPickup(now);
+ }
+
+ ///
+ /// Finds the nearest ground item that matches the loot profile and counts all matches
+ /// in range (for ). Requests appraisal for stat-gated items.
+ ///
+ private WorldObject? ScanGroundLoot(LegacyUiSettings settings, double maxMeters, long now,
+ out double bestDist, out string bestAction, out string bestRule, out bool bestSalvage)
+ {
+ bestDist = double.MaxValue;
+ bestAction = bestRule = string.Empty;
+ bestSalvage = false;
+ _groundMatchesInRange = 0;
+ if (_objectCache == null || maxMeters <= 0.25)
+ return null;
+ // The profile loaders chat on every failed load; a 300 ms scan must not trigger that.
+ string profilePath = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"');
+ if (profilePath.Length == 0 || !System.IO.File.Exists(profilePath))
+ return null;
+
+ int playerId = unchecked((int)_playerId);
+ int appraisalsSent = 0;
+ WorldObject? best = null;
+
+ foreach (WorldObject wo in _objectCache.AllKnownObjects())
+ {
+ if (wo.Id == playerId || IsGroundLootExcludedClass(wo.ObjectClass))
+ continue;
+ if (_groundSkipUntil.TryGetValue(wo.Id, out long until))
+ {
+ if (until > now) continue;
+ _groundSkipUntil.Remove(wo.Id);
+ }
+ if (string.IsNullOrWhiteSpace(wo.Name))
+ continue;
+
+ // Carried / contained items have no world position, so Distance is MaxValue for them.
+ double dist = _objectCache.Distance(playerId, wo.Id);
+ if (dist > maxMeters)
+ continue;
+ if (!_objectCache.IsOnGround(wo.Id))
+ continue;
+
+ uint uid = unchecked((uint)wo.Id);
+ bool appraised = Host.HasHasAppraisalData && Host.HasAppraisalData(uid);
+ if (!appraised && ItemNeedsAppraisalForLoot(wo))
+ {
+ if (!_groundAppraiseAt.TryGetValue(wo.Id, out long firstAsk))
+ {
+ if (appraisalsSent < GroundAppraisalsPerScan && _busyCount == 0 && Host.RequestId(uid))
+ {
+ _groundAppraiseAt[wo.Id] = now;
+ appraisalsSent++;
+ }
+ continue;
+ }
+ if (now - firstAsk < GroundAppraiseWaitMs)
+ continue;
+ // Appraisal never arrived — classify best-effort, like the corpse assess window.
+ }
+
+ bool keep = ClassifyItemAgainstProfile(wo, settings, out string action, out bool salvage, out string rule);
+ LootDiag($"[LootEval] ground '{wo.Name}' cls={wo.ObjectClass} dist={dist:F1}m appraised={appraised} -> " +
+ (keep ? $"KEEP [{action}] rule='{rule}'" : "leave"));
+ if (!keep)
+ {
+ _groundSkipUntil[wo.Id] = now + GroundLeaveCooldownMs;
+ continue;
+ }
+
+ _groundMatchesInRange++;
+ if (dist < bestDist)
+ {
+ best = wo;
+ bestDist = dist;
+ bestAction = action;
+ bestRule = rule;
+ bestSalvage = salvage;
+ }
+ }
+
+ return best;
+ }
+
+ /// Follows a claimed item: confirm pickup, retry, or give up.
+ private void TickGroundTarget(double maxMeters, long now)
+ {
+ if (_objectCache == null)
+ return;
+
+ int id = _groundTargetId;
+ WorldObject? item = _objectCache[id];
+ if (item == null)
+ {
+ // Deleted from the world: decayed or another player took it.
+ LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' is gone.");
+ FinishGroundTarget(now, GroundFailCooldownMs);
+ return;
+ }
+
+ if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0)
+ {
+ LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'.");
+ ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)");
+ if (_groundTargetIsSalvage)
+ _salvageManager?.EnqueueItem(unchecked((uint)id));
+ FinishGroundTarget(now, GroundFailCooldownMs);
+ return;
+ }
+
+ int playerId = unchecked((int)_playerId);
+ double dist = _objectCache.Distance(playerId, id);
+ if (dist > Math.Max(maxMeters * 1.5, maxMeters + 2.0))
+ {
+ LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' drifted out of range ({dist:F1}m); releasing.");
+ FinishGroundTarget(now, GroundLeaveCooldownMs);
+ return;
+ }
+
+ if (_groundPickupRequestedAt == 0)
+ {
+ if (now - _groundTargetSince > GroundClaimStallMs)
+ {
+ LootDiag($"[RynthAi] Ground loot: could not send pickup for 0x{(uint)id:X8} (client busy); releasing.");
+ FinishGroundTarget(now, GroundLeaveCooldownMs);
+ return;
+ }
+ TryRequestGroundPickup(now);
+ return;
+ }
+
+ if (now - _groundPickupRequestedAt < GroundPickupVerifyMs)
+ return;
+
+ if (_groundPickupAttempts >= GroundMaxPickupAttempts)
+ {
+ LootDiag($"[RynthAi] Ground loot: pickup failed for 0x{(uint)id:X8} '{_groundTargetName}' after {_groundPickupAttempts} attempt(s).");
+ FinishGroundTarget(now, GroundFailCooldownMs);
+ return;
+ }
+
+ TryRequestGroundPickup(now);
+ }
+
+ /// Sends the pickup (item → player's main pack) when the client isn't busy.
+ private void TryRequestGroundPickup(long now)
+ {
+ if (_busyCount > 0 || _groundTargetId == 0)
+ return;
+
+ uint uid = unchecked((uint)_groundTargetId);
+ Host.SelectItem(uid);
+ bool sent = Host.HasMoveItemExternal
+ ? Host.MoveItemExternal(uid, _playerId, 0)
+ : Host.UseObject(uid);
+ _groundPickupAttempts++;
+ _groundPickupRequestedAt = now;
+ LootDiag($"[RynthAi] Ground loot: pickup {(sent ? "sent" : "rejected")} for 0x{uid:X8} attempt {_groundPickupAttempts}.");
+ }
+
+ /// Releases the claimed item and parks it for .
+ private void FinishGroundTarget(long now, long cooldownMs)
+ {
+ if (_groundTargetId != 0)
+ {
+ _groundSkipUntil[_groundTargetId] = now + cooldownMs;
+ _groundAppraiseAt.Remove(_groundTargetId);
+ }
+ _groundTargetId = 0;
+ _groundTargetSince = 0;
+ _groundPickupRequestedAt = 0;
+ _groundPickupAttempts = 0;
+ _groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
+ _groundTargetIsSalvage = false;
+ _groundLastScanAt = 0; // rescan straight away for the next item
+ }
+
+ /// Drops the claim (and optionally the per-item caches, e.g. on logout or /ra groundloot scan).
+ private void ResetGroundLoot(bool clearCaches)
+ {
+ _groundTargetId = 0;
+ _groundTargetSince = 0;
+ _groundPickupRequestedAt = 0;
+ _groundPickupAttempts = 0;
+ _groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
+ _groundTargetIsSalvage = false;
+ _groundMatchesInRange = 0;
+ if (!clearCaches)
+ return;
+ _groundSkipUntil.Clear();
+ _groundAppraiseAt.Clear();
+ _groundLastScanAt = 0;
+ }
+
+ /// Keeps the per-item maps bounded.
+ private void PruneGroundCollections(long now)
+ {
+ if (_groundSkipUntil.Count > 512)
+ {
+ var expired = new List();
+ foreach (var kv in _groundSkipUntil)
+ if (kv.Value <= now) expired.Add(kv.Key);
+ foreach (int k in expired) _groundSkipUntil.Remove(k);
+ }
+ if (_groundAppraiseAt.Count > 256)
+ {
+ var stale = new List();
+ foreach (var kv in _groundAppraiseAt)
+ if (now - kv.Value > GroundLeaveCooldownMs) stale.Add(kv.Key);
+ foreach (int k in stale) _groundAppraiseAt.Remove(k);
+ }
+ }
+
+ /// Scenery, creatures, fixtures and containers are never picked up from the ground.
+ private static bool IsGroundLootExcludedClass(AcObjectClass cls) => cls is
+ AcObjectClass.Unknown or AcObjectClass.Monster or AcObjectClass.Player or AcObjectClass.Npc
+ or AcObjectClass.Vendor or AcObjectClass.Portal or AcObjectClass.Door or AcObjectClass.Corpse
+ or AcObjectClass.Lifestone or AcObjectClass.Sign or AcObjectClass.Housing or AcObjectClass.Container
+ or AcObjectClass.CombatPet or AcObjectClass.Services;
+
+ /// /ra groundloot [on|off|status|scan]
+ private void HandleGroundLootCommand(string[] parts)
+ {
+ var settings = _dashboard?.Settings;
+ if (settings == null) { ChatLine("[RynthAi] Not logged in."); return; }
+
+ string verb = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status";
+ switch (verb)
+ {
+ case "on":
+ settings.EnableGroundLoot = true;
+ _dashboard?.SaveSettings();
+ ChatLine("[RynthAi] Ground loot ON (uses the loot profile and the corpse max range).");
+ break;
+ case "off":
+ settings.EnableGroundLoot = false;
+ ResetGroundLoot(clearCaches: true);
+ _dashboard?.SaveSettings();
+ ChatLine("[RynthAi] Ground loot OFF.");
+ break;
+ case "scan":
+ ResetGroundLoot(clearCaches: true);
+ ChatLine("[RynthAi] Ground loot: cleared skip list; rescanning.");
+ break;
+ default:
+ double yards = settings.CorpseApproachRangeMax;
+ string target = _groundTargetId != 0 ? $" | target '{_groundTargetName}' attempts={_groundPickupAttempts}" : string.Empty;
+ ChatLine($"[RynthAi] Ground loot {(settings.EnableGroundLoot ? "ON" : "OFF")} | range {yards:0.#} yd | " +
+ $"looting {(settings.EnableLooting ? "on" : "off")} | matches in range {_groundMatchesInRange} | " +
+ $"skipped {_groundSkipUntil.Count}{target}");
+ break;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs
new file mode 100644
index 0000000..05820bd
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/CombatHudTracker.cs
@@ -0,0 +1,223 @@
+// CombatHudTracker.cs — Pump-thread feed for the Mini Remote's Target and Summon rows.
+//
+// Target the creature combat is attacking (CombatManager.activeTargetId): name, health
+// ratio from the object cache, distance.
+// Summon the player's pet ("'s " in the landscape): health ratio (polled with
+// QueryHealth) and time left (RemainingLifespan from one appraisal, then counted
+// down locally).
+//
+// The render thread only reads the published immutable snapshot.
+using System;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+/// Immutable view of the attack target and the active summon (render thread safe).
+internal sealed record CombatHudSnapshot(
+ int TargetId,
+ string TargetName,
+ float TargetHealth, // 0..1, -1 = no health received yet
+ double TargetDistance, // yards, < 0 = unknown
+ int PetId,
+ string PetName,
+ float PetHealth, // 0..1, -1 = no health received yet
+ long PetExpiresAtMs, // Environment.TickCount64 deadline, 0 = lifespan unknown
+ int PetLifespanSec, // total lifespan, 0 = unknown
+ long PetSeenAtMs) // when this pet first appeared
+{
+ public static readonly CombatHudSnapshot Empty = new(0, string.Empty, -1f, -1, 0, string.Empty, -1f, 0, 0, 0);
+}
+
+internal sealed class CombatHudTracker
+{
+ private const uint StypeLifespan = 267;
+ private const uint StypeRemainingLifespan = 268;
+ private const long ThinkIntervalMs = 250;
+ // QueryHealth makes the server stream that creature's health to us instead of the previous
+ // query's, so each pet poll is followed by a re-query of the combat / selected target.
+ private const long PetHealthPollMs = 3000;
+ private const long AppraiseRetryMs = 5000;
+ private const int AppraiseMaxAttempts = 3;
+ private const long PlayerNameRefreshMs = 30_000;
+
+ private readonly RynthCoreHost _host;
+ private readonly Func _cache;
+ private readonly Func _attackTargetId;
+
+ private volatile CombatHudSnapshot _snapshot = CombatHudSnapshot.Empty;
+ private long _lastThinkAt;
+
+ private string _playerName = string.Empty;
+ private long _playerNameAt;
+
+ // Current pet bookkeeping.
+ private int _petId;
+ private long _petSeenAt;
+ private long _petExpiresAt;
+ private int _petLifespanSec;
+ private int _appraiseAttempts;
+ private long _lastAppraiseAt;
+ private long _lastPetHealthAt;
+
+ public CombatHudTracker(RynthCoreHost host, Func cache, Func attackTargetId)
+ {
+ _host = host;
+ _cache = cache;
+ _attackTargetId = attackTargetId;
+ }
+
+ /// Latest target / summon view.
+ public CombatHudSnapshot Snapshot => _snapshot;
+
+ private static long NowMs => Environment.TickCount64;
+
+ /// Refreshes the snapshot (pump thread). Cheap when called every tick.
+ public void Tick()
+ {
+ long now = NowMs;
+ if (now - _lastThinkAt < ThinkIntervalMs) return;
+ _lastThinkAt = now;
+
+ var cache = _cache();
+ if (cache == null) { _snapshot = CombatHudSnapshot.Empty; return; }
+
+ int playerId = unchecked((int)_host.GetPlayerId());
+ int targetId = _attackTargetId();
+
+ // ── Attack target ──
+ string targetName = string.Empty;
+ float targetHealth = -1f;
+ double targetDist = -1;
+ if (targetId != 0)
+ {
+ targetName = cache[targetId]?.Name ?? string.Empty;
+ if (targetName.Length == 0 && _host.TryGetObjectName(unchecked((uint)targetId), out string n)) targetName = n;
+ if (targetName.Length == 0) targetName = $"0x{(uint)targetId:X8}";
+ targetHealth = cache.GetHealthRatio(targetId);
+ if (playerId != 0)
+ {
+ double d = cache.Distance(playerId, targetId);
+ targetDist = d < double.MaxValue ? d : -1;
+ }
+ }
+
+ // ── Summon ──
+ var pet = FindOwnPet(cache);
+ string petName = string.Empty;
+ float petHealth = -1f;
+ if (pet == null)
+ {
+ ForgetPet();
+ }
+ else
+ {
+ if (pet.Id != _petId) StartTrackingPet(pet.Id, now);
+ petName = StripOwner(pet.Name);
+ TickPetLifespan(now);
+ TickPetHealth(now, targetId);
+ petHealth = cache.GetHealthRatio(_petId);
+ }
+
+ _snapshot = new CombatHudSnapshot(targetId, targetName, targetHealth, targetDist,
+ _petId, petName, petHealth, _petExpiresAt, _petLifespanSec, _petSeenAt);
+ }
+
+ public void OnLogout()
+ {
+ ForgetPet();
+ _playerName = string.Empty;
+ _snapshot = CombatHudSnapshot.Empty;
+ }
+
+ // ── Pet ─────────────────────────────────────────────────────────────────
+
+ private WorldObject? FindOwnPet(WorldObjectCache cache)
+ {
+ string me = PlayerName();
+ if (me.Length == 0) return null;
+ string prefix = me + "'s ";
+ foreach (var wo in cache.GetLandscape())
+ if (wo != null && !string.IsNullOrEmpty(wo.Name) && wo.Name.StartsWith(prefix, StringComparison.Ordinal))
+ return wo;
+ return null;
+ }
+
+ private string PlayerName()
+ {
+ long now = NowMs;
+ if (_playerName.Length > 0 && now - _playerNameAt < PlayerNameRefreshMs) return _playerName;
+ uint pid = _host.GetPlayerId();
+ if (pid != 0 && _host.TryGetObjectName(pid, out string n) && !string.IsNullOrEmpty(n))
+ {
+ _playerName = n;
+ _playerNameAt = now;
+ }
+ return _playerName;
+ }
+
+ /// "Silent's Fire Banshee" → "Fire Banshee".
+ private string StripOwner(string name)
+ {
+ string prefix = _playerName + "'s ";
+ return _playerName.Length > 0 && name.StartsWith(prefix, StringComparison.Ordinal) ? name[prefix.Length..] : name;
+ }
+
+ private void StartTrackingPet(int id, long now)
+ {
+ _petId = id;
+ _petSeenAt = now;
+ _petExpiresAt = 0;
+ _petLifespanSec = 0;
+ _appraiseAttempts = 0;
+ _lastAppraiseAt = 0;
+ _lastPetHealthAt = 0;
+ RynthLog.Trace(LogCat.Huds, $"summon tracked 0x{(uint)id:X8}");
+ }
+
+ private void ForgetPet()
+ {
+ _petId = 0;
+ _petSeenAt = 0;
+ _petExpiresAt = 0;
+ _petLifespanSec = 0;
+ _appraiseAttempts = 0;
+ }
+
+ ///
+ /// Appraises the new pet (at most times) and anchors the
+ /// countdown on the first RemainingLifespan the server returns. The pet's guid is new, so
+ /// any cached value belongs to this pet.
+ ///
+ private void TickPetLifespan(long now)
+ {
+ if (_petExpiresAt != 0) return;
+ uint uid = unchecked((uint)_petId);
+
+ if (_host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, StypeRemainingLifespan, out int remaining) && remaining > 0)
+ {
+ _petExpiresAt = now + remaining * 1000L;
+ if (_host.TryGetObjectIntProperty(uid, StypeLifespan, out int total) && total > 0)
+ _petLifespanSec = Math.Max(total, remaining);
+ RynthLog.Trace(LogCat.Huds, $"summon 0x{uid:X8}: {remaining}s left of {_petLifespanSec}s");
+ return;
+ }
+
+ if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return;
+ if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return;
+ _appraiseAttempts++;
+ _lastAppraiseAt = now;
+ _host.RequestId(uid);
+ }
+
+ /// Polls the pet's health, then hands the server's health stream back to the fight target.
+ private void TickPetHealth(long now, int combatTargetId)
+ {
+ if (!_host.HasQueryHealth || now - _lastPetHealthAt < PetHealthPollMs) return;
+ _lastPetHealthAt = now;
+ _host.QueryHealth(unchecked((uint)_petId));
+
+ uint restore = combatTargetId != 0 ? unchecked((uint)combatTargetId) : 0;
+ if (restore == 0 && _host.HasGetSelectedItemId) restore = _host.GetSelectedItemId();
+ if (restore != 0 && restore != unchecked((uint)_petId)) _host.QueryHealth(restore);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/DxtUtil.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/DxtUtil.cs
new file mode 100644
index 0000000..f83fd04
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/DxtUtil.cs
@@ -0,0 +1,442 @@
+// #region License
+// /*
+// Microsoft Public License (Ms-PL)
+// MonoGame - Copyright © 2009 The MonoGame Team
+//
+// All rights reserved.
+//
+// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
+// accept the license, do not use the software.
+//
+// 1. Definitions
+// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
+// U.S. copyright law.
+//
+// A "contribution" is the original software, or any additions or changes to the software.
+// A "contributor" is any person that distributes its contribution under this license.
+// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
+//
+// 2. Grant of Rights
+// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
+// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
+// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
+// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
+//
+// 3. Conditions and Limitations
+// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
+// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
+// your patent license from such contributor to the software ends automatically.
+// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
+// notices that are present in the software.
+// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
+// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
+// code form, you may only do so under a license that complies with this license.
+// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
+// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
+// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
+// purpose and non-infringement.
+// */
+// #endregion License
+//
+
+namespace RynthCore.Plugin.RynthAi.Huds
+{
+ using System.IO;
+
+ internal static class DxtUtil
+ {
+ internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
+ {
+ using (MemoryStream imageStream = new MemoryStream(imageData))
+ return DecompressDxt1(imageStream, width, height);
+ }
+
+ internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
+ {
+ byte[] imageData = new byte[width * height * 4];
+
+ using (BinaryReader imageReader = new BinaryReader(imageStream))
+ {
+ int blockCountX = (width + 3) / 4;
+ int blockCountY = (height + 3) / 4;
+
+ for (int y = 0; y < blockCountY; y++)
+ {
+ for (int x = 0; x < blockCountX; x++)
+ {
+ DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
+ }
+ }
+ }
+
+ return imageData;
+ }
+
+ private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
+ {
+ ushort c0 = imageReader.ReadUInt16();
+ ushort c1 = imageReader.ReadUInt16();
+
+ byte r0, g0, b0;
+ byte r1, g1, b1;
+ ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
+ ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
+
+ uint lookupTable = imageReader.ReadUInt32();
+
+ for (int blockY = 0; blockY < 4; blockY++)
+ {
+ for (int blockX = 0; blockX < 4; blockX++)
+ {
+ byte r = 0, g = 0, b = 0, a = 255;
+ uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
+
+ if (c0 > c1)
+ {
+ switch (index)
+ {
+ case 0:
+ r = r0;
+ g = g0;
+ b = b0;
+ break;
+ case 1:
+ r = r1;
+ g = g1;
+ b = b1;
+ break;
+ case 2:
+ r = (byte)((2 * r0 + r1) / 3);
+ g = (byte)((2 * g0 + g1) / 3);
+ b = (byte)((2 * b0 + b1) / 3);
+ break;
+ case 3:
+ r = (byte)((r0 + 2 * r1) / 3);
+ g = (byte)((g0 + 2 * g1) / 3);
+ b = (byte)((b0 + 2 * b1) / 3);
+ break;
+ }
+ }
+ else
+ {
+ switch (index)
+ {
+ case 0:
+ r = r0;
+ g = g0;
+ b = b0;
+ break;
+ case 1:
+ r = r1;
+ g = g1;
+ b = b1;
+ break;
+ case 2:
+ r = (byte)((r0 + r1) / 2);
+ g = (byte)((g0 + g1) / 2);
+ b = (byte)((b0 + b1) / 2);
+ break;
+ case 3:
+ r = 0;
+ g = 0;
+ b = 0;
+ a = 0;
+ break;
+ }
+ }
+
+ int px = (x << 2) + blockX;
+ int py = (y << 2) + blockY;
+ if ((px < width) && (py < height))
+ {
+ int offset = ((py * width) + px) << 2;
+ imageData[offset] = r;
+ imageData[offset + 1] = g;
+ imageData[offset + 2] = b;
+ imageData[offset + 3] = a;
+ }
+ }
+ }
+ }
+
+ internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
+ {
+ using (MemoryStream imageStream = new MemoryStream(imageData))
+ return DecompressDxt3(imageStream, width, height);
+ }
+
+ internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
+ {
+ byte[] imageData = new byte[width * height * 4];
+
+ using (BinaryReader imageReader = new BinaryReader(imageStream))
+ {
+ int blockCountX = (width + 3) / 4;
+ int blockCountY = (height + 3) / 4;
+
+ for (int y = 0; y < blockCountY; y++)
+ {
+ for (int x = 0; x < blockCountX; x++)
+ {
+ DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
+ }
+ }
+ }
+
+ return imageData;
+ }
+
+ private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
+ {
+ byte a0 = imageReader.ReadByte();
+ byte a1 = imageReader.ReadByte();
+ byte a2 = imageReader.ReadByte();
+ byte a3 = imageReader.ReadByte();
+ byte a4 = imageReader.ReadByte();
+ byte a5 = imageReader.ReadByte();
+ byte a6 = imageReader.ReadByte();
+ byte a7 = imageReader.ReadByte();
+
+ ushort c0 = imageReader.ReadUInt16();
+ ushort c1 = imageReader.ReadUInt16();
+
+ byte r0, g0, b0;
+ byte r1, g1, b1;
+ ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
+ ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
+
+ uint lookupTable = imageReader.ReadUInt32();
+
+ int alphaIndex = 0;
+ for (int blockY = 0; blockY < 4; blockY++)
+ {
+ for (int blockX = 0; blockX < 4; blockX++)
+ {
+ byte r = 0, g = 0, b = 0, a = 0;
+
+ uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
+
+ switch (alphaIndex)
+ {
+ case 0:
+ a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
+ break;
+ case 1:
+ a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
+ break;
+ case 2:
+ a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
+ break;
+ case 3:
+ a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
+ break;
+ case 4:
+ a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
+ break;
+ case 5:
+ a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
+ break;
+ case 6:
+ a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
+ break;
+ case 7:
+ a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
+ break;
+ case 8:
+ a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
+ break;
+ case 9:
+ a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
+ break;
+ case 10:
+ a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
+ break;
+ case 11:
+ a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
+ break;
+ case 12:
+ a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
+ break;
+ case 13:
+ a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
+ break;
+ case 14:
+ a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
+ break;
+ case 15:
+ a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
+ break;
+ }
+ ++alphaIndex;
+
+ switch (index)
+ {
+ case 0:
+ r = r0;
+ g = g0;
+ b = b0;
+ break;
+ case 1:
+ r = r1;
+ g = g1;
+ b = b1;
+ break;
+ case 2:
+ r = (byte)((2 * r0 + r1) / 3);
+ g = (byte)((2 * g0 + g1) / 3);
+ b = (byte)((2 * b0 + b1) / 3);
+ break;
+ case 3:
+ r = (byte)((r0 + 2 * r1) / 3);
+ g = (byte)((g0 + 2 * g1) / 3);
+ b = (byte)((b0 + 2 * b1) / 3);
+ break;
+ }
+
+ int px = (x << 2) + blockX;
+ int py = (y << 2) + blockY;
+ if ((px < width) && (py < height))
+ {
+ int offset = ((py * width) + px) << 2;
+ imageData[offset] = r;
+ imageData[offset + 1] = g;
+ imageData[offset + 2] = b;
+ imageData[offset + 3] = a;
+ }
+ }
+ }
+ }
+
+ internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
+ {
+ using (MemoryStream imageStream = new MemoryStream(imageData))
+ return DecompressDxt5(imageStream, width, height);
+ }
+
+ internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
+ {
+ byte[] imageData = new byte[width * height * 4];
+
+ using (BinaryReader imageReader = new BinaryReader(imageStream))
+ {
+ int blockCountX = (width + 3) / 4;
+ int blockCountY = (height + 3) / 4;
+
+ for (int y = 0; y < blockCountY; y++)
+ {
+ for (int x = 0; x < blockCountX; x++)
+ {
+ DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
+ }
+ }
+ }
+
+ return imageData;
+ }
+
+ private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
+ {
+ byte alpha0 = imageReader.ReadByte();
+ byte alpha1 = imageReader.ReadByte();
+
+ ulong alphaMask = (ulong)imageReader.ReadByte();
+ alphaMask += (ulong)imageReader.ReadByte() << 8;
+ alphaMask += (ulong)imageReader.ReadByte() << 16;
+ alphaMask += (ulong)imageReader.ReadByte() << 24;
+ alphaMask += (ulong)imageReader.ReadByte() << 32;
+ alphaMask += (ulong)imageReader.ReadByte() << 40;
+
+ ushort c0 = imageReader.ReadUInt16();
+ ushort c1 = imageReader.ReadUInt16();
+
+ byte r0, g0, b0;
+ byte r1, g1, b1;
+ ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
+ ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
+
+ uint lookupTable = imageReader.ReadUInt32();
+
+ for (int blockY = 0; blockY < 4; blockY++)
+ {
+ for (int blockX = 0; blockX < 4; blockX++)
+ {
+ byte r = 0, g = 0, b = 0, a = 255;
+ uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
+
+ uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
+ if (alphaIndex == 0)
+ {
+ a = alpha0;
+ }
+ else if (alphaIndex == 1)
+ {
+ a = alpha1;
+ }
+ else if (alpha0 > alpha1)
+ {
+ a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
+ }
+ else if (alphaIndex == 6)
+ {
+ a = 0;
+ }
+ else if (alphaIndex == 7)
+ {
+ a = 0xff;
+ }
+ else
+ {
+ a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
+ }
+
+ switch (index)
+ {
+ case 0:
+ r = r0;
+ g = g0;
+ b = b0;
+ break;
+ case 1:
+ r = r1;
+ g = g1;
+ b = b1;
+ break;
+ case 2:
+ r = (byte)((2 * r0 + r1) / 3);
+ g = (byte)((2 * g0 + g1) / 3);
+ b = (byte)((2 * b0 + b1) / 3);
+ break;
+ case 3:
+ r = (byte)((r0 + 2 * r1) / 3);
+ g = (byte)((g0 + 2 * g1) / 3);
+ b = (byte)((b0 + 2 * b1) / 3);
+ break;
+ }
+
+ int px = (x << 2) + blockX;
+ int py = (y << 2) + blockY;
+ if ((px < width) && (py < height))
+ {
+ int offset = ((py * width) + px) << 2;
+ imageData[offset] = r;
+ imageData[offset + 1] = g;
+ imageData[offset + 2] = b;
+ imageData[offset + 3] = a;
+ }
+ }
+ }
+ }
+
+ private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
+ {
+ int temp;
+
+ temp = (color >> 11) * 255 + 16;
+ r = (byte)((temp / 32 + temp) / 32);
+ temp = ((color & 0x07E0) >> 5) * 255 + 32;
+ g = (byte)((temp / 64 + temp) / 64);
+ temp = (color & 0x001F) * 255 + 16;
+ b = (byte)((temp / 32 + temp) / 32);
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs
new file mode 100644
index 0000000..e125f87
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudController.cs
@@ -0,0 +1,480 @@
+// HudController.cs — Owner of RynthAi's floating HUD windows.
+//
+// * Pack item count HUD (ItemCountHud): icon + carried count for pinned items.
+// * Mini Remote (MiniRemoteHud): session stats, attack target, summon (health / time
+// left, fed by CombatHudTracker), 30 quick-use item slots, macro toggles, bank balances
+// and rebuff buttons.
+// * Inventory HUDs setup window (HudSetupUi): picks what the two HUDs show. Opened from
+// the Inventory Management settings (ImGui Advanced Settings, the Avalonia Settings
+// panel) or "/ra huds".
+// Every HUD is an ordinary ImGui window, so it can be docked into / undocked from other
+// ImGui windows and dragged outside the game window (multi-viewport).
+//
+// Threading: host reads and every game action run on the pump thread (Tick / posted
+// actions). The render thread only reads the published pack snapshot and toggles simple
+// flags; list edits are posted so the pump thread is the only writer.
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi.IltHub;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+/// One carried item name, aggregated over every stack in the pack.
+internal sealed record HudPackRow(string Name, uint Wcid, uint IconDid, long Count, int FirstId);
+
+/// Immutable pack view published by the pump thread.
+internal sealed class HudPackSnapshot
+{
+ public static readonly HudPackSnapshot Empty = new(Array.Empty());
+
+ public HudPackRow[] Rows { get; }
+ public Dictionary ByName { get; }
+
+ public HudPackSnapshot(HudPackRow[] rows)
+ {
+ Rows = rows;
+ ByName = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var r in rows) ByName[r.Name] = r;
+ }
+
+ public long CountOf(string name) => ByName.TryGetValue(name, out var r) ? r.Count : 0;
+}
+
+internal sealed class HudController
+{
+ private const uint StypeIcon = 8; // DataID Icon → PWD _iconID
+ private const int StypeStackSize = 12;
+ private const long PackScanIntervalMs = 1000;
+ private const long SaveIntervalMs = 5000;
+
+ private readonly RynthCoreHost _host;
+ private readonly Func _cache;
+ private readonly HudStore _store;
+ private readonly ConcurrentQueue _posted = new();
+ private readonly Dictionary _iconById = new();
+ private readonly ItemCountHud _itemHud;
+ private readonly MiniRemoteHud _miniRemote;
+ private readonly HudSetupUi _setup;
+ private readonly CombatHudTracker _combat;
+
+ private volatile HudPackSnapshot _pack = HudPackSnapshot.Empty;
+ private long _lastScanAt;
+ private long _lastSaveAt;
+ private bool _scanRequested;
+
+ ///
+ /// How long a pack item the player selected stays assignable after the game selection moves
+ /// on (the combat bot re-selects monsters, so "the selected item" is often gone by the time
+ /// the player clicks a slot).
+ ///
+ private const long RememberSelectionMs = 120_000;
+ private uint _lastSeenSelection;
+ private int _lastPackSelId;
+ private long _lastPackSelAt;
+ private volatile string _assignCandidate = string.Empty;
+
+ public HudController(RynthCoreHost host, string charFolder, Func cache,
+ LegacyDashboardRenderer dashboard, Func hub, HudIconCache icons, Func attackTargetId)
+ {
+ _host = host;
+ _cache = cache;
+ _store = new HudStore(charFolder);
+ State = _store.Load();
+ Icons = icons;
+ Dashboard = dashboard;
+ Hub = hub;
+ _itemHud = new ItemCountHud(this);
+ _miniRemote = new MiniRemoteHud(this);
+ _setup = new HudSetupUi(this);
+ _combat = new CombatHudTracker(host, cache, attackTargetId);
+ }
+
+ public HudState State { get; }
+ public HudIconCache Icons { get; }
+ public LegacyDashboardRenderer Dashboard { get; }
+ public Func Hub { get; }
+ public RynthCoreHost Host => _host;
+
+ /// Latest pack view (render thread safe).
+ public HudPackSnapshot Pack => _pack;
+
+ /// Latest attack target / summon view (render thread safe).
+ public CombatHudSnapshot Combat => _combat.Snapshot;
+
+ ///
+ /// Name of the pack item a slot click would assign (current or remembered selection); empty
+ /// when there is none. Render thread safe.
+ ///
+ public string AssignCandidate => _assignCandidate;
+
+ /// Chat translator views for the Mini Remote row; null until the translator exists.
+ public RynthCore.Plugin.RynthAi.Translate.TranslateUi? Translate { get; set; }
+
+ /// Queues work for the next pump tick (safe from the render thread).
+ public void Post(Action action) => _posted.Enqueue(action);
+
+ private static long NowMs => Environment.TickCount64;
+
+ // ── Pump thread ─────────────────────────────────────────────────────────
+
+ public void Tick()
+ {
+ int guard = 0;
+ while (guard++ < 64 && _posted.TryDequeue(out var a))
+ {
+ try { a(); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "posted HUD action"); }
+ }
+
+ long now = NowMs;
+ // The pack is only scanned while something shows it.
+ bool needPack = State.ShowItemHud || State.ShowMiniRemote || State.ShowSetup;
+ if (needPack && (_scanRequested || now - _lastScanAt >= PackScanIntervalMs))
+ {
+ _scanRequested = false;
+ _lastScanAt = now;
+ RebuildPack();
+ }
+
+ Icons.Tick();
+ if (State.ShowMiniRemote || State.ShowSetup || State.ShowItemHud) TrackPackSelection(now);
+
+ // Target / summon polling sends health queries and appraisals, so it only runs while shown.
+ if (State.ShowMiniRemote && (State.MiniShowTarget || State.MiniShowPet))
+ _combat.Tick();
+
+ if (now - _lastSaveAt >= SaveIntervalMs)
+ {
+ _lastSaveAt = now;
+ _store.SaveIfDirty(State);
+ }
+ }
+
+ public void OnLogout()
+ {
+ _store.SaveIfDirty(State);
+ _pack = HudPackSnapshot.Empty;
+ _iconById.Clear();
+ _combat.OnLogout();
+ }
+
+ /// Aggregates the pack by item name and refreshes pinned entries' icon / WCID.
+ private void RebuildPack()
+ {
+ var cache = _cache();
+ if (cache == null) return;
+
+ var byName = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ var seen = new HashSet();
+ foreach (var wo in cache.GetInventory())
+ {
+ if (wo == null || string.IsNullOrWhiteSpace(wo.Name)) continue;
+ seen.Add(wo.Id);
+ long count = Math.Max(1, wo.Values(StypeStackSize, 1));
+ if (byName.TryGetValue(wo.Name, out var row))
+ {
+ byName[wo.Name] = row with { Count = row.Count + count };
+ continue;
+ }
+ byName[wo.Name] = new HudPackRow(wo.Name, Wcid(wo), IconOf(wo), count, wo.Id);
+ }
+
+ // Forget icon lookups for items that left the pack.
+ if (_iconById.Count > seen.Count + 64)
+ foreach (int id in _iconById.Keys.Where(k => !seen.Contains(k)).ToList()) _iconById.Remove(id);
+
+ var snap = new HudPackSnapshot(byName.Values.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray());
+ _pack = snap;
+
+ // Remember icon / WCID on pinned entries so they still draw while none are carried.
+ foreach (var e in State.ItemHudItems.Concat(State.MiniRemoteSlots))
+ {
+ if (e.IsEmpty || !snap.ByName.TryGetValue(e.Name, out var r)) continue;
+ if (r.IconDid != 0) e.IconDid = r.IconDid;
+ if (r.Wcid != 0) e.Wcid = r.Wcid;
+ }
+ }
+
+ private uint IconOf(WorldObject wo)
+ {
+ if (_iconById.TryGetValue(wo.Id, out uint icon) && icon != 0) return icon;
+ if (_host.HasGetObjectDataIdProperty && _host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), StypeIcon, out icon))
+ _iconById[wo.Id] = icon;
+ return icon;
+ }
+
+ private uint Wcid(WorldObject wo)
+ => _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint w) ? w : 0;
+
+ // ── Actions (pump thread; post them from the render thread) ──────────────
+
+ /// Rescans the pack on the next tick.
+ public void RequestScan() => _scanRequested = true;
+
+ /// Uses one carried item by name (falls back to WCID when the name changed).
+ public void UseItem(HudItemEntry entry)
+ {
+ if (entry.IsEmpty) return;
+ var cache = _cache();
+ if (cache == null || !_host.HasUseObject) return;
+ var inv = cache.GetInventory().Where(w => w != null).ToList();
+ var wo = inv.FirstOrDefault(w => w.Name.Equals(entry.Name, StringComparison.OrdinalIgnoreCase))
+ ?? (entry.Wcid != 0 ? inv.FirstOrDefault(w => Wcid(w) == entry.Wcid) : null);
+ if (wo == null) { Chat($"[RynthAi] No {entry.Name} in your pack."); return; }
+ _host.UseObject(unchecked((uint)wo.Id));
+ RynthLog.Trace(LogCat.Huds, $"use {wo.Name} (0x{wo.Id:X8})");
+ }
+
+ /// Carried item by object id, or null.
+ private WorldObject? PackItem(int id)
+ => id == 0 ? null : _cache()?.GetInventory().FirstOrDefault(w => w != null && w.Id == id);
+
+ ///
+ /// Remembers the last pack item selected in the game (native inventory, or the RynthCore
+ /// Inventory window, which mirrors its clicks to the game selection). Only re-checks the
+ /// pack when the selection changes.
+ ///
+ private void TrackPackSelection(long now)
+ {
+ if (!_host.HasGetSelectedItemId) return;
+ uint sel = _host.GetSelectedItemId();
+ if (sel != _lastSeenSelection)
+ {
+ _lastSeenSelection = sel;
+ var wo = PackItem(unchecked((int)sel));
+ if (wo != null)
+ {
+ _lastPackSelId = wo.Id;
+ _lastPackSelAt = now;
+ }
+ }
+ // The candidate label only feeds tooltips / menus: refresh it a few times a second.
+ if (now - _lastCandidateAt < 250) return;
+ _lastCandidateAt = now;
+ var candidate = AssignablePackItem(quiet: true);
+ _assignCandidate = candidate?.Name ?? string.Empty;
+ }
+ private long _lastCandidateAt;
+
+ ///
+ /// The pack item to assign: the current game selection when it is carried, otherwise the
+ /// last carried item the player selected within .
+ ///
+ private WorldObject? AssignablePackItem(bool quiet = false)
+ {
+ if (!_host.HasGetSelectedItemId)
+ {
+ if (!quiet) Chat("[RynthAi] This client build can't read the selected item.");
+ return null;
+ }
+ uint selected = _host.GetSelectedItemId();
+ var wo = PackItem(unchecked((int)selected));
+ bool fellBack = false;
+ long rememberedAge = NowMs - _lastPackSelAt;
+ if (wo == null && _lastPackSelId != 0 && rememberedAge <= RememberSelectionMs)
+ {
+ wo = PackItem(_lastPackSelId);
+ fellBack = wo != null;
+ }
+ // Quiet calls feed tooltips several times a second: only real assignments are traced.
+ if (!quiet)
+ {
+ string selInfo = selected == 0 ? "none" : $"0x{selected:X8} ({(fellBack || wo == null ? DescribeCacheEntry(unchecked((int)selected)) : "in inventory")})";
+ string result = wo == null ? "nothing to assign"
+ : fellBack ? $"fell back to remembered 0x{_lastPackSelId:X8} '{wo.Name}' ({rememberedAge / 1000.0:0.0} s old)"
+ : $"selected '{wo.Name}'";
+ RynthLog.Trace(LogCat.Huds, $"assign candidate: selected={selInfo}; {result}");
+ }
+ if (wo == null && !quiet)
+ Chat("[RynthAi] Click an item in your pack (game inventory or RynthCore Inventory) first, "
+ + "or drag it from the RynthCore Inventory onto the slot.");
+ return wo;
+ }
+
+ /// The item to act on for "use the selected item" HUD actions.
+ private WorldObject? SelectedPackItem() => AssignablePackItem();
+
+ public void AddSelectedToItemHud()
+ {
+ var wo = SelectedPackItem();
+ if (wo != null) AddToItemHud(wo.Name);
+ }
+
+ public void AddToItemHud(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name) || State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) return;
+ var row = _pack.ByName.TryGetValue(name, out var r) ? r : null;
+ State.ItemHudItems.Add(new HudItemEntry { Name = name, Wcid = row?.Wcid ?? 0, IconDid = row?.IconDid ?? 0 });
+ RynthLog.Trace(LogCat.Huds, $"item HUD += '{name}' (first id 0x{(uint)(row?.FirstId ?? 0):X8}, wcid {row?.Wcid ?? 0}, in pack scan: {(row != null ? "yes" : "no")})");
+ }
+
+ ///
+ /// Adds to the item count HUD (if missing) and shows the HUD.
+ /// Icon and WCID fill in on the next pack scan. Returns the chat confirmation.
+ ///
+ public string AddToItemHudAndShow(string name)
+ {
+ name = name.Trim();
+ bool already = State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ if (!already) AddToItemHud(name);
+ State.ShowItemHud = true;
+ RequestScan();
+ return already ? $"{name} is already on the item count HUD." : $"Added {name} to the item count HUD.";
+ }
+
+ public void RemoveFromItemHud(string name)
+ => State.ItemHudItems.RemoveAll(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+
+ /// Moves a HUD entry up (-1) or down (+1) in display order.
+ public void MoveItemHudEntry(string name, int delta)
+ {
+ var list = State.ItemHudItems;
+ int i = list.FindIndex(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ int j = i + delta;
+ if (i < 0 || j < 0 || j >= list.Count) return;
+ (list[i], list[j]) = (list[j], list[i]);
+ }
+
+ /// Removes HUD entries for items no longer carried.
+ public void DropMissingFromItemHud()
+ {
+ var pack = _pack;
+ int n = State.ItemHudItems.RemoveAll(e => pack.CountOf(e.Name) == 0);
+ Chat(n > 0 ? $"[RynthAi] Removed {n} item(s) you no longer carry from the HUD." : "[RynthAi] Every HUD item is still in your pack.");
+ }
+
+ /// Puts the selected (or last selected) pack item into Mini Remote slot .
+ public void SetSlotFromSelection(int slot)
+ {
+ if (slot < 0 || slot >= State.MiniRemoteSlots.Count) return;
+ var wo = AssignablePackItem();
+ if (wo != null) AssignSlot(slot, wo);
+ }
+
+ ///
+ /// Puts carried item into (-1 = first empty
+ /// slot). Used by drag-and-drop from the RynthCore Inventory and its "Add to Mini Remote" menu.
+ ///
+ public void SetSlotFromItemId(int slot, uint objectId)
+ {
+ var wo = PackItem(unchecked((int)objectId));
+ if (wo == null)
+ {
+ // The cache's view of the id shows a classification miss (item filed outside inventory).
+ int invCount = _cache()?.GetInventory().Count() ?? -1;
+ RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} not in inventory ({invCount} items); {DescribeCacheEntry(unchecked((int)objectId))}");
+ Chat("[RynthAi] That item is no longer in your pack.");
+ return;
+ }
+ RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} = '{wo.Name}' ({wo.ObjectClass}), requested slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}");
+ if (slot < 0) slot = State.MiniRemoteSlots.FindIndex(e => e.IsEmpty);
+ if (slot < 0) { Chat("[RynthAi] Every Mini Remote slot is in use. Clear one first (right-click it)."); return; }
+ if (slot >= State.MiniRemoteSlots.Count) return;
+ AssignSlot(slot, wo);
+ }
+
+ private void AssignSlot(int slot, WorldObject wo)
+ {
+ var row = _pack.ByName.TryGetValue(wo.Name, out var r) ? r : null;
+ var entry = new HudItemEntry { Name = wo.Name, Wcid = row?.Wcid ?? Wcid(wo), IconDid = row?.IconDid ?? IconOf(wo) };
+ State.MiniRemoteSlots[slot] = entry;
+ RynthLog.Trace(LogCat.Huds, $"assign slot {slot + 1:00} = '{wo.Name}' 0x{(uint)wo.Id:X8} (wcid {entry.Wcid}, icon 0x{entry.IconDid:X8})");
+ Chat($"[RynthAi] Mini Remote slot {slot + 1:00} = {wo.Name}.");
+ }
+
+ /// How the world cache knows (for traces): name and class, or that it doesn't.
+ private string DescribeCacheEntry(int id)
+ {
+ var cache = _cache();
+ if (cache == null) return "no world cache";
+ var wo = cache[id];
+ return wo == null ? "unknown to the world cache" : $"world cache has '{wo.Name}' as {wo.ObjectClass}";
+ }
+
+ ///
+ /// Remote command "remoteslot <slot|first> <objectId>" (RynthCore Inventory menu).
+ /// Slot is 1-based. Returns false when the value can't be parsed.
+ ///
+ public bool HandleRemoteSlot(string value)
+ {
+ var parts = (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ int slot = 0;
+ bool ok = parts.Length == 2 && uint.TryParse(parts[1], out _);
+ if (ok)
+ {
+ if (parts[0].Equals("first", StringComparison.OrdinalIgnoreCase)) slot = -1;
+ else if (int.TryParse(parts[0], out int n) && n >= 1) slot = n - 1;
+ else ok = false;
+ }
+ if (!ok)
+ {
+ RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': can't parse (expected ' ')");
+ return false;
+ }
+ uint id = uint.Parse(parts[1]);
+ RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}, id 0x{id:X8}");
+ SetSlotFromItemId(slot, id);
+ return true;
+ }
+
+ public void ClearSlot(int slot)
+ {
+ if (slot >= 0 && slot < State.MiniRemoteSlots.Count) State.MiniRemoteSlots[slot] = new HudItemEntry();
+ }
+
+ public void Chat(string text)
+ {
+ // Every message the player sees also lands in the Huds trace.
+ RynthLog.Trace(LogCat.Huds, "chat: " + text);
+ if (_host.HasWriteToChat) _host.WriteToChat(text, 1);
+ }
+
+ ///
+ /// "/ra huds|itemhud|remote [show|hide|toggle]" and the matching remote command.
+ /// Returns the chat confirmation.
+ ///
+ public string HandleCommand(string which, string mode)
+ {
+ static bool Resolve(string m, bool current) => m.ToLowerInvariant() switch
+ {
+ "show" or "on" or "true" or "1" => true,
+ "hide" or "off" or "false" or "0" => false,
+ _ => !current,
+ };
+
+ switch (which)
+ {
+ case "itemhud":
+ State.ShowItemHud = Resolve(mode, State.ShowItemHud);
+ return State.ShowItemHud ? "Pack item count HUD shown." : "Pack item count HUD hidden.";
+ case "remote":
+ case "miniremote":
+ State.ShowMiniRemote = Resolve(mode, State.ShowMiniRemote);
+ return State.ShowMiniRemote ? "Mini Remote shown." : "Mini Remote hidden.";
+ default:
+ State.ShowSetup = Resolve(mode, State.ShowSetup);
+ return State.ShowSetup ? "Inventory HUDs window shown." : "Inventory HUDs window hidden.";
+ }
+ }
+
+ // ── Render thread ───────────────────────────────────────────────────────
+
+ public void Render()
+ {
+ int pushed = LegacyDashboardRenderer.PushDashboardStyle();
+ try
+ {
+ if (State.ShowSetup) _setup.Render();
+ if (State.ShowItemHud) _itemHud.Render(); else _itemHud.OnHidden();
+ if (State.ShowMiniRemote) _miniRemote.Render(); else _miniRemote.OnHidden();
+ }
+ finally
+ {
+ ImGuiNET.ImGui.PopStyleColor(pushed);
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudDraw.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudDraw.cs
new file mode 100644
index 0000000..4f5cd3a
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudDraw.cs
@@ -0,0 +1,56 @@
+// HudDraw.cs — Small ImGui drawing helpers shared by the HUD windows (render thread only).
+using System;
+using System.Numerics;
+using ImGuiNET;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+internal static class HudDraw
+{
+ private static readonly Vector4 Opaque = new(1f, 1f, 1f, 1f);
+ private static readonly Vector4 Faded = new(1f, 1f, 1f, 0.35f);
+ private static readonly Vector4 NoBorder = Vector4.Zero;
+
+ ///
+ /// Draws an item icon of pixels. While the texture is still
+ /// loading (or the item has no icon) a framed box with the name's first letter stands in.
+ /// fades it (e.g. none carried).
+ ///
+ public static void Icon(HudIconCache icons, uint iconDid, string name, float size, bool dim)
+ {
+ IntPtr tex = icons.GetTexture(iconDid);
+ var sz = new Vector2(size, size);
+ if (tex != IntPtr.Zero)
+ {
+ ImGui.Image(tex, sz, Vector2.Zero, Vector2.One, dim ? Faded : Opaque, NoBorder);
+ return;
+ }
+ Placeholder(name, sz, dim);
+ }
+
+ /// Framed stand-in with the item's first letter, same footprint as an icon.
+ public static void Placeholder(string name, Vector2 size, bool dim)
+ {
+ Vector2 p = ImGui.GetCursorScreenPos();
+ ImGui.Dummy(size);
+ var dl = ImGui.GetWindowDrawList();
+ uint frame = ImGui.GetColorU32(new Vector4(0.45f, 0.55f, 0.65f, dim ? 0.35f : 0.8f));
+ uint fill = ImGui.GetColorU32(new Vector4(0.12f, 0.16f, 0.22f, dim ? 0.35f : 0.8f));
+ dl.AddRectFilled(p, p + size, fill, 3f);
+ dl.AddRect(p, p + size, frame, 3f);
+ if (string.IsNullOrEmpty(name)) return;
+ string letter = name.Substring(0, 1).ToUpperInvariant();
+ Vector2 ts = ImGui.CalcTextSize(letter);
+ dl.AddText(p + (size - ts) * 0.5f, ImGui.GetColorU32(new Vector4(0.9f, 0.9f, 0.9f, dim ? 0.4f : 1f)), letter);
+ }
+
+ /// "1468", "12.3k", "4.5m", "1.2b" — compact counts for tight HUD rows.
+ public static string Compact(double v)
+ {
+ double a = Math.Abs(v);
+ if (a >= 1e9) return (v / 1e9).ToString("0.0") + "b";
+ if (a >= 1e6) return (v / 1e6).ToString("0.0") + "m";
+ if (a >= 1e4) return (v / 1e3).ToString("0.0") + "k";
+ return v.ToString("0");
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudIconCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudIconCache.cs
new file mode 100644
index 0000000..0035700
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudIconCache.cs
@@ -0,0 +1,266 @@
+// HudIconCache.cs — Item icons for the RynthAi HUD windows.
+//
+// An item's icon DID (PWD _iconID, 0x06xxxxxx) points at a Texture file in portal.dat.
+// Decoding (dat read + pixel conversion) runs on the pump thread; the D3D9 texture is
+// created lazily on the render thread, a few per frame, so a full pack never stalls a frame.
+// Textures are POOL_MANAGED (they survive device resets) and are never released: plugin
+// unload can run off the render thread, where touching the device is unsafe, and the
+// whole set is a few hundred 32×32 icons.
+using System;
+using System.Collections.Concurrent;
+using System.IO;
+using System.Runtime.InteropServices;
+using RynthCore.Plugin.RynthAi.Raycasting;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+internal sealed class HudIconCache
+{
+ // IDirect3DDevice9 / IDirect3DTexture9 vtable slots.
+ private const int VtCreateTexture = 23;
+ private const int VtLockRect = 19;
+ private const int VtUnlockRect = 20;
+ private const int VtRelease = 2;
+ private const uint D3DFMT_A8R8G8B8 = 21;
+ private const uint D3DPOOL_MANAGED = 1;
+
+ /// Texture uploads allowed per rendered frame.
+ private const int UploadsPerFrame = 6;
+ /// Icons decoded per pump tick.
+ private const int DecodesPerTick = 12;
+ /// Runaway guard; a full character's icons are a few hundred.
+ private const int MaxIcons = 4000;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr tex, IntPtr shared);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr rect, uint flags);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ private delegate int UnlockRectD(IntPtr tex, uint level);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ private delegate uint ReleaseD(IntPtr obj);
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct D3DLockedRect { public int Pitch; public IntPtr Bits; }
+
+ /// Decoded icon in D3D A8R8G8B8 order (A<<24 | R<<16 | G<<8 | B).
+ private sealed class Decoded
+ {
+ public int Width;
+ public int Height;
+ public uint[] Pixels = Array.Empty();
+ }
+
+ private readonly RynthCoreHost _host;
+ private readonly Func _portal;
+
+ // DID → decoded pixels (null value = decode failed, don't retry).
+ private readonly ConcurrentDictionary _decoded = new();
+ // DIDs the render thread asked for that the pump thread hasn't decoded yet.
+ private readonly ConcurrentQueue _pending = new();
+ private readonly ConcurrentDictionary _queued = new();
+
+ // Render thread only.
+ private readonly System.Collections.Generic.Dictionary _textures = new();
+ private IntPtr _textureDevice;
+ private int _uploadFrame = -1;
+ private int _uploadsThisFrame;
+
+ public HudIconCache(RynthCoreHost host, Func portal)
+ {
+ _host = host;
+ _portal = portal;
+ }
+
+ // ── Render thread ───────────────────────────────────────────────────────
+
+ ///
+ /// ImGui texture id for , or IntPtr.Zero while it is still
+ /// being decoded / uploaded (callers draw a placeholder).
+ ///
+ public IntPtr GetTexture(uint iconDid)
+ {
+ if (iconDid == 0) return IntPtr.Zero;
+ IntPtr device = _host.D3DDevice;
+ if (device == IntPtr.Zero) return IntPtr.Zero;
+
+ // A new device means the old textures belong to a dead device; forget them (not
+ // Release — the owning device may already be gone).
+ if (device != _textureDevice)
+ {
+ _textures.Clear();
+ _textureDevice = device;
+ }
+
+ if (_textures.TryGetValue(iconDid, out IntPtr tex)) return tex;
+
+ if (!_decoded.TryGetValue(iconDid, out Decoded? d))
+ {
+ if (_queued.TryAdd(iconDid, 0)) _pending.Enqueue(iconDid);
+ return IntPtr.Zero;
+ }
+ if (d == null) return IntPtr.Zero;
+
+ int frame = ImGuiNET.ImGui.GetFrameCount();
+ if (frame != _uploadFrame) { _uploadFrame = frame; _uploadsThisFrame = 0; }
+ if (_uploadsThisFrame >= UploadsPerFrame) return IntPtr.Zero;
+ _uploadsThisFrame++;
+
+ tex = Upload(device, d);
+ // Failed uploads are remembered as Zero so they aren't retried every frame.
+ _textures[iconDid] = tex;
+ return tex;
+ }
+
+ // ── Pump thread ─────────────────────────────────────────────────────────
+
+ /// Decodes a batch of requested icons (dat reads stay off the render thread).
+ public void Tick()
+ {
+ var portal = _portal();
+ if (portal == null || !portal.IsLoaded) return;
+ for (int i = 0; i < DecodesPerTick && _pending.TryDequeue(out uint did); i++)
+ {
+ _queued.TryRemove(did, out _);
+ if (_decoded.Count >= MaxIcons) { _decoded.TryAdd(did, null); continue; }
+ Decoded? d = null;
+ try { d = Decode(portal, did); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"icon decode 0x{did:X8}"); }
+ _decoded[did] = d;
+ }
+ }
+
+ // ── Decoding (Texture 0x06 → ARGB) ──────────────────────────────────────
+
+ // Texture layout: Id(u32) Unknown(i32) Width(i32) Height(i32) Format(u32) Length(i32)
+ // Source[Length], then DefaultPaletteId(u32) for INDEX16 / P8.
+ private static Decoded? Decode(DatDatabase portal, uint textureId)
+ {
+ byte[]? data = portal.GetFileData(textureId);
+ if (data == null || data.Length < 24) return null;
+ using var ms = new MemoryStream(data);
+ using var r = new BinaryReader(ms);
+ r.ReadUInt32(); r.ReadInt32();
+ int w = r.ReadInt32(), h = r.ReadInt32();
+ uint fmt = r.ReadUInt32();
+ int len = r.ReadInt32();
+ if (w <= 0 || h <= 0 || w > 1024 || h > 1024 || len < 0 || ms.Position + len > ms.Length) return null;
+ byte[] src = r.ReadBytes(len);
+ uint palId = 0;
+ if ((fmt == 101 || fmt == 41) && ms.Position + 4 <= ms.Length) palId = r.ReadUInt32();
+
+ var px = new uint[w * h];
+ static uint Argb(int a, int rr, int g, int b) => ((uint)a << 24) | ((uint)rr << 16) | ((uint)g << 8) | (uint)b;
+
+ switch (fmt)
+ {
+ case 827611204: return FromRgba(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
+ case 861165636: return FromRgba(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
+ case 894720068: return FromRgba(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
+ case 20: // R8G8B8, stored B,G,R
+ for (int i = 0; i < px.Length && i * 3 + 2 < src.Length; i++) px[i] = Argb(255, src[i * 3 + 2], src[i * 3 + 1], src[i * 3]);
+ break;
+ case 21: // A8R8G8B8, stored B,G,R,A
+ case 22: // X8R8G8B8
+ for (int i = 0; i < px.Length && i * 4 + 3 < src.Length; i++)
+ px[i] = Argb(fmt == 22 ? 255 : src[i * 4 + 3], src[i * 4 + 2], src[i * 4 + 1], src[i * 4]);
+ break;
+ case 23: // R5G6B5
+ for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
+ {
+ int v = src[i * 2] | (src[i * 2 + 1] << 8);
+ px[i] = Argb(255, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3);
+ }
+ break;
+ case 26: // A4R4G4B4
+ for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
+ {
+ int v = src[i * 2] | (src[i * 2 + 1] << 8);
+ px[i] = Argb(((v >> 12) & 0xF) * 17, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17);
+ }
+ break;
+ case 28: // A8 greyscale
+ for (int i = 0; i < px.Length && i < src.Length; i++) px[i] = Argb(255, src[i], src[i], src[i]);
+ break;
+ case 101: // INDEX16
+ case 41: // P8
+ {
+ uint[]? pal = LoadPalette(portal, palId);
+ if (pal == null || pal.Length == 0) return null;
+ bool p8 = fmt == 41;
+ for (int i = 0; i < px.Length; i++)
+ {
+ int idx;
+ if (p8) { if (i >= src.Length) break; idx = src[i]; }
+ else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
+ px[i] = pal[idx % pal.Length]; // palette entries are already ARGB
+ }
+ break;
+ }
+ default:
+ return null;
+ }
+ return new Decoded { Width = w, Height = h, Pixels = px };
+ }
+
+ /// Palette (0x04): Id(u32), Count(i32), Count × ARGB(u32).
+ private static uint[]? LoadPalette(DatDatabase portal, uint paletteId)
+ {
+ byte[]? data = portal.GetFileData(paletteId);
+ if (data == null || data.Length < 8) return null;
+ int n = BitConverter.ToInt32(data, 4);
+ if (n <= 0 || n > 65536) return null;
+ n = Math.Min(n, (data.Length - 8) / 4);
+ var pal = new uint[n];
+ for (int i = 0; i < n; i++) pal[i] = BitConverter.ToUInt32(data, 8 + i * 4);
+ return pal;
+ }
+
+ /// DxtUtil output (R,G,B,A bytes) → ARGB.
+ private static Decoded FromRgba(byte[] rgba, int w, int h)
+ {
+ var px = new uint[w * h];
+ for (int i = 0; i < px.Length && i * 4 + 3 < rgba.Length; i++)
+ px[i] = ((uint)rgba[i * 4 + 3] << 24) | ((uint)rgba[i * 4] << 16) | ((uint)rgba[i * 4 + 1] << 8) | rgba[i * 4 + 2];
+ return new Decoded { Width = w, Height = h, Pixels = px };
+ }
+
+ // ── D3D9 upload (render thread) ─────────────────────────────────────────
+
+ private static unsafe IntPtr Upload(IntPtr device, Decoded d)
+ {
+ try
+ {
+ int hr = Vt(device, VtCreateTexture)(device, (uint)d.Width, (uint)d.Height, 1, 0,
+ D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
+ if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
+
+ var locked = new D3DLockedRect();
+ if (Vt(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0) < 0)
+ {
+ Vt(tex, VtRelease)(tex);
+ return IntPtr.Zero;
+ }
+ // Row by row: the locked pitch can be wider than Width * 4.
+ for (int row = 0; row < d.Height; row++)
+ {
+ fixed (uint* src = &d.Pixels[row * d.Width])
+ Buffer.MemoryCopy(src, (void*)IntPtr.Add(locked.Bits, row * locked.Pitch), d.Width * 4, d.Width * 4);
+ }
+ Vt(tex, VtUnlockRect)(tex, 0);
+ return tex;
+ }
+ catch (Exception ex)
+ {
+ RynthLog.Exception(LogCat.Huds, ex, "icon upload");
+ return IntPtr.Zero;
+ }
+ }
+
+ private static unsafe T Vt(IntPtr obj, int index) where T : Delegate
+ {
+ void** vt = *(void***)obj;
+ return Marshal.GetDelegateForFunctionPointer((IntPtr)vt[index]);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs
new file mode 100644
index 0000000..ff41ed1
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudSetupUi.cs
@@ -0,0 +1,183 @@
+// HudSetupUi.cs — "Inventory HUDs" setup window (UtilityBelt Item Hud tab equivalent).
+//
+// * Show / hide the pack item count HUD and the Mini Remote.
+// * Two lists: items on the HUD (left) and carried items not on it (right).
+// "<" pins the highlighted right row, ">" unpins the highlighted left row,
+// Up / Down reorder the HUD. "Add from inventory" pins the item selected in the game.
+// * Mini Remote slots: pick a slot, then Set (selected game item) or Clear.
+// Render thread only; list edits are posted to the pump thread.
+using System;
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+internal sealed class HudSetupUi
+{
+ private const float ListIcon = 18f;
+
+ private readonly HudController _hud;
+ private string _selOnHud = string.Empty;
+ private string _selInPack = string.Empty;
+ private string _packFilter = string.Empty;
+ private int _slot;
+
+ public HudSetupUi(HudController hud) => _hud = hud;
+
+ public void Render()
+ {
+ var s = _hud.State;
+ ImGui.SetNextWindowSize(new Vector2(640, 520), ImGuiCond.FirstUseEver);
+ bool open = true;
+ bool visible = ImGui.Begin("Inventory HUDs##rynthhudsetup", ref open);
+ if (!open) s.ShowSetup = false;
+ if (!visible) { ImGui.End(); return; }
+
+ RenderHudToggles(s);
+ ImGui.Separator();
+ RenderItemLists(s);
+ ImGui.Separator();
+ RenderSlotPicker(s);
+ ImGui.End();
+ }
+
+ private static void RenderHudToggles(HudState s)
+ {
+ bool itemHud = s.ShowItemHud;
+ if (ImGui.Checkbox("Show pack item count HUD", ref itemHud)) s.ShowItemHud = itemHud;
+ ImGui.SameLine();
+ bool names = s.ItemHudShowNames;
+ if (ImGui.Checkbox("with names", ref names)) s.ItemHudShowNames = names;
+ ImGui.SameLine();
+ bool remote = s.ShowMiniRemote;
+ if (ImGui.Checkbox("Show Mini Remote", ref remote)) s.ShowMiniRemote = remote;
+ ImGui.TextDisabled("Both are separate windows: drag them anywhere, dock them into other RynthAi windows,");
+ ImGui.TextDisabled("or pull them outside the game window. Right-click a HUD for its options.");
+ }
+
+ private void RenderItemLists(HudState s)
+ {
+ ImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
+ + "< pins the highlighted right row; > removes the highlighted left row. "
+ + "Add from inventory uses the item selected in the game.");
+
+ if (ImGui.Button("Scan pack")) _hud.Post(_hud.RequestScan);
+ ImGui.SameLine();
+ if (ImGui.Button("Add from inventory")) _hud.Post(_hud.AddSelectedToItemHud);
+ ImGui.SameLine();
+ if (ImGui.Button("Drop missing")) _hud.Post(_hud.DropMissingFromItemHud);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Remove HUD items you no longer carry.");
+
+ var entries = s.ItemHudItems.ToArray();
+ var pack = _hud.Pack;
+ float listH = 230f;
+ float colW = Math.Max(180f, (ImGui.GetContentRegionAvail().X - 50f) * 0.5f);
+
+ // ── Left: on the HUD ──
+ ImGui.BeginGroup();
+ ImGui.TextUnformatted($"On HUD ({entries.Length})");
+ if (ImGui.BeginChild("##hudon", new Vector2(colW, listH), ImGuiChildFlags.Borders))
+ {
+ foreach (var e in entries)
+ {
+ long count = pack.CountOf(e.Name);
+ if (Row(e.Name, e.IconDid, $"{e.Name} | {count:N0}", _selOnHud == e.Name, count == 0))
+ _selOnHud = e.Name;
+ }
+ }
+ ImGui.EndChild();
+ bool haveLeft = entries.Any(e => e.Name == _selOnHud);
+ ImGui.BeginDisabled(!haveLeft);
+ string upName = _selOnHud;
+ if (ImGui.SmallButton("Up")) _hud.Post(() => _hud.MoveItemHudEntry(upName, -1));
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Down")) _hud.Post(() => _hud.MoveItemHudEntry(upName, +1));
+ ImGui.EndDisabled();
+ ImGui.EndGroup();
+
+ // ── Middle: move buttons ──
+ ImGui.SameLine();
+ ImGui.BeginGroup();
+ ImGui.Dummy(new Vector2(1, listH * 0.35f));
+ ImGui.BeginDisabled(string.IsNullOrEmpty(_selInPack));
+ string add = _selInPack;
+ if (ImGui.Button("<", new Vector2(36, 0))) { _hud.Post(() => _hud.AddToItemHud(add)); _selInPack = string.Empty; }
+ ImGui.EndDisabled();
+ ImGui.BeginDisabled(!haveLeft);
+ string remove = _selOnHud;
+ if (ImGui.Button(">", new Vector2(36, 0))) { _hud.Post(() => _hud.RemoveFromItemHud(remove)); _selOnHud = string.Empty; }
+ ImGui.EndDisabled();
+ ImGui.EndGroup();
+
+ // ── Right: in pack, not on the HUD ──
+ ImGui.SameLine();
+ ImGui.BeginGroup();
+ ImGui.TextUnformatted("Not on HUD");
+ ImGui.SameLine();
+ ImGui.SetNextItemWidth(Math.Max(80f, colW - 90f));
+ ImGui.InputTextWithHint("##hudpackfilter", "filter", ref _packFilter, 64u);
+ if (ImGui.BeginChild("##hudoff", new Vector2(colW, listH), ImGuiChildFlags.Borders))
+ {
+ var pinned = entries.Select(e => e.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var r in pack.Rows)
+ {
+ if (pinned.Contains(r.Name)) continue;
+ if (_packFilter.Length > 0 && !r.Name.Contains(_packFilter, StringComparison.OrdinalIgnoreCase)) continue;
+ if (Row(r.Name, r.IconDid, $"{r.Name} | {r.Count:N0}", _selInPack == r.Name, false))
+ _selInPack = r.Name;
+ // Double-click pins straight away.
+ if (ImGui.IsItemHovered() && ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
+ {
+ string name = r.Name;
+ _hud.Post(() => _hud.AddToItemHud(name));
+ }
+ }
+ if (pack.Rows.Length == 0) ImGui.TextDisabled("Scanning your pack...");
+ }
+ ImGui.EndChild();
+ ImGui.EndGroup();
+ }
+
+ /// Icon + label selectable row; returns true when clicked.
+ private bool Row(string name, uint iconDid, string label, bool selected, bool dim)
+ {
+ Vector2 start = ImGui.GetCursorPos();
+ bool clicked = ImGui.Selectable($"##row{name}", selected, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, ListIcon));
+ ImGui.SetCursorPos(start);
+ HudDraw.Icon(_hud.Icons, iconDid, name, ListIcon, dim);
+ ImGui.SameLine();
+ if (dim) ImGui.TextDisabled(label);
+ else ImGui.TextUnformatted(label);
+ return clicked;
+ }
+
+ private void RenderSlotPicker(HudState s)
+ {
+ var slots = s.MiniRemoteSlots.ToArray();
+ if (slots.Length == 0) return;
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Mini Remote slots");
+ ImGui.TextDisabled($"Slot 01 = top-left of the Mini Remote grid ({HudState.MiniRemoteColumns} per row). "
+ + "Select an item in your pack, pick the slot, then Set.");
+ _slot = Math.Clamp(_slot, 0, slots.Length - 1);
+ string Label(int i) => $"{i + 1:00} - {(slots[i].IsEmpty ? "(empty)" : slots[i].Name)}";
+
+ ImGui.SetNextItemWidth(320);
+ if (ImGui.BeginCombo("##mrslot", Label(_slot)))
+ {
+ for (int i = 0; i < slots.Length; i++)
+ if (ImGui.Selectable(Label(i), i == _slot)) _slot = i;
+ ImGui.EndCombo();
+ }
+ int slot = _slot;
+ ImGui.SameLine();
+ if (ImGui.Button("Set")) _hud.Post(() => _hud.SetSlotFromSelection(slot));
+ ImGui.SameLine();
+ ImGui.BeginDisabled(slots[slot].IsEmpty);
+ if (ImGui.Button("Clear")) _hud.Post(() => _hud.ClearSlot(slot));
+ ImGui.EndDisabled();
+ ImGui.SameLine();
+ if (ImGui.Button("Refresh")) _hud.Post(_hud.RequestScan);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs
new file mode 100644
index 0000000..de59819
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs
@@ -0,0 +1,119 @@
+// HudState.cs — Persisted per-character settings for the floating HUD windows
+// (\huds.json). Fields, not properties, so the source-generated
+// RynthAiJsonContext (IncludeFields) round-trips them under NativeAOT.
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+public sealed class HudState
+{
+ /// Mini Remote gem grid size (UB layout: 5 columns × 6 rows).
+ public const int MiniRemoteColumns = 5;
+ public const int MiniRemoteSlotCount = 30;
+
+ /// The "Inventory HUDs" setup window is open.
+ public bool ShowSetup;
+
+ // ── Pack item count HUD ──
+ public bool ShowItemHud;
+ public bool ItemHudShowNames;
+ public bool ItemHudLocked;
+ public float ItemHudIconSize = 20f;
+ /// Items shown on the HUD, in display order (matched by name).
+ public List ItemHudItems = new();
+
+ // ── Mini Remote ──
+ public bool ShowMiniRemote;
+ public bool MiniRemoteLocked;
+ /// Sections laid out side by side in columns (the V/H button) instead of stacked.
+ public bool MiniRemoteHorizontal;
+ public bool MiniShowStats = true;
+ /// Attack target row: name, health bar, distance.
+ public bool MiniShowTarget = true;
+ /// Pet row: the summon that is out (health, time left), else the next combat essence.
+ public bool MiniShowPet = true;
+ public bool MiniShowGems = true;
+ public bool MiniShowToggles = true;
+ public bool MiniShowBank = true;
+ public bool MiniShowRebuff = true;
+ /// Chat translator row: on/off, receive / send language swap.
+ public bool MiniShowTranslate = true;
+ /// Temple guardian row: the last riddle answer with a Give button (only while one is recent).
+ public bool MiniShowGuardian = true;
+ /// Gem grid slots, row-major from the top-left (empty Name = unassigned).
+ public List MiniRemoteSlots = new();
+}
+
+/// An item pinned to a HUD. Matched by name; Wcid / IconDid are remembered so the
+/// entry still shows its icon while none are carried.
+public sealed class HudItemEntry
+{
+ public string Name = string.Empty;
+ public uint Wcid;
+ public uint IconDid;
+
+ [JsonIgnore] public bool IsEmpty => string.IsNullOrWhiteSpace(Name);
+}
+
+/// Loads / dirty-checked saves of .
+internal sealed class HudStore
+{
+ private readonly string _charFolder;
+ private string _lastJson = string.Empty;
+
+ public HudStore(string charFolder) => _charFolder = charFolder ?? string.Empty;
+
+ private string StatePath => Path.Combine(_charFolder, "huds.json");
+
+ public HudState Load()
+ {
+ HudState? s = null;
+ try
+ {
+ if (_charFolder.Length > 0 && File.Exists(StatePath))
+ {
+ string json = File.ReadAllText(StatePath);
+ s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.HudState);
+ if (s != null) _lastJson = json;
+ }
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"load {StatePath}"); }
+ s ??= new HudState();
+ Normalize(s);
+ return s;
+ }
+
+ /// Writes the state only when its JSON differs from the last write.
+ public void SaveIfDirty(HudState state)
+ {
+ if (_charFolder.Length == 0) return;
+ try
+ {
+ string json = JsonSerializer.Serialize(state, RynthAiJsonContext.Default.HudState);
+ if (json == _lastJson) return;
+ Directory.CreateDirectory(_charFolder);
+ string tmp = StatePath + ".tmp";
+ File.WriteAllText(tmp, json);
+ File.Move(tmp, StatePath, overwrite: true);
+ _lastJson = json;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"save {StatePath}"); }
+ }
+
+ /// Repairs null lists / out-of-range values after deserialization.
+ private static void Normalize(HudState s)
+ {
+ s.ItemHudItems ??= new();
+ s.ItemHudItems.RemoveAll(e => e == null || e.IsEmpty);
+ s.ItemHudIconSize = Math.Clamp(s.ItemHudIconSize, 12f, 48f);
+ s.MiniRemoteSlots ??= new();
+ for (int i = 0; i < s.MiniRemoteSlots.Count; i++) s.MiniRemoteSlots[i] ??= new HudItemEntry();
+ while (s.MiniRemoteSlots.Count < HudState.MiniRemoteSlotCount) s.MiniRemoteSlots.Add(new HudItemEntry());
+ if (s.MiniRemoteSlots.Count > HudState.MiniRemoteSlotCount)
+ s.MiniRemoteSlots.RemoveRange(HudState.MiniRemoteSlotCount, s.MiniRemoteSlots.Count - HudState.MiniRemoteSlotCount);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs
new file mode 100644
index 0000000..7ae9702
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/ItemCountHud.cs
@@ -0,0 +1,89 @@
+// ItemCountHud.cs — Floating "pack item count" HUD: one row per pinned item with its
+// icon, carried count and (optionally) name. Right-click for options. Render thread only.
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+internal sealed class ItemCountHud
+{
+ private const string OptionsPopup = "##itemhudopts";
+ private static readonly Vector4 ColCount = new(0.95f, 0.95f, 0.95f, 1f);
+ private static readonly Vector4 ColNone = new(0.95f, 0.45f, 0.40f, 1f);
+ private static readonly Vector4 ColName = new(0.70f, 0.75f, 0.80f, 1f);
+
+ private readonly HudController _hud;
+ private bool _rescueChecked; // off-screen check done for the current show
+
+ public ItemCountHud(HudController hud) => _hud = hud;
+
+ /// The HUD was not drawn this frame: check its position again on the next show.
+ public void OnHidden() => _rescueChecked = false;
+
+ public void Render()
+ {
+ var s = _hud.State;
+ var entries = s.ItemHudItems.ToArray();
+ var pack = _hud.Pack;
+
+ var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar
+ | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav;
+ if (s.ItemHudLocked) flags |= ImGuiWindowFlags.NoMove;
+
+ // Right of and above centre, clear of the character in the middle of the view.
+ UiPlacement.CenterFirstUse(new Vector2(220, -160));
+ ImGui.SetNextWindowBgAlpha(0.55f);
+ ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
+ ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 2));
+ bool visible = ImGui.Begin("Item HUD##rynthitemhud", flags);
+ ImGui.PopStyleVar(2);
+ if (!visible) { ImGui.End(); return; }
+ UiPlacement.RescueOncePerShow(ref _rescueChecked);
+
+ if (entries.Length == 0)
+ {
+ ImGui.TextDisabled("Item HUD is empty.");
+ ImGui.TextDisabled("Right-click > Edit items...");
+ }
+
+ float size = s.ItemHudIconSize;
+ foreach (var e in entries)
+ {
+ long count = pack.CountOf(e.Name);
+ HudDraw.Icon(_hud.Icons, e.IconDid, e.Name, size, count == 0);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{e.Name}\n{count:N0} carried");
+ ImGui.SameLine();
+ // Vertically centre the text on the icon.
+ float pad = (size - ImGui.GetTextLineHeight()) * 0.5f;
+ if (pad > 0) ImGui.SetCursorPosY(ImGui.GetCursorPosY() + pad);
+ ImGui.TextColored(count == 0 ? ColNone : ColCount, count.ToString("N0"));
+ if (s.ItemHudShowNames)
+ {
+ ImGui.SameLine();
+ ImGui.TextColored(ColName, e.Name);
+ }
+ }
+
+ if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(OptionsPopup);
+ RenderOptions(s);
+ ImGui.End();
+ }
+
+ private void RenderOptions(HudState s)
+ {
+ if (!ImGui.BeginPopup(OptionsPopup)) return;
+ ImGui.TextDisabled("Item HUD");
+ bool names = s.ItemHudShowNames;
+ if (ImGui.Checkbox("Show names", ref names)) s.ItemHudShowNames = names;
+ bool locked = s.ItemHudLocked;
+ if (ImGui.Checkbox("Lock position", ref locked)) s.ItemHudLocked = locked;
+ float size = s.ItemHudIconSize;
+ ImGui.SetNextItemWidth(120);
+ if (ImGui.SliderFloat("Icon size", ref size, 12f, 48f, "%.0f")) s.ItemHudIconSize = size;
+ ImGui.Separator();
+ if (ImGui.MenuItem("Edit items...")) s.ShowSetup = true;
+ if (ImGui.MenuItem("Hide HUD")) s.ShowItemHud = false;
+ ImGui.EndPopup();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs
new file mode 100644
index 0000000..610b3d2
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs
@@ -0,0 +1,525 @@
+// MiniRemoteHud.cs — Floating Mini Remote (UtilityBelt-style) for RynthAi. Render thread only.
+//
+// The Mini Remote is the ILT Hub's main window: its Options menu (the Options button or a
+// right-click) opens the Hub's section windows (Character, Quests, Pets, Banking, Gear, Games,
+// Guardian).
+// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
+//
+// Sections (each can be hidden from the Options menu):
+// Stats session time and per-hour XP / luminance / kills / coins / pyreals (ILT Hub rates)
+// Target the creature combat is attacking: name, health bar, distance
+// Pet the summon that is out (health bar, time left), else the next combat essence and
+// whether it is ready
+// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
+// pack item), right-click assigns / clears, and items dragged from the game's
+// inventory or the RynthCore Inventory window drop straight into a slot
+// Toggles macro and subsystem switches (same as the dashboard buttons)
+// Bank ILT bank balances (pyreals, luminance, keys, coins)
+// Rebuff force rebuff / cancel rebuff
+// Translate chat translator on/off and the receive <-> send language swap
+// Guardian the last Temple guardian answer with a Give button (only while it is recent)
+// All game actions are posted to the pump thread.
+using System;
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.IltHub;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.Huds;
+
+internal sealed class MiniRemoteHud
+{
+ private const string OptionsPopup = "##miniremoteopts";
+ private const string SlotPopup = "##miniremoteslot";
+ private const float SlotSize = 28f;
+ /// Slot button edge including its 1 px frame padding on each side.
+ private const float SlotButtonSize = SlotSize + 2f;
+ /// Narrowest horizontal-layout column (fits the stat lines and the translate row).
+ private const float MinColumnWidth = 190f;
+ private const float HeaderButtonWidth = 80f;
+
+ 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);
+ private static readonly Vector4 ColOut = new(0.45f, 0.85f, 0.95f, 1f);
+ private static readonly Vector4 ColEmpty = new(0.95f, 0.45f, 0.40f, 1f);
+ private static readonly Vector4 ColBusy = new(0.95f, 0.80f, 0.35f, 1f);
+
+ private readonly HudController _hud;
+ private int _slotMenuIndex = -1;
+ private bool _rescueChecked; // off-screen check done for the current show
+ private bool _columnOpen; // horizontal layout: a column was already started this frame (next one goes SameLine)
+
+ public MiniRemoteHud(HudController hud) => _hud = hud;
+
+ /// The remote was not drawn this frame: check its position again on the next show.
+ public void OnHidden() => _rescueChecked = false;
+
+ public void Render()
+ {
+ var s = _hud.State;
+ var flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoScrollbar
+ | ImGuiWindowFlags.NoFocusOnAppearing;
+ if (s.MiniRemoteLocked) flags |= ImGuiWindowFlags.NoMove;
+
+ // Left of and above centre, mirroring the Item HUD's first spot.
+ UiPlacement.CenterFirstUse(new Vector2(-220, -160));
+ ImGui.SetNextWindowBgAlpha(0.70f);
+ bool open = true;
+ ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
+ bool visible = ImGui.Begin("Mini Remote##rynthminiremote", ref open, flags);
+ ImGui.PopStyleVar();
+ if (!open) s.ShowMiniRemote = false;
+ if (!visible) { ImGui.End(); return; }
+ UiPlacement.RescueOncePerShow(ref _rescueChecked);
+
+ var hub = _hud.Hub();
+ RenderHeaderRow(s);
+ if (s.MiniRemoteHorizontal) RenderHorizontal(s, hub);
+ else RenderVertical(s, hub);
+
+ // Right-click on the window body opens the options, unless a slot's own menu is open.
+ if (_slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
+ ImGui.OpenPopup(OptionsPopup);
+ RenderOptions(s);
+ _slotMenuIndex = -1;
+ ImGui.End();
+ }
+
+ // ── Layout ──────────────────────────────────────────────────────────────
+
+ /// [V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.
+ private static void RenderHeaderRow(HudState s)
+ {
+ if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
+ s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal;
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
+ ImGui.SameLine();
+ if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) ImGui.OpenPopup(OptionsPopup);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("ILT Hub windows and Mini Remote settings (or right-click the remote).");
+ }
+
+ private void RenderVertical(HudState s, IltHubController? hub)
+ {
+ RenderStatusSections(s, hub);
+ RenderActionSections(s);
+ RenderEconomySections(s, hub);
+ }
+
+ ///
+ /// Three side-by-side columns: status (stats, target, pet), actions (slots, toggles) and
+ /// economy (bank, rebuff, translate). Each column is a fixed-width child that grows only in
+ /// height; widgets sized from the available width would otherwise make the auto-resizing
+ /// window grow every frame.
+ ///
+ private void RenderHorizontal(HudState s, IltHubController? hub)
+ {
+ float colW = ColumnWidth();
+ _columnOpen = false;
+ if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet)
+ {
+ BeginColumn("##mrcolstatus", colW);
+ RenderStatusSections(s, hub);
+ ImGui.EndChild();
+ }
+ if (s.MiniShowGems || s.MiniShowToggles)
+ {
+ BeginColumn("##mrcolactions", colW);
+ RenderActionSections(s);
+ ImGui.EndChild();
+ }
+ if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian)
+ {
+ BeginColumn("##mrcoleconomy", colW);
+ RenderEconomySections(s, hub);
+ ImGui.EndChild();
+ }
+ }
+
+ /// Starts a column child (caller always calls EndChild, whatever BeginChild returned).
+ private void BeginColumn(string id, float width)
+ {
+ if (_columnOpen) ImGui.SameLine();
+ _columnOpen = true;
+ ImGui.BeginChild(id, new Vector2(width, 0), ImGuiChildFlags.AutoResizeY, ImGuiWindowFlags.NoScrollbar);
+ }
+
+ /// Wide enough for the slot grid, and never narrower than MinColumnWidth.
+ private static float ColumnWidth()
+ {
+ int cols = HudState.MiniRemoteColumns;
+ float grid = cols * SlotButtonSize + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
+ return Math.Max(MinColumnWidth, grid);
+ }
+
+ private void RenderStatusSections(HudState s, IltHubController? hub)
+ {
+ var combat = _hud.Combat;
+ if (s.MiniShowStats) RenderStats(hub);
+ if (s.MiniShowTarget) RenderTarget(combat);
+ if (s.MiniShowPet) RenderPet(hub, combat);
+ if (s.MiniShowStats) RenderStatButtons(hub);
+ }
+
+ private void RenderActionSections(HudState s)
+ {
+ if (s.MiniShowGems) RenderSlots(s);
+ if (s.MiniShowToggles) RenderToggles(_hud.Dashboard.Settings);
+ }
+
+ private void RenderEconomySections(HudState s, IltHubController? hub)
+ {
+ if (s.MiniShowBank) RenderBank(hub);
+ if (s.MiniShowRebuff) RenderRebuff();
+ if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection();
+ if (s.MiniShowGuardian && IltActive(hub)) hub!.Guardian.RenderRemoteLine();
+ }
+
+ // ── Sections ────────────────────────────────────────────────────────────
+
+ private static bool IltActive(IltHubController? hub) => hub != null && hub.Options.IsIltLikeWorld;
+
+ private static void Stat(string label, string value)
+ {
+ ImGui.TextColored(ColLabel, label);
+ ImGui.SameLine();
+ ImGui.TextUnformatted(value);
+ }
+
+ private static void RenderStats(IltHubController? hub)
+ {
+ if (!IltActive(hub)) { ImGui.TextDisabled("Session stats: ILT worlds only"); return; }
+ var r = hub!.Rates.Summary;
+ Stat("Time:", IltParse.Duration(DateTime.UtcNow - hub.Rates.SessionStartUtc));
+ Stat("XP:", HudDraw.Compact(r.XpPerHour) + "/h");
+ Stat("Lum:", HudDraw.Compact(r.LumPerHour) + "/h");
+ Stat("Kills:", HudDraw.Compact(r.KillsPerHour) + "/h");
+ Stat("Coins:", HudDraw.Compact(r.CoinsPerHour) + "/h");
+ Stat("Pyr:", HudDraw.Compact(r.PyrealsPerHour) + "/h");
+ }
+
+ private static void RenderTarget(CombatHudSnapshot c)
+ {
+ if (c.TargetId == 0) { ImGui.TextDisabled("Target: none"); return; }
+ ImGui.TextColored(ColLabel, "Target:");
+ ImGui.SameLine();
+ ImGui.TextUnformatted(c.TargetName);
+ if (c.TargetDistance >= 0)
+ {
+ ImGui.SameLine();
+ ImGui.TextDisabled($"{c.TargetDistance:F0}yd");
+ }
+ HealthBar("##mrtargethp", c.TargetHealth);
+ }
+
+ /// The live summon when one is out, else the ILT Hub's next-essence line.
+ private static void RenderPet(IltHubController? hub, CombatHudSnapshot c)
+ {
+ if (c.PetId != 0)
+ {
+ RenderSummon(hub, c);
+ return;
+ }
+ if (!IltActive(hub)) { ImGui.TextDisabled("Summon: none"); return; }
+ string name = hub!.Pets.HudPetName;
+ string status = hub.Pets.HudPetStatus;
+ if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; }
+ ImGui.TextUnformatted(name);
+ var col = status switch { "Ready" => ColReady, "Out" => ColOut, "Healing" => ColBusy, _ => ColEmpty };
+ ImGui.TextColored(col, status);
+ }
+
+ private static void RenderSummon(IltHubController? hub, CombatHudSnapshot c)
+ {
+ ImGui.TextColored(ColLabel, "Summon:");
+ ImGui.SameLine();
+ ImGui.TextUnformatted(c.PetName);
+ if (IltActive(hub) && hub!.Pets.HudPetStatus == "Healing")
+ {
+ ImGui.SameLine();
+ ImGui.TextColored(ColBusy, "Healing");
+ }
+ HealthBar("##mrpethp", c.PetHealth);
+
+ long now = Environment.TickCount64;
+ if (c.PetExpiresAtMs != 0)
+ {
+ long leftMs = Math.Max(0, c.PetExpiresAtMs - now);
+ var left = TimeSpan.FromMilliseconds(leftMs);
+ string text = $"{FormatClock(left)} left";
+ if (c.PetLifespanSec > 0)
+ {
+ float frac = Math.Clamp(leftMs / (c.PetLifespanSec * 1000f), 0f, 1f);
+ var col = left.TotalSeconds <= 30 ? ColEmpty : left.TotalSeconds <= 90 ? ColBusy : ColOut;
+ Bar("##mrpettime", frac, text, col);
+ }
+ else
+ {
+ ImGui.TextColored(left.TotalSeconds <= 30 ? ColEmpty : ColOut, text);
+ }
+ }
+ else
+ {
+ // No RemainingLifespan from the server: show how long it has been out instead.
+ var up = TimeSpan.FromMilliseconds(Math.Max(0, now - c.PetSeenAtMs));
+ ImGui.TextDisabled($"Out {FormatClock(up)}");
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server hasn't reported this summon's lifespan yet.");
+ }
+ }
+
+ private static string FormatClock(TimeSpan t)
+ => t.TotalHours >= 1 ? $"{(int)t.TotalHours}:{t.Minutes:00}:{t.Seconds:00}" : $"{t.Minutes}:{t.Seconds:00}";
+
+ /// Health ratio bar coloured green / yellow / red; "--" until the first health update.
+ private static void HealthBar(string id, float ratio)
+ {
+ if (ratio < 0f) { Bar(id, 0f, "HP --", ColLabel); return; }
+ var col = ratio > 0.6f ? ColReady : ratio > 0.3f ? ColBusy : ColEmpty;
+ Bar(id, ratio, $"HP {ratio * 100f:F0}%", col);
+ }
+
+ private static void Bar(string id, float fraction, string overlay, Vector4 color)
+ {
+ float w = Math.Max(ImGui.GetContentRegionAvail().X, 140f);
+ ImGui.PushStyleColor(ImGuiCol.PlotHistogram, color with { W = 0.85f });
+ ImGui.PushID(id);
+ ImGui.ProgressBar(fraction, new Vector2(w, 14f), overlay);
+ ImGui.PopID();
+ ImGui.PopStyleColor();
+ }
+
+ private void RenderStatButtons(IltHubController? hub)
+ {
+ if (!IltActive(hub)) return;
+ float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
+ w = Math.Max(w, 70f);
+ if (ImGui.Button("Reset XP", new Vector2(w, 0))) _hud.Post(() => _hud.Hub()?.Rates.Reset());
+ ImGui.SameLine();
+ if (ImGui.Button("Report", new Vector2(w, 0))) _hud.Post(ReportToChat);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print the session rates in your chat window (local only).");
+ }
+
+ /// One-line session summary written to local chat (pump thread).
+ private void ReportToChat()
+ {
+ var hub = _hud.Hub();
+ if (hub == null) return;
+ var r = hub.Rates.Summary;
+ string time = IltParse.Duration(DateTime.UtcNow - hub.Rates.SessionStartUtc);
+ _hud.Chat($"[RynthAi] Session {time}: XP {HudDraw.Compact(r.XpPerHour)}/h, Lum {HudDraw.Compact(r.LumPerHour)}/h, "
+ + $"Kills {HudDraw.Compact(r.KillsPerHour)}/h ({r.Kills:N0}), Coins {HudDraw.Compact(r.CoinsPerHour)}/h, "
+ + $"Pyr {HudDraw.Compact(r.PyrealsPerHour)}/h");
+ }
+
+ private void RenderSlots(HudState s)
+ {
+ var slots = s.MiniRemoteSlots.ToArray();
+ var pack = _hud.Pack;
+ ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 1));
+ for (int i = 0; i < slots.Length; i++)
+ {
+ if (i % HudState.MiniRemoteColumns != 0) ImGui.SameLine();
+ var e = slots[i];
+ long count = e.IsEmpty ? 0 : pack.CountOf(e.Name);
+ ImGui.PushID(i);
+ bool clicked;
+ IntPtr tex = e.IsEmpty ? IntPtr.Zero : _hud.Icons.GetTexture(e.IconDid);
+ if (tex != IntPtr.Zero)
+ {
+ var tint = count == 0 ? new Vector4(1, 1, 1, 0.35f) : Vector4.One;
+ clicked = ImGui.ImageButton("##slot", tex, new Vector2(SlotSize, SlotSize), Vector2.Zero, Vector2.One, Vector4.Zero, tint);
+ }
+ else
+ {
+ string label = e.IsEmpty ? string.Empty : e.Name.Substring(0, 1).ToUpperInvariant();
+ if (e.IsEmpty) ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.13f, 0.18f, 0.6f));
+ clicked = ImGui.Button(label + "##slot", new Vector2(SlotSize + 2, SlotSize + 2));
+ if (e.IsEmpty) ImGui.PopStyleColor();
+ }
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(e.IsEmpty ? EmptySlotTip(i) : $"{e.Name}\n{count:N0} carried\nClick to use, right-click for options.");
+ int slotIndex = i;
+ if (clicked)
+ {
+ // Empty slot: click assigns the selected (or last selected) pack item.
+ if (e.IsEmpty) _hud.Post(() => _hud.SetSlotFromSelection(slotIndex));
+ else
+ {
+ var entry = e;
+ _hud.Post(() => _hud.UseItem(entry));
+ }
+ }
+ AcceptItemDrop(slotIndex, e.IsEmpty);
+ if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
+ {
+ _slotMenuIndex = i;
+ ImGui.OpenPopup(SlotPopup);
+ }
+ RenderSlotMenu(i, e);
+ ImGui.PopID();
+ }
+ ImGui.PopStyleVar();
+ }
+
+ ///
+ /// ImGui drag-and-drop payload type for one inventory item (uint object id). Must match
+ /// InventoryFace.ItemPayloadType in RynthCore.Engine, which publishes it while dragging.
+ ///
+ private const string ItemPayloadType = "RYNTH_INV_ITEM";
+
+ ///
+ /// Payload type for an AC-inventory drag whose item the engine guessed from the game selection
+ /// (uint object id); engines that hook AC's drag start send the real item as ItemPayloadType
+ /// instead. Must match ItemDragBridge.NativePayloadType in RynthCore.Engine. A guess can be the
+ /// wrong item, so it is taken by empty slots only and never replaces an assigned one.
+ ///
+ private const string GameItemPayloadType = "RYNTH_GAME_ITEM";
+
+ ///
+ /// Makes the last slot button a drop target: RynthCore Inventory drags on any slot, game
+ /// inventory drags on slots.
+ ///
+ private unsafe void AcceptItemDrop(int slot, bool empty)
+ {
+ if (!ImGui.BeginDragDropTarget()) return;
+ ImGuiPayloadPtr payload = ImGui.AcceptDragDropPayload(ItemPayloadType);
+ if (payload.NativePtr == null && empty) payload = ImGui.AcceptDragDropPayload(GameItemPayloadType);
+ if (payload.NativePtr != null && payload.Data != IntPtr.Zero && payload.DataSize >= sizeof(uint))
+ {
+ uint objectId = *(uint*)payload.Data;
+ _hud.Post(() => _hud.SetSlotFromItemId(slot, objectId));
+ }
+ ImGui.EndDragDropTarget();
+ }
+
+ private string EmptySlotTip(int index)
+ {
+ string candidate = _hud.AssignCandidate;
+ return candidate.Length > 0
+ ? $"Slot {index + 1:00}: empty\nClick to assign {candidate}.\nOr drag an item here from the game inventory or the RynthCore Inventory."
+ : $"Slot {index + 1:00}: empty\nClick an item in your pack, then click here to assign it.\nOr drag an item here from the game inventory or the RynthCore Inventory.";
+ }
+
+ /// Per-slot right-click menu (opened inside the slot's ID scope).
+ private void RenderSlotMenu(int index, HudItemEntry e)
+ {
+ if (!ImGui.BeginPopup(SlotPopup)) return;
+ _slotMenuIndex = index;
+ ImGui.TextDisabled(e.IsEmpty ? $"Slot {index + 1:00}" : $"Slot {index + 1:00}: {e.Name}");
+ string candidate = _hud.AssignCandidate;
+ if (ImGui.MenuItem(candidate.Length > 0 ? $"Assign {candidate}" : "Assign selected item"))
+ _hud.Post(() => _hud.SetSlotFromSelection(index));
+ if (!e.IsEmpty && ImGui.MenuItem("Clear slot")) _hud.Post(() => _hud.ClearSlot(index));
+ ImGui.EndPopup();
+ }
+
+ private void RenderToggles(LegacyUiSettings settings)
+ {
+ var dash = _hud.Dashboard;
+ if (!ImGui.BeginTable("##mrtoggles", 3, ImGuiTableFlags.SizingStretchSame)) return;
+ Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro());
+ Toggle("Combat", settings.EnableCombat, on => dash.SetSubsystemEnabled(0, on));
+ Toggle("Buff", settings.EnableBuffing, on => dash.SetSubsystemEnabled(1, on));
+ Toggle("Nav", settings.EnableNavigation, on => dash.SetSubsystemEnabled(2, on));
+ Toggle("Loot", settings.EnableLooting, on => dash.SetSubsystemEnabled(3, on));
+ Toggle("Meta", settings.EnableMeta, on => dash.SetSubsystemEnabled(4, on));
+ Toggle("Pet", settings.SummonPets, on => { settings.SummonPets = on; dash.SaveSettings(); });
+ ImGui.EndTable();
+ }
+
+ /// A checkbox in the next table cell whose change is applied on the pump thread.
+ private void Toggle(string label, bool current, Action apply)
+ {
+ ImGui.TableNextColumn();
+ bool v = current;
+ if (ImGui.Checkbox(label + "##mrt", ref v)) _hud.Post(() => apply(v));
+ }
+
+ private static void RenderBank(IltHubController? hub)
+ {
+ if (!IltActive(hub) || hub!.Options.IsOff(IltFeature.Bank)) return;
+ var b = hub.State.Bank;
+ if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; }
+ Stat("P:", HudDraw.Compact(b.Pyreals));
+ Stat("Lum:", HudDraw.Compact(b.Luminance));
+ if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return;
+ ImGui.TableNextColumn(); Stat("LK:", HudDraw.Compact(b.LegendaryKeys));
+ ImGui.TableNextColumn(); Stat("MK:", HudDraw.Compact(b.MythicalKeys));
+ ImGui.TableNextColumn(); Stat("EC:", HudDraw.Compact(b.EnlightenedCoins));
+ ImGui.TableNextColumn(); Stat("WE:", HudDraw.Compact(b.WeaklyEnlightenedCoins));
+ ImGui.EndTable();
+ }
+
+ private void RenderRebuff()
+ {
+ var dash = _hud.Dashboard;
+ ImGui.TextColored(ColLabel, "Rebuff:");
+ float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
+ w = Math.Max(w, 70f);
+ if (ImGui.Button("FB", new Vector2(w, 0))) _hud.Post(dash.RequestForceRebuff);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Force rebuff: recast every buff now.");
+ ImGui.SameLine();
+ if (ImGui.Button("CFB", new Vector2(w, 0))) _hud.Post(dash.RequestCancelForceRebuff);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Cancel the running rebuff.");
+ }
+
+ private void RenderOptions(HudState s)
+ {
+ if (!ImGui.BeginPopup(OptionsPopup)) return;
+ RenderHubMenu(_hud.Hub());
+ ImGui.Separator();
+ ImGui.TextDisabled("Mini Remote sections");
+ Flag("Session stats", ref s.MiniShowStats);
+ Flag("Attack target", ref s.MiniShowTarget);
+ Flag("Pet / summon", ref s.MiniShowPet);
+ Flag("Item slots", ref s.MiniShowGems);
+ Flag("Toggles", ref s.MiniShowToggles);
+ Flag("Bank", ref s.MiniShowBank);
+ Flag("Rebuff", ref s.MiniShowRebuff);
+ Flag("Translate", ref s.MiniShowTranslate);
+ Flag("Guardian answer", ref s.MiniShowGuardian);
+ ImGui.Separator();
+ Flag("Horizontal layout", ref s.MiniRemoteHorizontal);
+ Flag("Lock position", ref s.MiniRemoteLocked);
+ if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
+ if (ImGui.MenuItem("Hide Mini Remote")) s.ShowMiniRemote = false;
+ ImGui.EndPopup();
+ }
+
+ ///
+ /// ILT Hub group of the Options menu: one item per section window (checked when open, greyed
+ /// out until the server reports the feature). Off ILT worlds it also offers the Force-ILT
+ /// override and a server-options refresh.
+ ///
+ private static void RenderHubMenu(IltHubController? hub)
+ {
+ ImGui.TextDisabled("ILT Hub");
+ if (hub == null) { ImGui.TextDisabled("Available after login."); return; }
+
+ foreach (IltSection section in IltSections.All)
+ {
+ bool open = hub.IsSectionOpen(section);
+ if (ImGui.MenuItem(IltSections.Label(section) + "##mrsec", string.Empty, open, hub.SectionAvailable(section)))
+ hub.SetSectionOpen(section, !open);
+ }
+ ImGui.TextDisabled("Progression: Skills panel (Char right-click)");
+
+ if (hub.Available) return;
+ var o = hub.Options;
+ ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
+ : o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
+ : "No ILT features reported.");
+ bool force = hub.ForceIltWorld;
+ if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) hub.ForceIltWorld = force;
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip("World-identity override only: the Hub asks the server which features exist.\nIt never turns a feature on by itself.");
+ if (ImGui.MenuItem("Refresh server features##mrrefresh")) hub.RequestOptionsRefresh();
+ }
+
+ private static void Flag(string label, ref bool value)
+ {
+ bool v = value;
+ if (ImGui.Checkbox(label, ref v)) value = v;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBanking.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBanking.cs
new file mode 100644
index 0000000..a7e0810
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBanking.cs
@@ -0,0 +1,427 @@
+// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, confirmed transfers, transaction log.
+//
+// Server contract (ACECustom PlayerCommands bank handler):
+// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:",
+// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:",
+// "Weakly Enlightened Coins:".
+// /bank t → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
+// the recipient sees "Received {N0} {currency} from {Name}".
+// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins.
+// 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).
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltBanking : IIltFeature
+{
+ /// Transfer currency table: display name, /bank t code.
+ public static readonly (string Name, string Code)[] Currencies =
+ {
+ ("Pyreals", "p"),
+ ("Luminance", "l"),
+ ("Legendary Keys", "k"),
+ ("Mythical Keys", "mk"),
+ ("Enlightened Coins", "e"),
+ ("Weakly Enlightened Coins", "we"),
+ };
+ private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray();
+
+ /// Server throttle for bank commands (bank_command_limit).
+ private const long BankCommandSpacingMs = 5000;
+
+ private readonly IltHubContext _ctx;
+ private readonly object _txLock = new();
+ private readonly List _transactions;
+ private IltBankTransaction[] _txSnapshot = Array.Empty();
+ private bool _txDirty;
+
+ private long _lastBankCommandAt;
+ private long _lastAutoRefreshAt;
+
+ // Render-thread form state.
+ private string _amountText = string.Empty;
+ private string _txFilter = string.Empty;
+ private string _lastResult = string.Empty;
+
+ /// Raised (pump thread) after a balance line updates the state; Character rates use the deltas.
+ public event Action? BalanceChanged;
+
+ public IltBanking(IltHubContext ctx)
+ {
+ _ctx = ctx;
+ _transactions = ctx.Store.LoadTransactions();
+ PublishSnapshot();
+ }
+
+ private IltBankState Bank => _ctx.State.Bank;
+ public bool Enabled => _ctx.Options.IsOn(IltFeature.Bank);
+
+ /// Exposed for the one-time UB import (mutated under the lock).
+ public void ImportUb(Func, string> importer)
+ {
+ string summary;
+ lock (_txLock)
+ {
+ summary = importer(_transactions);
+ _txDirty = true;
+ }
+ PublishSnapshot();
+ RynthLog.Write(LogCat.IltBanking, $"[IltHub] UB sidecar import: {summary}");
+ }
+
+ // ── Commands ────────────────────────────────────────────────────────────
+
+ /// Queues a /bank balance refresh (eaten when ).
+ public void RequestRefresh(bool quiet)
+ {
+ RynthLog.Trace(LogCat.IltBanking, $"RequestRefresh(quiet={quiet})");
+ if (_ctx.Capture.IsPending("/bank")) return;
+ long now = IltHubContext.NowMs;
+ if (now - _lastBankCommandAt < BankCommandSpacingMs) return;
+ _lastBankCommandAt = now;
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = "/bank",
+ IsResponseLine = t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase),
+ IdleEndMs = 2000,
+ FirstLineTimeoutMs = 15000,
+ Eat = quiet,
+ OnComplete = r =>
+ {
+ if (r.UnknownCommand) _ctx.Options.Set(IltFeature.Bank, IltTri.Off);
+ else if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Bank, IltTri.On);
+ },
+ });
+ }
+
+ ///
+ /// Validates and (after the UI confirm) sends a transfer. Pump thread.
+ /// Returns an error message, or empty when the command was queued.
+ ///
+ public string SendTransfer(int currencyIndex, long amount, string target)
+ {
+ RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')");
+ if (!Enabled) return "Bank is not available on this server.";
+ if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency.";
+ if (amount <= 0) return "Amount must be positive.";
+ target = (target ?? string.Empty).Trim();
+ if (target.Length == 0) return "Enter a recipient.";
+ // The recipient is spliced into a chat command, so only character-name characters are
+ // allowed: no '/', control characters or line breaks that could start a second command.
+ if (!IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only).";
+ if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself.";
+ long now = IltHubContext.NowMs;
+ if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
+ _lastBankCommandAt = now;
+
+ string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}";
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = cmd,
+ IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal)
+ || t.StartsWith("Character '", StringComparison.Ordinal)
+ || t.StartsWith("You cannot transfer", StringComparison.Ordinal)
+ || t.StartsWith("You don't have enough", StringComparison.Ordinal)
+ || t.StartsWith("[Transfer]", StringComparison.Ordinal),
+ IdleEndMs = 500,
+ FirstLineTimeoutMs = 8000,
+ Eat = false,
+ OnComplete = r =>
+ {
+ _lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
+ // Balances changed — refresh quietly once the server throttle allows.
+ _lastAutoRefreshAt = 0;
+ },
+ });
+ return string.Empty;
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ // Periodic quiet refresh only while the Hub is open and the server has /bank.
+ int every = Bank.AutoRefreshSeconds;
+ if (Enabled && _ctx.WindowOpen && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
+ && nowMs - _lastBankCommandAt >= BankCommandSpacingMs)
+ {
+ _lastAutoRefreshAt = nowMs;
+ RequestRefresh(quiet: true);
+ }
+
+ if (_txDirty)
+ {
+ lock (_txLock)
+ {
+ _ctx.Store.SaveTransactionsIfDirty(_transactions);
+ _txDirty = false;
+ }
+ PublishSnapshot();
+ }
+ }
+
+ public bool OnChat(string text)
+ {
+ if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase))
+ {
+ ParseBalanceLine(text);
+ return false; // eating is decided by the capture queue
+ }
+ TryLogTransaction(text);
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions);
+ }
+
+ // ── Parsing ─────────────────────────────────────────────────────────────
+
+ private void ParseBalanceLine(string text)
+ {
+ string body = text.Substring("[BANK]".Length).Trim();
+ int colon = body.IndexOf(':');
+ if (colon <= 0) return;
+ 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("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;
+
+ Bank.LastUpdated = DateTime.Now;
+ _ctx.Options.Set(IltFeature.Bank, IltTri.On);
+ }
+
+ private void Apply(string key, ref long field, long value)
+ {
+ long old = field;
+ field = value;
+ if (old != value)
+ {
+ try { BalanceChanged?.Invoke(key, old, value); } catch { }
+ }
+ }
+
+ private void TryLogTransaction(string text)
+ {
+ if (!(text.StartsWith("Transferred ", StringComparison.Ordinal) || text.StartsWith("Received ", StringComparison.Ordinal)))
+ return;
+ // Only server system lines are logged. Anything another player can author (tells, says,
+ // emotes, any bracketed channel) is rejected so quoted "Transferred ..." text can't
+ // forge entries in the transaction log.
+ if (IsPlayerAuthoredLine(text))
+ {
+ RynthLog.Trace(LogCat.IltBanking, "transaction ignored (player-authored line): " + text);
+ return;
+ }
+
+ var sent = IltParse.BankSent.Match(text);
+ var recv = sent.Success ? System.Text.RegularExpressions.Match.Empty : IltParse.BankReceived.Match(text);
+ var m = sent.Success ? sent : recv;
+ if (!m.Success) return;
+
+ string other = IltParse.StripMarkup(m.Groups[3].Value).Replace(" (offline)", string.Empty).Trim();
+ var tx = new IltBankTransaction
+ {
+ Timestamp = DateTime.Now,
+ Type = sent.Success ? "Sent" : "Received",
+ Amount = IltParse.ParseLeadingLong(m.Groups[1].Value),
+ Currency = m.Groups[2].Value.Trim(),
+ OtherPlayer = other,
+ Description = text,
+ };
+ lock (_txLock)
+ {
+ _transactions.Add(tx);
+ if (_transactions.Count > IltHubStore.MaxTransactions)
+ _transactions.RemoveRange(0, _transactions.Count - IltHubStore.MaxTransactions);
+ _txDirty = true;
+ }
+ }
+
+ /// True for chat another player could have written (tells, says, channel or emote markup).
+ private static bool IsPlayerAuthoredLine(string text)
+ => text.Contains(" RequestRefresh(quiet: true));
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine());
+ ImGui.SameLine();
+ ImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g"));
+
+ if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
+ {
+ Row("Pyreals", Bank.Pyreals);
+ Row("Luminance", Bank.Luminance);
+ Row("Legendary Keys", Bank.LegendaryKeys);
+ Row("Mythical Keys", Bank.MythicalKeys);
+ Row("Enlightened Coins", Bank.EnlightenedCoins);
+ Row("Weakly Enlightened Coins", Bank.WeaklyEnlightenedCoins);
+ ImGui.EndTable();
+ }
+
+ int refresh = Bank.AutoRefreshSeconds;
+ ImGui.SetNextItemWidth(120);
+ if (ImGui.InputInt("Auto-refresh seconds (0 = off)", ref refresh, 30))
+ Bank.AutoRefreshSeconds = refresh <= 0 ? 0 : Math.Max(30, refresh);
+
+ ImGui.Separator();
+ RenderTransferForm();
+ ImGui.Separator();
+ RenderTransactionLog();
+ }
+
+ private static void Row(string label, long value)
+ {
+ ImGui.TableNextRow();
+ ImGui.TableNextColumn();
+ ImGui.TextUnformatted(label);
+ ImGui.TableNextColumn();
+ ImGui.TextUnformatted($"{IltParse.N0(value)} ({IltParse.Compact(value)})");
+ }
+
+ private void RenderTransferForm()
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Transfer");
+ int idx = Math.Clamp(Bank.TransferCurrencyIndex, 0, Currencies.Length - 1);
+ ImGui.SetNextItemWidth(200);
+ if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length))
+ Bank.TransferCurrencyIndex = idx;
+
+ ImGui.SetNextItemWidth(200);
+ ImGui.InputTextWithHint("Amount##xfer", "e.g. 250000, 1.5m, 2b", ref _amountText, 32u);
+ string target = Bank.TransferTarget;
+ ImGui.SetNextItemWidth(200);
+ if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u))
+ Bank.TransferTarget = target;
+
+ bool amountOk = IltParse.TryParseAmount(_amountText, out long amount);
+ if (_amountText.Length > 0)
+ {
+ ImGui.SameLine();
+ if (amountOk) ImGui.TextDisabled("= " + IltParse.N0(amount));
+ else ImGui.TextColored(LegacyDashboardRenderer.ColHp, "invalid amount");
+ }
+
+ ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
+ if (ImGui.Button("Send transfer..."))
+ {
+ int cur = idx;
+ long amt = amount;
+ string who = Bank.TransferTarget.Trim();
+ _ctx.Confirm("Confirm bank transfer",
+ $"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.",
+ () =>
+ {
+ string err = SendTransfer(cur, amt, who);
+ _lastResult = err.Length > 0 ? err : "Transfer sent...";
+ },
+ "Send");
+ }
+ ImGui.EndDisabled();
+ if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult);
+ }
+
+ private void RenderTransactionLog()
+ {
+ var snap = _txSnapshot;
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, $"Transactions ({snap.Length})");
+ ImGui.SameLine();
+ ImGui.SetNextItemWidth(180);
+ ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u);
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Copy CSV")) ImGui.SetClipboardText(BuildCsv(snap));
+
+ if (ImGui.BeginTable("##ilttx", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
+ new Vector2(0, 220)))
+ {
+ ImGui.TableSetupScrollFreeze(0, 1);
+ ImGui.TableSetupColumn("When");
+ ImGui.TableSetupColumn("Type");
+ ImGui.TableSetupColumn("Amount");
+ ImGui.TableSetupColumn("Currency");
+ ImGui.TableSetupColumn("Player");
+ ImGui.TableHeadersRow();
+ for (int i = snap.Length - 1; i >= 0; i--)
+ {
+ var t = snap[i];
+ if (_txFilter.Length > 0
+ && !t.OtherPlayer.Contains(_txFilter, StringComparison.OrdinalIgnoreCase)
+ && !t.Currency.Contains(_txFilter, StringComparison.OrdinalIgnoreCase))
+ continue;
+ ImGui.TableNextRow();
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g"));
+ ImGui.TableNextColumn();
+ ImGui.TextColored(t.Type == "Sent" ? LegacyDashboardRenderer.ColAmber : LegacyDashboardRenderer.ColGreen, t.Type);
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount));
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency);
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer);
+ }
+ ImGui.EndTable();
+ }
+ }
+
+ /// One-line summary in UB's chat-paste format.
+ public string BuildCopyLine()
+ => $"Bank Balances - {_ctx.CharName} | P: {IltParse.N0(Bank.Pyreals)} | L: {IltParse.N0(Bank.Luminance)} | "
+ + $"LK: {IltParse.N0(Bank.LegendaryKeys)} | MK: {IltParse.N0(Bank.MythicalKeys)} | "
+ + $"Coins: {IltParse.N0(Bank.EnlightenedCoins)} | W Coins: {IltParse.N0(Bank.WeaklyEnlightenedCoins)} | "
+ + $"Updated: {(Bank.LastUpdated == DateTime.MinValue ? "never" : Bank.LastUpdated.ToString("g"))}";
+
+ private static string BuildCsv(IltBankTransaction[] rows)
+ {
+ var sb = new System.Text.StringBuilder("Timestamp,Type,Amount,Currency,Player\n");
+ foreach (var t in rows)
+ sb.Append(t.Timestamp.ToString("s")).Append(',').Append(t.Type).Append(',').Append(t.Amount).Append(',')
+ .Append('"').Append(t.Currency.Replace("\"", "\"\"")).Append("\",\"")
+ .Append(t.OtherPlayer.Replace("\"", "\"\"")).Append("\"\n");
+ return sb.ToString();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBuffKeepers.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBuffKeepers.cs
new file mode 100644
index 0000000..f897eae
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltBuffKeepers.cs
@@ -0,0 +1,254 @@
+// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab).
+//
+// Both read the player's enchantment list once a second (one shared read).
+// Dispel: classifies active spells by NAME (SpellDatabase has no debuff flag):
+// 1. Mire Foot (3051 / "mire"+"foot") → never (dispelling it is pointless)
+// 2. user include list → dispel
+// 3. beneficial pattern → keep
+// 4. user exclude list → keep
+// 5. known-harmful exact name or pattern → dispel
+// and uses a Rune of Dispel (WCID 30133). Cooldown, verify after 2 s, up to 3 retries.
+// Surging Strength: uses the Empowered Volcanic Ember when the buff is missing.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltBuffKeepers : IIltFeature
+{
+ private const int SpellMireFoot = 3051;
+ private const int MaxEnch = 256;
+
+ private static readonly HashSet HarmfulExact = BuildHarmfulExact();
+ private static readonly Regex HarmfulPattern = new(
+ @"\b(vulnerability|imperil|weakness|slowness|bane|exhaustion|mana burn|fester|curse of|blight of|burden of)\b",
+ RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ private static readonly Regex BeneficialPattern = new(
+ @"\b(invulnerability|invulnerable|protection|ward|armor|blessing|strength|coordination|endurance|quickness|focus|willpower|"
+ + @"regeneration|mana renewal|stamina renewal|health renewal|arcanum|cantrap|enhancement|augmentation|weave of|shroud of|"
+ + @"mantle of|cloak of|veil of|master's blessing|society|fellowship|loyalty|devotion)\b",
+ RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+
+ private static HashSet BuildHarmfulExact()
+ {
+ var set = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (string s in new[] { "weakness other", "vulnerability other", "imperil other", "slowness other",
+ "bane other", "exhaustion other", "mana burn other", "fester other" })
+ {
+ set.Add(s);
+ set.Add("incantation of " + s);
+ }
+ foreach (string s in new[] { "belly of lead", "gelidite's gift", "inferno's gift", "senescence", "archer's gift",
+ "swordsman's gift", "leaden feet", "heart of ice", "burning soul", "withering" })
+ set.Add(s);
+ return set;
+ }
+
+ private readonly IltHubContext _ctx;
+ private readonly uint[] _ids = new uint[MaxEnch];
+ private readonly double[] _exp = new double[MaxEnch];
+ private long _lastRead;
+
+ // Dispel state
+ private long _dispelCooldownUntil;
+ private long _verifyAt;
+ private int _retries;
+ private volatile string[] _harmfulNow = Array.Empty();
+ private volatile string _dispelStatus = "idle";
+
+ // Surging state
+ private long _surgeCooldownUntil;
+ private volatile bool _surgeActive;
+ private volatile string _surgeStatus = "idle";
+
+ // Render-thread edit buffers
+ private string _newInclude = string.Empty, _newExclude = string.Empty;
+
+ public IltBuffKeepers(IltHubContext ctx) => _ctx = ctx;
+
+ private IltGearState G => _ctx.State.Gear;
+
+ /// True when this spell should be dispelled (precedence documented above).
+ public bool IsHarmful(int spellId, string name)
+ {
+ if (spellId == SpellMireFoot || (name.Contains("mire", StringComparison.OrdinalIgnoreCase) && name.Contains("foot", StringComparison.OrdinalIgnoreCase)))
+ return false;
+ if (G.DispelInclusions.ToArray().Any(i => i.Length > 0 && name.Contains(i, StringComparison.OrdinalIgnoreCase))) return true;
+ if (BeneficialPattern.IsMatch(name)) return false;
+ if (G.DispelExclusions.ToArray().Any(e => e.Length > 0 && name.Contains(e, StringComparison.OrdinalIgnoreCase))) return false;
+ string bare = StripTier(name);
+ return HarmfulExact.Contains(name) || HarmfulExact.Contains(bare) || HarmfulPattern.IsMatch(name);
+ }
+
+ /// "Vulnerability Other VII" → "vulnerability other" (roman numeral suffix removed).
+ private static string StripTier(string name)
+ {
+ string n = name.Trim();
+ int sp = n.LastIndexOf(' ');
+ if (sp > 0)
+ {
+ string tail = n.Substring(sp + 1);
+ if (tail.Length > 0 && tail.All(ch => "IVXL".IndexOf(char.ToUpperInvariant(ch)) >= 0)) n = n.Substring(0, sp);
+ }
+ return n.ToLowerInvariant();
+ }
+
+ private WorldObject? FindRune()
+ => _ctx.Inventory.FindByWcid(IltInventory.WcidRuneOfDispel)
+ ?? _ctx.Inventory.FindByName(n => n.Equals("Rune of Dispel", StringComparison.OrdinalIgnoreCase)
+ || (n.Contains("dispel", StringComparison.OrdinalIgnoreCase) && n.Contains("rune", StringComparison.OrdinalIgnoreCase)));
+
+ private WorldObject? FindEmber()
+ => _ctx.Inventory.FindByName(n => n.Contains("empowered", StringComparison.OrdinalIgnoreCase)
+ && n.Contains("volcanic", StringComparison.OrdinalIgnoreCase)
+ && n.Contains("ember", StringComparison.OrdinalIgnoreCase));
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ if (!G.AutoDispel && !G.SurgingStrength) return;
+ if (nowMs - _lastRead < 1000) return;
+ _lastRead = nowMs;
+ if (!_ctx.Host.HasReadPlayerEnchantments) return;
+
+ int n = _ctx.Host.ReadPlayerEnchantments(_ids, _exp, MaxEnch);
+ if (n < 0) return;
+ n = Math.Min(n, MaxEnch);
+
+ var harmful = new List();
+ bool surge = false;
+ for (int i = 0; i < n; i++)
+ {
+ int id = unchecked((int)_ids[i]);
+ string name = SpellDatabase.GetSpellName(id);
+ if (string.IsNullOrEmpty(name)) continue;
+ if (name.Contains("Surging Strength", StringComparison.OrdinalIgnoreCase)) surge = true;
+ if (G.AutoDispel && IsHarmful(id, name)) harmful.Add(name);
+ }
+ _harmfulNow = harmful.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ _surgeActive = surge;
+
+ if (G.AutoDispel) TickDispel(nowMs, harmful.Count > 0);
+ if (G.SurgingStrength) TickSurge(nowMs, surge);
+ }
+
+ private void TickDispel(long now, bool anyHarmful)
+ {
+ // Verification / retry window after a rune use.
+ if (_verifyAt > 0)
+ {
+ if (now < _verifyAt) return;
+ if (!anyHarmful || _retries >= 3)
+ {
+ _dispelStatus = anyHarmful ? "debuffs remain after 3 retries" : "dispelled";
+ _verifyAt = 0;
+ _dispelCooldownUntil = now + Math.Max(2, G.DispelCooldownSeconds) * 1000L;
+ return;
+ }
+ _retries++;
+ if (UseRune(now)) _verifyAt = now + 2500;
+ return;
+ }
+
+ if (!anyHarmful) { _dispelStatus = "no harmful spells"; return; }
+ if (now < _dispelCooldownUntil) { _dispelStatus = "cooling down"; return; }
+ _retries = 0;
+ if (UseRune(now)) _verifyAt = now + 2000;
+ }
+
+ private bool UseRune(long now)
+ {
+ if (_ctx.Inventory.IsBusy) return false;
+ var rune = FindRune();
+ if (rune == null) { _dispelStatus = "no Rune of Dispel carried"; _dispelCooldownUntil = now + 30_000; _verifyAt = 0; return false; }
+ if (!_ctx.Inventory.Use(rune)) return false;
+ _dispelStatus = $"used {rune.Name} on {_harmfulNow.Length} debuff(s)";
+ return true;
+ }
+
+ private void TickSurge(long now, bool active)
+ {
+ if (active) { _surgeStatus = "Surging Strength active"; return; }
+ if (now < _surgeCooldownUntil || _ctx.Inventory.IsBusy) return;
+ var ember = FindEmber();
+ if (ember == null) { _surgeStatus = "no Empowered Volcanic Ember carried"; _surgeCooldownUntil = now + 30_000; return; }
+ if (_ctx.Inventory.Use(ember)) _surgeStatus = "used " + ember.Name;
+ _surgeCooldownUntil = now + Math.Max(5, G.SurgingCooldownSeconds) * 1000L;
+ }
+
+ public bool OnChat(string text)
+ {
+ if (!G.SurgingStrength) return false;
+ if (text.Contains("surging strength", StringComparison.OrdinalIgnoreCase))
+ {
+ if (text.Contains("you cast", StringComparison.OrdinalIgnoreCase) && text.Contains("on yourself", StringComparison.OrdinalIgnoreCase))
+ _surgeActive = true;
+ else if (text.Contains("has expired", StringComparison.OrdinalIgnoreCase))
+ {
+ _surgeActive = false;
+ _surgeCooldownUntil = 0; // re-apply on the next read
+ }
+ }
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ _verifyAt = 0;
+ _harmfulNow = Array.Empty();
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Auto-dispel (Rune of Dispel)");
+ bool ad = G.AutoDispel;
+ if (ImGui.Checkbox("Use a Rune of Dispel on harmful debuffs", ref ad)) G.AutoDispel = ad;
+ int cd = G.DispelCooldownSeconds;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd);
+ ImGui.TextDisabled("Status: " + _dispelStatus);
+ var harm = _harmfulNow;
+ if (harm.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Harmful now: " + string.Join(", ", harm));
+ if (ImGui.TreeNode("Always / never dispel lists"))
+ {
+ EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc");
+ EditList("Never dispel (name contains)", G.DispelExclusions, ref _newExclude, "exc");
+ ImGui.TreePop();
+ }
+
+ ImGui.Separator();
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Surging Strength");
+ bool ss = G.SurgingStrength;
+ if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss;
+ ImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus));
+ }
+
+ private void EditList(string label, List list, ref string buffer, string id)
+ {
+ ImGui.TextUnformatted(label);
+ var snap = list.ToArray();
+ for (int i = 0; i < snap.Length; i++)
+ {
+ ImGui.BulletText(snap[i]);
+ ImGui.SameLine();
+ string victim = snap[i];
+ if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim));
+ }
+ ImGui.SetNextItemWidth(200);
+ ImGui.InputTextWithHint($"##new{id}", "spell name text", ref buffer, 64u);
+ ImGui.SameLine();
+ if (ImGui.SmallButton($"Add##{id}") && buffer.Trim().Length > 0)
+ {
+ string add = buffer.Trim();
+ _ctx.Post(() => { if (!list.Contains(add, StringComparer.OrdinalIgnoreCase)) list.Add(add); });
+ buffer = string.Empty;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltCharmTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltCharmTracker.cs
new file mode 100644
index 0000000..b1d6953
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltCharmTracker.cs
@@ -0,0 +1,137 @@
+// IltCharmTracker.cs — Snapshot of every ACECustom registry charm for the engine Settings
+// panel's "Charms Tracking" tab (RynthPluginGetCharmsJson).
+//
+// Per charm it reports:
+// acquired — "carried" (in pack / equipped now), "seen" (carried earlier this or a past
+// session, remembered in IltCharacterState.CharmsSeen), or "no".
+// active — "on" / "off" / "unknown". The charm's appraisal Use text ("Status: ON") wins;
+// otherwise the player ability PropertyBool the server sets while it's active.
+// The server deactivates abilities whose charm isn't possessed, so not carried = off.
+// server — "off" when the server refused / reported the charm disabled, "on" when a feature
+// dump reported it enabled, else "unknown" (clients can't query /charms).
+// Pump thread only (inventory and property reads).
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltCharmTracker
+{
+ private readonly IltHubContext _ctx;
+
+ public IltCharmTracker(IltHubContext ctx) => _ctx = ctx;
+
+ /// One charm's tracked state.
+ internal readonly record struct CharmState(
+ IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier,
+ IltTri Active, IltTri Server, DateTime LastSeenUtc);
+
+ /// Evaluates every registry charm and refreshes the "seen" memory for carried ones.
+ public List Evaluate()
+ {
+ var inv = _ctx.Inventory;
+ var seenMap = _ctx.State.Character.CharmsSeen;
+ var result = new List(IltInventory.Charms.Length);
+ // One inventory pass, grouped by charm definition, instead of a WCID scan per charm.
+ var carried = new Dictionary>();
+ foreach (var wo in inv.Items())
+ {
+ var def = inv.CharmDefFor(wo);
+ if (def == null) continue;
+ if (!carried.TryGetValue(def, out var list)) carried[def] = list = new();
+ list.Add(wo);
+ }
+
+ foreach (var def in IltInventory.Charms)
+ {
+ carried.TryGetValue(def, out var items);
+ int count = items?.Count ?? 0;
+ int tier = 0, maxTier = 0;
+ IltTri active = IltTri.Off;
+
+ if (count > 0)
+ {
+ // Server allows only one active charm per ability, so any ON item means ON.
+ bool anyOn = false, allKnown = true;
+ foreach (var wo in items!)
+ {
+ var (t, m) = inv.CharmTier(wo);
+ if (t > tier) { tier = t; maxTier = m; }
+ var st = inv.CharmStatus(wo);
+ if (st == IltTri.On) anyOn = true;
+ else if (st == IltTri.Unknown) allKnown = false;
+ }
+ if (anyOn) active = IltTri.On;
+ else if (def.PlayerFlag != 0 && inv.PlayerBool(def.PlayerFlag)) active = IltTri.On;
+ else active = allKnown ? IltTri.Off : IltTri.Unknown;
+
+ if (!seenMap.TryGetValue(def.Name, out var seen)) seenMap[def.Name] = seen = new IltCharmSeen();
+ if (tier > seen.Tier) { seen.Tier = tier; seen.MaxTier = maxTier; }
+ // Day resolution keeps the persisted state from changing (and re-saving) every poll.
+ var today = DateTime.UtcNow.Date;
+ if (seen.LastSeenUtc != today) seen.LastSeenUtc = today;
+ }
+
+ seenMap.TryGetValue(def.Name, out var memory);
+ string acquired = count > 0 ? "carried" : memory != null ? "seen" : "no";
+ if (count == 0 && memory != null) { tier = memory.Tier; maxTier = memory.MaxTier; }
+
+ result.Add(new CharmState(def, acquired, count, tier, maxTier, active,
+ ServerState(def), memory?.LastSeenUtc ?? default));
+ }
+ return result;
+ }
+
+ /// Server-side enabled state as far as the client has learned it.
+ private IltTri ServerState(IltCharmDef def)
+ {
+ var opts = _ctx.Options;
+ var tri = opts.Get(IltFeature.Charm(def.Name));
+ // Universal Summoning Mastery also has a ServerConfig switch, reported separately.
+ if (Array.IndexOf(def.Wcids, IltInventory.WcidUniversalMasteryCharm) >= 0)
+ {
+ var cfg = opts.Get(IltFeature.UniversalMastery);
+ if (cfg == IltTri.Off || tri == IltTri.Off) return IltTri.Off;
+ if (cfg == IltTri.On || tri == IltTri.On) return IltTri.On;
+ }
+ return tri;
+ }
+
+ /// JSON for RynthPluginGetCharmsJson. "available" is false off ILT-like worlds.
+ public string BuildJson()
+ {
+ var sb = new StringBuilder(4096);
+ bool available = _ctx.Options.IsIltLikeWorld;
+ sb.Append("{\"available\":").Append(available ? "true" : "false");
+ sb.Append(",\"world\":\"").Append(RynthAiPlugin.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append('"');
+ if (!available) return sb.Append(",\"charms\":[]}").ToString();
+
+ var rows = Evaluate();
+ sb.Append(",\"total\":").Append(rows.Count);
+ sb.Append(",\"acquiredCount\":").Append(rows.Count(r => r.Acquired != "no"));
+ sb.Append(",\"activeCount\":").Append(rows.Count(r => r.Active == IltTri.On));
+ sb.Append(",\"charms\":[");
+ for (int i = 0; i < rows.Count; i++)
+ {
+ var r = rows[i];
+ if (i > 0) sb.Append(',');
+ sb.Append("{\"name\":\"").Append(RynthAiPlugin.JsonEscape(r.Def.Name)).Append('"');
+ sb.Append(",\"effect\":\"").Append(RynthAiPlugin.JsonEscape(r.Def.Effect)).Append('"');
+ sb.Append(",\"acquired\":\"").Append(r.Acquired).Append('"');
+ sb.Append(",\"count\":").Append(r.Count);
+ sb.Append(",\"tier\":").Append(r.Tier);
+ sb.Append(",\"maxTier\":").Append(r.MaxTier);
+ sb.Append(",\"active\":\"").Append(TriText(r.Active)).Append('"');
+ sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"');
+ sb.Append(",\"lastSeen\":\"")
+ .Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd"))
+ .Append("\"}");
+ }
+ sb.Append("]}");
+ return sb.ToString();
+ }
+
+ private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChatCapture.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChatCapture.cs
new file mode 100644
index 0000000..31da8ca
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChatCapture.cs
@@ -0,0 +1,199 @@
+// IltChatCapture.cs — Shared "send a server command and collect its reply" helper.
+//
+// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb,
+// /ilt features, the login probe, ...) goes through this one queue so that:
+// * only one capture is in flight at a time (replies can't be attributed to the wrong
+// request),
+// * reply lines can be eaten so a Hub refresh doesn't spam the chat window,
+// * an "Unknown command: X" reply is recognised uniformly (feature not on this server).
+// All methods must be called on the plugin pump thread (OnTick / OnChatWindowText).
+using System;
+using System.Collections.Generic;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+/// Describes one command whose reply should be captured.
+internal sealed class IltChatRequest
+{
+ /// Text handed to InvokeChatParser, e.g. "/bank".
+ public string Command = string.Empty;
+ /// True for lines that belong to this reply (captured, refresh the idle timer).
+ public Func IsResponseLine = _ => false;
+ /// Optional: a line that ends the reply immediately (it is captured too).
+ public Func? IsTerminator;
+ /// The reply is complete after this long with no new response line.
+ public int IdleEndMs = 2000;
+ /// Give up if no response line arrives within this long.
+ public int FirstLineTimeoutMs = 15000;
+ /// Hide captured lines from the chat window.
+ public bool Eat = true;
+ /// Invoked once on the pump thread when the capture finishes for any reason.
+ public Action? OnComplete;
+}
+
+/// What a capture produced.
+internal sealed class IltChatResult
+{
+ public readonly List Lines = new();
+ /// No response line ever arrived.
+ public bool TimedOut;
+ /// The server answered "Unknown command: …" for this command.
+ public bool UnknownCommand;
+ /// The engine had no InvokeChatParser, so nothing was sent.
+ public bool NotSent;
+ public string? TerminatorLine;
+}
+
+internal sealed class IltChatCapture
+{
+ private readonly RynthCoreHost _host;
+ private readonly Queue _queue = new();
+
+ private IltChatRequest? _active;
+ private IltChatResult? _activeResult;
+ private long _sentAt;
+ private long _lastLineAt;
+
+ /// Minimum spacing between two sends so the server's own command throttles aren't tripped.
+ private const long SendSpacingMs = 400;
+ private long _lastSendAt;
+
+ private static long NowMs => Environment.TickCount64;
+
+ public IltChatCapture(RynthCoreHost host) => _host = host;
+
+ /// True while a capture is in flight or queued.
+ public bool IsBusy => _active != null || _queue.Count > 0;
+
+ /// True if a request with this exact command is queued or in flight (avoids duplicate refreshes).
+ public bool IsPending(string command)
+ {
+ if (_active != null && string.Equals(_active.Command, command, StringComparison.OrdinalIgnoreCase))
+ return true;
+ foreach (var r in _queue)
+ if (string.Equals(r.Command, command, StringComparison.OrdinalIgnoreCase))
+ return true;
+ return false;
+ }
+
+ /// Queues a capture. It is sent from once earlier captures finish.
+ public void Enqueue(IltChatRequest request)
+ {
+ _queue.Enqueue(request);
+ RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})");
+ }
+
+ /// Drops everything (logout / teardown). Pending callbacks are not invoked.
+ public void Clear()
+ {
+ if (_active != null || _queue.Count > 0)
+ RynthLog.Trace(LogCat.IltChat, $"clear: dropping active='{_active?.Command}' and {_queue.Count} queued");
+ _queue.Clear();
+ _active = null;
+ _activeResult = null;
+ }
+
+ /// Starts queued captures and finishes the active one on idle/timeout.
+ public void Tick()
+ {
+ long now = NowMs;
+ if (_active != null && _activeResult != null)
+ {
+ bool gotAny = _activeResult.Lines.Count > 0;
+ if (gotAny && now - _lastLineAt >= _active.IdleEndMs)
+ Finish();
+ else if (!gotAny && now - _sentAt >= _active.FirstLineTimeoutMs)
+ {
+ _activeResult.TimedOut = true;
+ Finish();
+ }
+ }
+
+ if (_active == null && _queue.Count > 0 && now - _lastSendAt >= SendSpacingMs)
+ StartNext(now);
+ }
+
+ ///
+ /// Feed every incoming chat line. Returns true when the line belonged to the active
+ /// capture and that capture asked for its lines to be eaten.
+ ///
+ public bool OnChatLine(string rawText)
+ {
+ if (_active == null || _activeResult == null) return false;
+ string text = rawText.Trim();
+ if (text.Length == 0) return false;
+
+ // "Unknown command: blackjack" — ACE GameActionTalk reply for unregistered commands.
+ if (text.StartsWith("Unknown command:", StringComparison.OrdinalIgnoreCase)
+ && CommandWordMatches(text.Substring("Unknown command:".Length).Trim()))
+ {
+ _activeResult.UnknownCommand = true;
+ _activeResult.Lines.Add(text);
+ bool eat = _active.Eat;
+ Finish();
+ return eat;
+ }
+
+ if (_active.IsTerminator != null && _active.IsTerminator(text))
+ {
+ _activeResult.TerminatorLine = text;
+ _activeResult.Lines.Add(text);
+ bool eat = _active.Eat;
+ Finish();
+ return eat;
+ }
+
+ if (!_active.IsResponseLine(text)) return false;
+ _activeResult.Lines.Add(text);
+ _lastLineAt = NowMs;
+ RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}");
+ return _active.Eat;
+ }
+
+ private bool CommandWordMatches(string word)
+ {
+ if (_active == null) return false;
+ // Request "/bank t p 5 Bob" → command word "bank".
+ string cmd = _active.Command.TrimStart('/', '@');
+ int sp = cmd.IndexOf(' ');
+ if (sp >= 0) cmd = cmd.Substring(0, sp);
+ return string.Equals(cmd, word, StringComparison.OrdinalIgnoreCase);
+ }
+
+ private void StartNext(long now)
+ {
+ var req = _queue.Dequeue();
+ var result = new IltChatResult();
+ if (!_host.HasInvokeChatParser)
+ {
+ RynthLog.Trace(LogCat.IltChat, $"not sent '{req.Command}': engine has no InvokeChatParser");
+ result.NotSent = true;
+ try { req.OnComplete?.Invoke(result); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
+ return;
+ }
+
+ _active = req;
+ _activeResult = result;
+ _sentAt = now;
+ _lastLineAt = now;
+ _lastSendAt = now;
+ RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})");
+ _host.InvokeChatParser(req.Command);
+ }
+
+ private void Finish()
+ {
+ var req = _active;
+ var res = _activeResult;
+ _active = null;
+ _activeResult = null;
+ if (req == null || res == null) return;
+ RynthLog.Trace(LogCat.IltChat,
+ $"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " +
+ $"unknown={res.UnknownCommand} terminator={(res.TerminatorLine != null)}");
+ try { req.OnComplete?.Invoke(res); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChunkClap.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChunkClap.cs
new file mode 100644
index 0000000..79edab0
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltChunkClap.cs
@@ -0,0 +1,282 @@
+// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
+//
+// Chunk: uses a Lugian (Aetheria) Hammer on eligible items, one at a time:
+// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
+// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and
+// max level (int 319) 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).
+// 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.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ImGuiNET;
+using RynthCore.Loot;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltChunkClap : IIltFeature
+{
+ private const long ChunkResultWaitMs = 10_000;
+ private const long ClapFirstDelayMs = 60_000;
+ private const long ClapJitterMs = 120_000;
+
+ private static readonly string[] ChunkDoneLines =
+ {
+ "You smash the aetheria with the hammer.", "The two artifacts link together effortlessly.",
+ "You successfully chunk the aetheria.", "You fail to chunk the aetheria.",
+ "The corrupted weapon is crushed into a fine powder.", "You smash the corrupted weapon with the hammer.",
+ "The corrupted weapon shatters into fragments.", "You fail to chunk the corrupted weapon.",
+ };
+ private static readonly string[] ChunkRefusedLines =
+ {
+ "The aetheria is too powerful to chunk.", "You cannot chunk this aetheria.",
+ "The corrupted weapon is too powerful to chunk.", "You cannot chunk this corrupted weapon.",
+ };
+
+ private readonly IltHubContext _ctx;
+ private readonly Random _rng = new();
+
+ // Chunk state
+ private long _lastChunkAt;
+ private int _waitingOn;
+ private long _waitStartedAt;
+ private readonly HashSet _skip = new();
+ private bool _manualPass;
+ private volatile string _chunkStatus = "idle";
+ private int _chunked;
+
+ // Clap state
+ private long _nextClapAt;
+ private volatile string _clapStatus = "idle";
+ private bool _clapWasEnabled;
+
+ public IltChunkClap(IltHubContext ctx) => _ctx = ctx;
+
+ private IltGearState G => _ctx.State.Gear;
+
+ // ── Chunk ───────────────────────────────────────────────────────────────
+
+ private WorldObject? FindHammer()
+ => _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase)
+ || n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase)
+ || n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase));
+
+ /// True/false when decidable; null when appraisal is still needed.
+ private bool? IsChunkableAetheria(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;
+ return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel);
+ }
+
+ 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;
+ }
+
+ private WorldObject? NextChunkTarget()
+ {
+ foreach (var wo in _ctx.Inventory.Items())
+ {
+ if (_skip.Contains(wo.Id)) continue;
+ if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo;
+ if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo;
+ }
+ return null;
+ }
+
+ /// Runs one chunk pass now (both item kinds) regardless of the auto toggles.
+ public void ChunkNow()
+ {
+ RynthLog.Trace(LogCat.IltGear, $"ChunkNow()");
+ _manualPass = true;
+ _lastChunkAt = 0;
+ _chunkStatus = "manual pass started";
+ }
+
+ private void TickChunk(long now)
+ {
+ if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return;
+
+ if (_waitingOn != 0)
+ {
+ if (now - _waitStartedAt < ChunkResultWaitMs) return;
+ _skip.Add(_waitingOn); // no result line — don't hammer the same item forever
+ _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;
+
+ var hammer = FindHammer();
+ if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; }
+ var target = NextChunkTarget();
+ if (target == null)
+ {
+ _chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible";
+ _manualPass = false;
+ return;
+ }
+ if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id)))
+ {
+ _waitingOn = target.Id;
+ _waitStartedAt = now;
+ _chunkStatus = "chunking " + target.Name;
+ }
+ }
+
+ // ── Clap ────────────────────────────────────────────────────────────────
+
+ 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;
+ }
+
+ /// Sends "/clap all" through the capture queue (reply stays visible).
+ public void ClapNow(bool manual)
+ {
+ 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; }
+ _clapStatus = "sending /clap all...";
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = "/clap all",
+ IsResponseLine = t => t.StartsWith("Deposited ", StringComparison.Ordinal)
+ || t.StartsWith("[Clap]", StringComparison.OrdinalIgnoreCase)
+ || t.Contains("aetheria materials", StringComparison.OrdinalIgnoreCase)
+ || t.Contains("AutoCraftingEnabled", StringComparison.OrdinalIgnoreCase),
+ IdleEndMs = 800,
+ FirstLineTimeoutMs = 10_000,
+ Eat = false,
+ OnComplete = r =>
+ {
+ if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Clap, IltTri.Off); _clapStatus = "/clap not available"; return; }
+ _clapStatus = r.Lines.Count > 0 ? r.Lines[^1] : "no reply";
+ if (r.Lines.Any(l => l.StartsWith("Deposited ", StringComparison.Ordinal))) _ctx.Options.Set(IltFeature.Clap, IltTri.On);
+ },
+ });
+ }
+
+ private void TickClap(long now)
+ {
+ // Automation only runs once the server has positively confirmed /clap (unknown = wait).
+ if (!G.AutoClap || !_ctx.Options.IsOn(IltFeature.Clap)) { _clapWasEnabled = false; return; }
+ if (!_clapWasEnabled)
+ {
+ _clapWasEnabled = true;
+ _nextClapAt = now + ClapFirstDelayMs;
+ _clapStatus = "first auto-clap in ~1 min";
+ return;
+ }
+ if (now < _nextClapAt) return;
+ long interval = Math.Max(5, G.ClapIntervalMinutes) * 60_000L;
+ _nextClapAt = now + interval + (long)((_rng.NextDouble() * 2 - 1) * ClapJitterMs);
+ ClapNow(manual: false);
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ TickChunk(nowMs);
+ TickClap(nowMs);
+ }
+
+ public bool OnChat(string text)
+ {
+ if (_waitingOn == 0) return false;
+ if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
+ {
+ _waitingOn = 0; // retry the same item next interval
+ return false;
+ }
+ if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
+ {
+ _chunked++;
+ _waitingOn = 0;
+ }
+ else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
+ {
+ _skip.Add(_waitingOn);
+ _waitingOn = 0;
+ }
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ _waitingOn = 0;
+ _skip.Clear();
+ _manualPass = false;
+ _clapWasEnabled = false;
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Chunking (Lugian Hammer)");
+ bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat;
+ if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a;
+ ImGui.SameLine();
+ if (ImGui.Checkbox("Auto-chunk corrupted weapons", ref c)) G.AutoChunkCorrupted = c;
+ if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb;
+ int under = G.ChunkAetheriaUnderLevel;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = Math.Clamp(under, 1, 6);
+ 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");
+ ImGui.TextDisabled("Status: " + _chunkStatus);
+
+ ImGui.Separator();
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Clap (/clap all)");
+ if (_ctx.Options.IsOff(IltFeature.Clap))
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "Not available (server off or AutoCraftingEnabled stamp missing).");
+ return;
+ }
+ bool ac = G.AutoClap;
+ if (ImGui.Checkbox("Auto-clap periodically", ref ac)) G.AutoClap = ac;
+ int mins = G.ClapIntervalMinutes;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins);
+ if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true));
+ ImGui.SameLine();
+ ImGui.TextDisabled(_clapStatus);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltEquipSuits.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltEquipSuits.cs
new file mode 100644
index 0000000..93e381b
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltEquipSuits.cs
@@ -0,0 +1,264 @@
+// IltEquipSuits.cs — UtilityBelt-style equipment profiles (.utl VTank loot files) (Gear tab, P2).
+//
+// A suit is a VTank loot profile: every carried wearable whose first matching rule is
+// Keep belongs to the suit. Loading a suit:
+// 1. dequip phase — equipped wearables NOT in the suit go to a pack with a free slot
+// (WorldObjectCache.FindPackFor; never into a full pack — that crashes the client);
+// 2. equip phase — suit items that aren't worn are used (AC equips on use).
+// One action per 100 ms tick and only while not busy. An item is abandoned after 15
+// attempts; the whole load bails after 10 s with no progress.
+// Search order: RynthAi EquipProfiles\, EquipProfiles, then UB's equip folders.
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using ImGuiNET;
+using RynthCore.Loot;
+using RynthCore.Loot.VTank;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Loot;
+using RynthCore.Install;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltEquipSuits : IIltFeature
+{
+ private const int MaxAttemptsPerItem = 15;
+ private const long NoProgressBailMs = 10_000;
+ private const long StepMs = 100;
+
+ private readonly IltHubContext _ctx;
+
+ // Load job (pump thread)
+ private readonly Queue _dequip = new();
+ private readonly Queue _equip = new();
+ private readonly Dictionary _attempts = new();
+ private bool _running;
+ private long _lastStep, _lastProgress;
+ private int _doneCount;
+ private volatile string _status = "idle";
+
+ // Render snapshots
+ private volatile string[] _profiles = Array.Empty();
+ private volatile string[] _preview = Array.Empty();
+ private int _selected;
+
+ public IltEquipSuits(IltHubContext ctx) => _ctx = ctx;
+
+ private static readonly AcObjectClass[] WearableClasses =
+ {
+ AcObjectClass.Armor, AcObjectClass.Clothing, AcObjectClass.Gem, AcObjectClass.Jewelry,
+ AcObjectClass.MeleeWeapon, AcObjectClass.MissileWeapon, AcObjectClass.WandStaffOrb,
+ };
+
+ // ── Profile discovery ───────────────────────────────────────────────────
+
+ private IEnumerable SearchDirs()
+ {
+ string root = Path.Combine(IltHubStore.SharedRoot, "EquipProfiles");
+ if (_ctx.CharName.Length > 0) yield return Path.Combine(root, _ctx.CharName);
+ yield return root;
+ string ub = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
+ string world = _ctx.Options.WorldName;
+ if (world.Length > 0 && _ctx.CharName.Length > 0) yield return Path.Combine(ub, world, _ctx.CharName, "equip");
+ if (world.Length > 0) yield return Path.Combine(ub, world, "equip");
+ yield return Path.Combine(ub, "equip");
+ }
+
+ /// All .utl profiles, first directory wins for duplicate names.
+ public List<(string Name, string Path)> ListProfiles()
+ {
+ var seen = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (string dir in SearchDirs())
+ {
+ try
+ {
+ if (!Directory.Exists(dir)) continue;
+ foreach (string f in Directory.GetFiles(dir, "*.utl"))
+ {
+ string n = Path.GetFileNameWithoutExtension(f);
+ if (!seen.ContainsKey(n)) seen[n] = f;
+ }
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltGear, ex, $"equip dir {dir}"); }
+ }
+ return seen.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).Select(k => (k.Key, k.Value)).ToList();
+ }
+
+ private string? ResolveProfile(string? name)
+ {
+ if (string.IsNullOrWhiteSpace(name)) name = _ctx.CharName;
+ name = name!.Trim();
+ if (name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
+ return ListProfiles().FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Path;
+ }
+
+ /// Items the suit wants worn (first matching rule is Keep).
+ private List? SuitItems(string path, out string error)
+ {
+ error = string.Empty;
+ VTankLootProfile profile;
+ try { profile = VTankLootParser.Load(path); }
+ catch (Exception ex) { error = "could not read profile: " + ex.Message; return null; }
+
+ var lootCtx = new VTankLootContext(_ctx.Host, _ctx.Inventory.PlayerId) { Cache = _ctx.Inventory.Cache };
+ var list = new List();
+ foreach (var wo in _ctx.Inventory.Items())
+ {
+ if (Array.IndexOf(WearableClasses, wo.ObjectClass) < 0) continue;
+ if (_ctx.Inventory.Int(wo, IltInventory.IntValidLocations) == 0) continue;
+ VTankLootRule? match = null;
+ foreach (var rule in profile.Rules)
+ if (VTankLootEvaluator.Match(rule, wo, lootCtx)) { match = rule; break; }
+ if (match != null && match.Action == VTankLootAction.Keep) list.Add(wo);
+ }
+ return list;
+ }
+
+ // ── Commands (pump thread) ──────────────────────────────────────────────
+
+ public void RefreshProfileList() => _profiles = ListProfiles().Select(p => p.Name).ToArray();
+
+ /// Lists what a load would do without doing it. Returns lines (also shown in the UI).
+ public List Test(string? name)
+ {
+ var lines = new List();
+ string? path = ResolveProfile(name);
+ if (path == null) { lines.Add($"Profile not found: {name ?? _ctx.CharName}"); _preview = lines.ToArray(); return lines; }
+ var suit = SuitItems(path, out string err);
+ if (suit == null) { lines.Add(err); _preview = lines.ToArray(); return lines; }
+ var suitIds = suit.Select(s => s.Id).ToHashSet();
+ foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
+ && Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
+ lines.Add("dequip " + wo.Name);
+ foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) lines.Add("equip " + wo.Name);
+ if (lines.Count == 0) lines.Add("Already wearing this suit.");
+ _preview = lines.ToArray();
+ return lines;
+ }
+
+ /// Starts loading a suit.
+ public string Load(string? name)
+ {
+ RynthLog.Trace(LogCat.IltGear, $"Suits.Load(name='{name}')");
+ if (_running) return "A suit load is already running.";
+ if (!_ctx.Host.HasMoveItemInternal || !_ctx.Host.HasUseObject) return "Engine lacks MoveItemInternal/UseObject.";
+ string? path = ResolveProfile(name);
+ if (path == null) return $"Profile not found: {name ?? _ctx.CharName}";
+ var suit = SuitItems(path, out string err);
+ if (suit == null) return err;
+
+ var suitIds = suit.Select(s => s.Id).ToHashSet();
+ _dequip.Clear(); _equip.Clear(); _attempts.Clear();
+ foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
+ && Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
+ _dequip.Enqueue(wo.Id);
+ foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) _equip.Enqueue(wo.Id);
+
+ if (_dequip.Count + _equip.Count == 0) return "Already wearing this suit.";
+ _running = true;
+ _doneCount = 0;
+ _lastProgress = IltHubContext.NowMs;
+ _ctx.State.Gear.LastEquipProfile = Path.GetFileNameWithoutExtension(path);
+ _status = $"loading {Path.GetFileNameWithoutExtension(path)}: {_dequip.Count} off, {_equip.Count} on";
+ return _status;
+ }
+
+ public void Cancel(string why)
+ {
+ RynthLog.Trace(LogCat.IltGear, $"Suits.Cancel(why='{why}')");
+ _running = false;
+ _dequip.Clear();
+ _equip.Clear();
+ _status = why;
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ if (!_running || nowMs - _lastStep < StepMs) return;
+ _lastStep = nowMs;
+ if (nowMs - _lastProgress > NoProgressBailMs) { Cancel($"no progress for 10 s - stopped ({_doneCount} done)"); return; }
+ if (_ctx.Inventory.IsBusy) return;
+
+ var cache = _ctx.Inventory.Cache;
+ if (cache == null) { Cancel("cache not ready"); return; }
+
+ // Dequip phase first so slots are free for the suit.
+ if (_dequip.Count > 0)
+ {
+ int id = _dequip.Peek();
+ var wo = cache[id];
+ if (wo == null || !_ctx.Inventory.IsEquipped(wo)) { _dequip.Dequeue(); Progress(nowMs); return; }
+ if (!Attempt(id)) { _dequip.Dequeue(); return; }
+ int pack = WorldObjectCache.FindPackFor(_ctx.Host, cache, includeMainPack: true, requireFree: 1);
+ if (pack == 0) { Cancel("no free pack slot for dequipped items - stopped"); return; }
+ _ctx.Host.MoveItemInternal(unchecked((uint)id), unchecked((uint)pack), 0, Math.Max(1, _ctx.Inventory.StackSize(wo)));
+ return;
+ }
+
+ if (_equip.Count > 0)
+ {
+ int id = _equip.Peek();
+ var wo = cache[id];
+ if (wo == null || _ctx.Inventory.IsEquipped(wo)) { _equip.Dequeue(); Progress(nowMs); return; }
+ if (!Attempt(id)) { _equip.Dequeue(); return; }
+ _ctx.Inventory.Use(wo);
+ return;
+ }
+
+ _running = false;
+ _status = $"suit loaded ({_doneCount} changes)";
+ }
+
+ /// Counts an attempt; false once the item has used up its attempts.
+ private bool Attempt(int id)
+ {
+ int n = _attempts.TryGetValue(id, out int a) ? a + 1 : 1;
+ _attempts[id] = n;
+ return n <= MaxAttemptsPerItem;
+ }
+
+ private void Progress(long now)
+ {
+ _doneCount++;
+ _lastProgress = now;
+ }
+
+ public bool OnChat(string text) => false;
+ public void OnLogout() => Cancel("idle");
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Equipment suits (.utl)");
+ if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList);
+ var profiles = _profiles;
+ if (profiles.Length == 0)
+ {
+ ImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "EquipProfiles")} or UtilityBelt equip folders).");
+ }
+ else
+ {
+ _selected = Math.Clamp(_selected, 0, profiles.Length - 1);
+ ImGui.SetNextItemWidth(220);
+ ImGui.Combo("Suit", ref _selected, profiles, profiles.Length);
+ string pick = profiles[_selected];
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Test")) _ctx.Post(() => Test(pick));
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Load..."))
+ _ctx.Confirm("Load equipment suit", $"Swap to suit '{pick}'?\nItems not in the suit are moved to your packs.",
+ () => _ctx.Chat("[ILT Hub] " + Load(pick)), "Load");
+ if (_running)
+ {
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player"));
+ }
+ }
+ ImGui.TextDisabled("Status: " + _status);
+ foreach (string l in _preview) ImGui.BulletText(l);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGames.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGames.cs
new file mode 100644
index 0000000..3de6d8d
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGames.cs
@@ -0,0 +1,254 @@
+// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball.
+//
+// Every bet / ticket purchase spends banked luminance, so each one needs a confirm.
+// Blackjack is commented out on the current ACECustom build ("Unknown command:
+// blackjack"); the pad only appears when the login probe found the command.
+// /blackjack , /hit, /stand, /double, /split (fellowship: /fblackjack, /fhit, ...; max 100B)
+// /pb (info), /pb buy <1-500>, /pb tickets
+// The HUD is a small always-on-top window shown while a hand is in progress.
+using System;
+using System.Collections.Generic;
+using System.Numerics;
+using System.Text.RegularExpressions;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltGames : IIltFeature
+{
+ private const long FBlackjackMaxBet = 100_000_000_000;
+ private static readonly Regex Dealt = new(@"^You were dealt (?:a |an )?(?.+?)\.$", RegexOptions.Compiled);
+ private static readonly Regex MyValue = new(@"Your (?:initial )?hand value is (?:now )?(?\d+)", RegexOptions.Compiled);
+ private static readonly Regex DealerValue = new(@"Rand's (?:current )?hand value is (?\d+)", RegexOptions.Compiled);
+
+ private readonly IltHubContext _ctx;
+
+ // Hand state (pump thread writes, render thread reads — simple fields / snapshot list)
+ private volatile bool _handActive;
+ private volatile bool _fellowshipHand;
+ private volatile string[] _cards = Array.Empty();
+ private volatile int _myValue, _dealerValue;
+ private volatile string _lastResult = string.Empty;
+
+ // Powerball info
+ private volatile string _pbDraw = string.Empty, _pbJackpot = string.Empty, _pbPrice = string.Empty, _pbStatus = string.Empty;
+
+ // Render-thread input
+ private string _bjBetText = string.Empty, _fbjBetText = string.Empty;
+
+ public IltGames(IltHubContext ctx) => _ctx = ctx;
+
+ private IltGamesState S => _ctx.State.Games;
+
+ public bool AnyGameAvailable => _ctx.Options.IsOn(IltFeature.Blackjack) || _ctx.Options.IsOn(IltFeature.FBlackjack)
+ || !_ctx.Options.IsOff(IltFeature.Powerball);
+
+ // ── Commands (pump thread) ──────────────────────────────────────────────
+
+ private void Send(string cmd)
+ {
+ if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd);
+ }
+
+ private void StartBlackjack(bool fellowship, long bet)
+ {
+ _fellowshipHand = fellowship;
+ _cards = Array.Empty();
+ _myValue = _dealerValue = 0;
+ _lastResult = string.Empty;
+ Send($"/{(fellowship ? "fblackjack" : "blackjack")} {bet}");
+ }
+
+ private void HandAction(string verb) => Send("/" + (_fellowshipHand ? "f" : "") + verb);
+
+ public void RequestPowerballInfo()
+ {
+ RynthLog.Trace(LogCat.IltGames, $"RequestPowerballInfo()");
+ if (_ctx.Options.IsOff(IltFeature.Powerball) || _ctx.Capture.IsPending("/pb")) return;
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = "/pb",
+ IsResponseLine = t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase),
+ IdleEndMs = 1200,
+ FirstLineTimeoutMs = 8000,
+ Eat = true,
+ OnComplete = r =>
+ {
+ if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Powerball, IltTri.Off); return; }
+ if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Powerball, IltTri.On);
+ foreach (string l in r.Lines) ParsePowerball(l);
+ RynthLog.Trace(LogCat.IltGames, $"/pb info: {r.Lines.Count} line(s), timedOut={r.TimedOut}");
+ _pbStatus = r.Lines.Count > 0 ? "updated " + DateTime.Now.ToString("t") : "no reply";
+ },
+ });
+ }
+
+ private void ParsePowerball(string l)
+ {
+ string t = l.Trim();
+ if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)) _pbDraw = t;
+ else if (t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)) _pbJackpot = t;
+ else if (t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase)) _pbPrice = t;
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs) { }
+
+ public bool OnChat(string text)
+ {
+ // Powerball lines typed by the player still update the panel.
+ if (text.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase))
+ {
+ if (text.Contains("You bought", StringComparison.OrdinalIgnoreCase) || text.Contains("Insufficient", StringComparison.OrdinalIgnoreCase))
+ _pbStatus = text;
+ return false;
+ }
+ string t = text.Trim();
+ if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase))
+ {
+ ParsePowerball(t);
+ return false;
+ }
+
+ // Blackjack
+ var d = Dealt.Match(text);
+ if (d.Success)
+ {
+ var list = new List(_cards) { d.Groups["card"].Value };
+ _cards = list.ToArray();
+ _handActive = true;
+ return false;
+ }
+ var mv = MyValue.Match(text);
+ if (mv.Success) { _myValue = int.Parse(mv.Groups["v"].Value); _handActive = true; }
+ var dv = DealerValue.Match(text);
+ if (dv.Success) _dealerValue = int.Parse(dv.Groups["v"].Value);
+ if (text.StartsWith("The game begins!", StringComparison.OrdinalIgnoreCase)) _handActive = true;
+
+ if (text.StartsWith("Blackjack! You win", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You won with", StringComparison.OrdinalIgnoreCase)
+ || text.StartsWith("You tied with Rand", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You lost with", StringComparison.OrdinalIgnoreCase)
+ || text.StartsWith("You busted", StringComparison.OrdinalIgnoreCase))
+ _lastResult = text;
+ if (text.StartsWith("The blackjack game has ended", StringComparison.OrdinalIgnoreCase)
+ || text.StartsWith("You are not currently in a blackjack game", StringComparison.OrdinalIgnoreCase))
+ _handActive = false;
+ if (text.StartsWith("You don't have enough luminance to place this bet", StringComparison.OrdinalIgnoreCase))
+ {
+ _lastResult = text;
+ _handActive = false;
+ }
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ _handActive = false;
+ _cards = Array.Empty();
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ bool bj = _ctx.Options.IsOn(IltFeature.Blackjack), fbj = _ctx.Options.IsOn(IltFeature.FBlackjack);
+ if (!bj && !fbj && _ctx.Options.IsOff(IltFeature.Powerball))
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "No games are enabled on this server.");
+ return;
+ }
+ bool hud = _ctx.State.GamesHudVisible;
+ if (ImGui.Checkbox("Show hand HUD while playing", ref hud)) _ctx.State.GamesHudVisible = hud;
+
+ if (bj && ImGui.CollapsingHeader("Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(false, ref _bjBetText);
+ if (fbj && ImGui.CollapsingHeader("Fellowship Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(true, ref _fbjBetText);
+ if (!bj && !fbj) ImGui.TextDisabled("Blackjack is not enabled on this server.");
+ if (!_ctx.Options.IsOff(IltFeature.Powerball) && ImGui.CollapsingHeader("Powerball", ImGuiTreeNodeFlags.DefaultOpen)) RenderPowerball();
+ }
+
+ private void RenderBlackjack(bool fellowship, ref string betText)
+ {
+ string id = fellowship ? "fbj" : "bj";
+ if (betText.Length == 0) betText = IltParse.Compact(fellowship ? S.FellowshipBlackjackBet : S.BlackjackBet).ToLowerInvariant();
+ ImGui.SetNextItemWidth(160);
+ ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u);
+ bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet);
+ ImGui.SameLine();
+ ImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid");
+
+ ImGui.BeginDisabled(!ok || _handActive);
+ if (ImGui.Button($"Deal...##{id}"))
+ {
+ long b = bet;
+ if (fellowship) S.FellowshipBlackjackBet = b; else S.BlackjackBet = b;
+ _ctx.Confirm(fellowship ? "Fellowship Blackjack" : "Blackjack",
+ $"Bet {IltParse.N0(b)} banked luminance on a new hand?", () => StartBlackjack(fellowship, b), "Bet");
+ }
+ ImGui.EndDisabled();
+
+ if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id);
+ if (_lastResult.Length > 0 && _fellowshipHand == fellowship) ImGui.TextWrapped(_lastResult);
+ }
+
+ private void RenderHandButtons(string id)
+ {
+ ImGui.TextUnformatted($"Hand: {string.Join(", ", _cards)} ({_myValue}) Rand: {(_dealerValue > 0 ? _dealerValue.ToString() : "?")}");
+ if (ImGui.Button($"Hit##{id}")) _ctx.Post(() => HandAction("hit"));
+ ImGui.SameLine();
+ if (ImGui.Button($"Stand##{id}")) _ctx.Post(() => HandAction("stand"));
+ ImGui.SameLine();
+ if (ImGui.Button($"Double...##{id}"))
+ _ctx.Confirm("Double down", "Double your bet on this hand?", () => HandAction("double"), "Double");
+ ImGui.SameLine();
+ if (ImGui.Button($"Split...##{id}"))
+ _ctx.Confirm("Split", "Split this hand (places a second bet)?", () => HandAction("split"), "Split");
+ }
+
+ private void RenderPowerball()
+ {
+ if (ImGui.SmallButton("Refresh##pb")) _ctx.Post(RequestPowerballInfo);
+ ImGui.SameLine();
+ if (ImGui.SmallButton("My tickets")) _ctx.Post(() => Send("/pb tickets"));
+ if (_pbDraw.Length > 0) ImGui.TextUnformatted(_pbDraw);
+ if (_pbJackpot.Length > 0) ImGui.TextUnformatted(_pbJackpot);
+ if (_pbPrice.Length > 0) ImGui.TextUnformatted(_pbPrice);
+ // Buying spends banked luminance, so it needs a positive server confirmation of /pb.
+ if (!_ctx.Options.IsOn(IltFeature.Powerball))
+ {
+ ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh).");
+ if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
+ return;
+ }
+ int qty = S.PowerballQuantity;
+ ImGui.SetNextItemWidth(120);
+ if (ImGui.InputInt("Tickets", ref qty)) S.PowerballQuantity = Math.Clamp(qty, 1, 500);
+ ImGui.SameLine();
+ if (ImGui.Button("Buy..."))
+ {
+ int q = S.PowerballQuantity;
+ _ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}",
+ () => Send($"/pb buy {q}"), "Buy");
+ }
+ if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
+ }
+
+ /// Small HUD with the current hand; called every frame by the Hub UI.
+ public void RenderHud()
+ {
+ if (!_handActive || !_ctx.State.GamesHudVisible) return;
+ ImGui.SetNextWindowSize(new Vector2(300, 0), ImGuiCond.FirstUseEver);
+ bool open = true;
+ if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse))
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
+ RenderHandButtons("hud");
+ }
+ ImGui.End();
+ if (!open) _ctx.State.GamesHudVisible = false;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGear.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGear.cs
new file mode 100644
index 0000000..2b92854
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGear.cs
@@ -0,0 +1,155 @@
+// IltGear.cs — ILT Hub "Gear" tab: charm strip (incl. Guardian Hand) plus the gear tools.
+//
+// Charm strip: every carried ACECustom charm with its ON/OFF state (from the appraisal
+// Use text) and a toggle (using a charm flips it). Charms the server reports disabled are
+// shown greyed out. Guardian Hand has no published WCID yet, so it is matched by name
+// ("guardian" + "hand") unless a WCID is configured in the Hub.
+// The remaining sections are separate modules (buff keepers, chunk/clap, split arrows,
+// equipment suits, VTank import) that this tab just lays out.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltGear : IIltFeature
+{
+ private readonly IltHubContext _ctx;
+ public IltBuffKeepers Keepers { get; }
+ public IltChunkClap ChunkClap { get; }
+ public IltSplitArrows Split { get; }
+ public IltEquipSuits Suits { get; }
+ public IltUsdImporter Usd { get; }
+
+ private sealed record CharmRow(int Id, string Name, IltTri Status, bool ServerDisabled, bool IsGuardianHand);
+ private volatile CharmRow[] _charms = Array.Empty();
+ private long _lastCharmScan;
+
+ public IltGear(IltHubContext ctx)
+ {
+ _ctx = ctx;
+ Keepers = new IltBuffKeepers(ctx);
+ ChunkClap = new IltChunkClap(ctx);
+ Split = new IltSplitArrows(ctx);
+ Suits = new IltEquipSuits(ctx);
+ Usd = new IltUsdImporter(ctx);
+ }
+
+ private IltGearState G => _ctx.State.Gear;
+
+ private bool IsGuardianHand(WorldObject wo)
+ {
+ if (G.GuardianHandWcid != 0 && _ctx.Inventory.Wcid(wo) == G.GuardianHandWcid) return true;
+ string want = string.IsNullOrWhiteSpace(G.GuardianHandName) ? "Guardian Hand" : G.GuardianHandName.Trim();
+ return wo.Name.Contains(want, StringComparison.OrdinalIgnoreCase)
+ || (wo.Name.Contains("guardian", StringComparison.OrdinalIgnoreCase) && wo.Name.Contains("hand", StringComparison.OrdinalIgnoreCase));
+ }
+
+ private void ScanCharms()
+ {
+ var inv = _ctx.Inventory;
+ var rows = new List();
+ var seen = new HashSet();
+ foreach (var wo in inv.CarriedCharms().Concat(inv.Items().Where(IsGuardianHand)))
+ {
+ if (!seen.Add(wo.Id)) continue;
+ bool gh = IsGuardianHand(wo);
+ string defName = gh ? "Guardian Hand" : inv.CharmDefFor(wo)?.Name ?? wo.Name;
+ rows.Add(new CharmRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm(defName)), gh));
+ }
+ _charms = rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
+ }
+
+ /// Uses (toggles) a charm (pump thread).
+ private void ToggleCharm(int id)
+ {
+ var wo = _ctx.Inventory.Cache?[id];
+ if (wo == null) return;
+ if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy - try the charm again in a moment."); return; }
+ _ctx.Inventory.Use(wo);
+ _lastCharmScan = 0; // re-read status soon (appraisal refresh is throttled per item)
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ if (_ctx.WindowOpen && nowMs - _lastCharmScan >= 3000)
+ {
+ _lastCharmScan = nowMs;
+ ScanCharms();
+ }
+ Keepers.Tick(nowMs);
+ ChunkClap.Tick(nowMs);
+ Split.Tick(nowMs);
+ Suits.Tick(nowMs);
+ }
+
+ public bool OnChat(string text)
+ {
+ bool eat = Keepers.OnChat(text);
+ eat |= ChunkClap.OnChat(text);
+ eat |= Split.OnChat(text);
+ eat |= Suits.OnChat(text);
+ return eat;
+ }
+
+ public void OnLogout()
+ {
+ Keepers.OnLogout();
+ ChunkClap.OnLogout();
+ Split.OnLogout();
+ Suits.OnLogout();
+ _charms = Array.Empty();
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ if (ImGui.CollapsingHeader("Charms", ImGuiTreeNodeFlags.DefaultOpen)) RenderCharms();
+ if (ImGui.CollapsingHeader("Dispel / Surging Strength")) Keepers.Render();
+ if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render();
+ if (ImGui.CollapsingHeader("Split arrows")) Split.Render();
+ if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render();
+ if (ImGui.CollapsingHeader("VirindiTank import")) Usd.Render();
+ }
+
+ private void RenderCharms()
+ {
+ var rows = _charms;
+ if (rows.Length == 0) ImGui.TextDisabled("No charms carried.");
+ foreach (var r in rows)
+ {
+ ImGui.PushID(r.Id);
+ if (r.ServerDisabled)
+ {
+ ImGui.TextDisabled($"{r.Name} - disabled on this server");
+ ImGui.PopID();
+ continue;
+ }
+ var col = r.Status == IltTri.On ? LegacyDashboardRenderer.ColGreen
+ : r.Status == IltTri.Off ? LegacyDashboardRenderer.ColTextMute : LegacyDashboardRenderer.ColAmber;
+ ImGui.TextColored(col, r.Status == IltTri.On ? "ON " : r.Status == IltTri.Off ? "OFF" : " ? ");
+ ImGui.SameLine();
+ ImGui.TextUnformatted(r.Name);
+ ImGui.SameLine();
+ int id = r.Id;
+ if (ImGui.SmallButton("Toggle")) _ctx.Post(() => ToggleCharm(id));
+ ImGui.PopID();
+ }
+
+ if (ImGui.TreeNode("Guardian Hand matching"))
+ {
+ string name = G.GuardianHandName;
+ ImGui.SetNextItemWidth(200);
+ if (ImGui.InputText("Name contains", ref name, 64u)) G.GuardianHandName = name;
+ int wcid = unchecked((int)G.GuardianHandWcid);
+ ImGui.SetNextItemWidth(140);
+ if (ImGui.InputInt("WCID (0 = name only)", ref wcid, 0)) G.GuardianHandWcid = unchecked((uint)Math.Max(0, wcid));
+ ImGui.TreePop();
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardian.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardian.cs
new file mode 100644
index 0000000..f7d9e1c
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardian.cs
@@ -0,0 +1,571 @@
+// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window).
+//
+// * Riddle translator: incoming "Guardian of ... tells you / says" lines (when chat auto-detect
+// is on) and pasted text go through IltGuardianPhrasebook; the answer shows here and on the
+// Mini Remote.
+// * Hand-in: gives one of the answer item to the guardian (GiveObjectTo). For the Temple
+// guardian, when none is carried and "buy missing" is on, it first buys one from the open or
+// nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the
+// client busy state is respected between steps.
+// * Attribute tracker: IltTempleAttributes.
+//
+// Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields
+// and posts actions through IltHubContext.Post.
+using System;
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Loot;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Meta;
+using RynthCore.Plugin.Shared;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltGuardian : IIltFeature
+{
+ /// The same guardian + answer from chat within this window is one prompt (tells repeat lines).
+ private const long DebounceMs = 2500;
+ private const long HandInTimeoutMs = 45_000;
+ private const long VendorOpenTimeoutMs = 10_000;
+ private const long BuyTimeoutMs = 10_000;
+ private const long ItemArriveTimeoutMs = 8_000;
+ private const long BusyRetryMs = 400;
+ private const int MaxGiveAttempts = 5;
+ /// How far (meters) to look for the guardian and a vendor.
+ private const double SearchRangeMeters = 60.0;
+ ///
+ /// PublicWeenieDesc BF_VENDOR. The world cache files vendors as creatures (Monster / Npc), never
+ /// AcObjectClass.Vendor, so vendors are recognised by this weenie flag.
+ ///
+ private const uint BfVendor = 0x200;
+ /// The Mini Remote shows the last answer for this long.
+ public static readonly TimeSpan AnswerShownFor = TimeSpan.FromMinutes(10);
+
+ private enum Step { Idle, FindItem, OpenVendor, WaitVendor, Buy, WaitBuy, WaitItem, Give }
+
+ private readonly IltHubContext _ctx;
+ private string _lastFingerprint = string.Empty;
+ private long _lastEmitAt;
+
+ // Last prompt (written on the pump thread, read by the render thread).
+ private volatile string _lastLine = string.Empty;
+ private volatile string _lastAnswer = string.Empty;
+ private volatile string _lastNpc = string.Empty;
+ private long _lastAnswerTicksUtc;
+ private volatile string _handInStatus = "idle";
+
+ // Hand-in state machine (pump thread only).
+ private Step _step = Step.Idle;
+ private string _item = string.Empty;
+ private string _npc = string.Empty;
+ private bool _asked;
+ private long _startedAt;
+ private long _stepDeadline;
+ private long _nextStepAt;
+ private uint _vendorId;
+ private uint _buyRequest;
+ private int _giveAttempts;
+
+ // Render-thread UI state.
+ private string _input = string.Empty;
+
+ public IltGuardian(IltHubContext ctx, Func tracker, IltQuests quests)
+ {
+ _ctx = ctx;
+ Attributes = new IltTempleAttributes(ctx, tracker, quests);
+ }
+
+ public IltTempleAttributes Attributes { get; }
+
+ private IltGuardianState S => _ctx.State.Guardian;
+
+ /// Last answer item ("" until a guardian prompt was translated).
+ public string LastAnswer => _lastAnswer;
+ /// Guardian the last answer goes to.
+ public string LastNpc => _lastNpc;
+ /// The hand-in sequence is running.
+ public bool HandInRunning => _step != Step.Idle;
+ public string HandInStatus => _handInStatus;
+
+ /// Time since the last answer (MaxValue when there is none).
+ public TimeSpan LastAnswerAge
+ {
+ get
+ {
+ long t = System.Threading.Interlocked.Read(ref _lastAnswerTicksUtc);
+ return t == 0 ? TimeSpan.MaxValue : DateTime.UtcNow - new DateTime(t, DateTimeKind.Utc);
+ }
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ Attributes.Tick(nowMs);
+ StepHandIn(nowMs);
+ }
+
+ public bool OnChat(string text)
+ {
+ if (!S.AutoDetectFromChat || !IltGuardianPhrasebook.LooksLikeIncomingGuardianLine(text)) return false;
+ _lastLine = text.Trim();
+ string answer = IltGuardianPhrasebook.Translate(text);
+ if (!IltGuardianPhrasebook.IsAnswer(answer)) return false;
+
+ string npc = IltGuardianPhrasebook.TurnInNpcFromLine(text);
+ long now = IltHubContext.NowMs;
+ string fingerprint = npc + "|" + answer;
+ if (fingerprint == _lastFingerprint && now - _lastEmitAt < DebounceMs) return false;
+ _lastFingerprint = fingerprint;
+ _lastEmitAt = now;
+
+ SetAnswer(answer, npc);
+ _ctx.Chat($"[ILT Guardian] {npc} wants: {answer}");
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] chat answer '{answer}' for {npc}");
+ if (S.AutoHandIn) StartHandIn(answer, npc, asked: false);
+ return false; // never hide the guardian's own lines
+ }
+
+ public void OnLogout()
+ {
+ StopHandIn("stopped (logout)");
+ Attributes.OnLogout();
+ }
+
+ private void SetAnswer(string answer, string npc)
+ {
+ _lastAnswer = answer;
+ _lastNpc = npc;
+ System.Threading.Interlocked.Exchange(ref _lastAnswerTicksUtc, DateTime.UtcNow.Ticks);
+ }
+
+ /// Translates pasted text; a real answer becomes the current answer. Pump thread.
+ public string TranslateManual(string text)
+ {
+ string answer = IltGuardianPhrasebook.Translate(text);
+ if (!IltGuardianPhrasebook.IsAnswer(answer)) return answer;
+ string npc = IltGuardianPhrasebook.TurnInNpcFromInput(text);
+ _lastLine = text.Trim();
+ SetAnswer(answer, npc);
+ return $"{answer} (give to {npc})";
+ }
+
+ // ── Hand-in ─────────────────────────────────────────────────────────────
+
+ /// Starts giving to . Pump thread.
+ public string StartHandIn(string item, string npc, bool asked)
+ {
+ if (!IltGuardianPhrasebook.IsAnswer(item)) return "No answer to hand in yet.";
+ if (!_ctx.Host.HasGiveObjectTo) return SetStatus("can't give items: update the RynthCore engine (API v62+).");
+ _item = item;
+ _npc = string.IsNullOrWhiteSpace(npc) ? IltGuardianPhrasebook.AttributeGuardian : npc;
+ _asked = asked;
+ _startedAt = IltHubContext.NowMs;
+ _nextStepAt = 0;
+ _vendorId = 0;
+ _buyRequest = 0;
+ _giveAttempts = 0;
+ _step = Step.FindItem;
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in start: '{_item}' -> {_npc} ({(asked ? "asked" : "auto")})");
+ return SetStatus($"handing {_item} to {_npc}...");
+ }
+
+ /// Stops a running hand-in.
+ public void StopHandIn(string why = "stopped")
+ {
+ if (_step == Step.Idle) return;
+ _step = Step.Idle;
+ SetStatus(why);
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in {why}");
+ }
+
+ private string SetStatus(string text)
+ {
+ _handInStatus = text;
+ return text;
+ }
+
+ private void Fail(string why)
+ {
+ _step = Step.Idle;
+ SetStatus("failed: " + why);
+ _ctx.Chat($"[ILT Guardian] Hand-in failed: {why}");
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in failed: {why}");
+ }
+
+ private void Next(Step step, long nowMs, long timeoutMs = 0)
+ {
+ _step = step;
+ _stepDeadline = timeoutMs > 0 ? nowMs + timeoutMs : 0;
+ }
+
+ private void StepHandIn(long nowMs)
+ {
+ if (_step == Step.Idle || nowMs < _nextStepAt) return;
+ if (nowMs - _startedAt > HandInTimeoutMs) { Fail("timed out"); return; }
+ if (_stepDeadline != 0 && nowMs > _stepDeadline) { Fail(TimeoutText(_step)); return; }
+
+ var host = _ctx.Host;
+ switch (_step)
+ {
+ case Step.FindItem:
+ if (FindHandInItem() != null) { Next(Step.Give, nowMs); break; }
+ if (!IsTempleGuardian(_npc) || !S.BuyMissingFromVendor) { LogItemNearMisses(); Fail($"no {_item} in your packs"); break; }
+ Next(Step.OpenVendor, nowMs);
+ break;
+
+ case Step.OpenVendor:
+ {
+ if (!host.HasVendorTrade) { Fail($"no {_item} carried and vendor buying needs a newer RynthCore engine"); break; }
+ if (host.TryGetVendorInfo(out var open)) { _vendorId = open.VendorId; Next(Step.Buy, nowMs); break; }
+ var vendor = Nearest(IsVendor);
+ if (vendor == null) { LogVendorSearch(); Fail($"no {_item} carried and no vendor within {SearchRangeMeters:0} m"); break; }
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] vendor for '{_item}': {vendor.Name} 0x{(uint)vendor.Id:X8}");
+ SetStatus($"opening {vendor.Name} to buy {_item}...");
+ host.UseFor(unchecked((uint)vendor.Id), "IltGuardian", $"buy {_item} for the Temple guardian",
+ _asked ? UseKind.Asked : UseKind.Auto);
+ Next(Step.WaitVendor, nowMs, VendorOpenTimeoutMs);
+ break;
+ }
+
+ case Step.WaitVendor:
+ if (host.TryGetVendorInfo(out var info) && info.ItemCount > 0) { _vendorId = info.VendorId; Next(Step.Buy, nowMs); }
+ break;
+
+ case Step.Buy:
+ {
+ if (!host.TryGetVendorInfo(out var v)) { Fail("the vendor closed"); break; }
+ if (v.TradeInFlight) { _nextStepAt = nowMs + BusyRetryMs; break; }
+ string want = NormalizeName(_item);
+ var match = host.GetVendorItems().FirstOrDefault(i => NormalizeName(i.Name) == want);
+ if (match == null) { Fail($"{v.Name} doesn't sell {_item}"); break; }
+ _buyRequest = host.VendorBuy(match.ObjectId, 1, v.VendorId);
+ if (_buyRequest == 0)
+ {
+ string why = host.TryGetVendorTradeStatus(out var st) && st.Message.Length > 0 ? st.Message : "refused";
+ Fail($"couldn't buy {_item}: {why}");
+ break;
+ }
+ SetStatus($"buying {_item} from {v.Name}...");
+ Next(Step.WaitBuy, nowMs, BuyTimeoutMs);
+ break;
+ }
+
+ case Step.WaitBuy:
+ if (!host.TryGetVendorTradeStatus(out var status) || status.RequestId != _buyRequest || !status.IsFinished) break;
+ if (!status.Succeeded) { Fail($"couldn't buy {_item}: {(status.Message.Length > 0 ? status.Message : status.Result.ToString())}"); break; }
+ Next(Step.WaitItem, nowMs, ItemArriveTimeoutMs);
+ break;
+
+ case Step.WaitItem:
+ if (FindHandInItem() != null) Next(Step.Give, nowMs);
+ break;
+
+ case Step.Give:
+ GiveStep(nowMs);
+ break;
+ }
+ }
+
+ private void GiveStep(long nowMs)
+ {
+ if (_ctx.Inventory.IsBusy)
+ {
+ SetStatus("waiting for the client (busy)...");
+ _nextStepAt = nowMs + BusyRetryMs;
+ return;
+ }
+ var item = FindHandInItem();
+ if (item == null) { LogItemNearMisses(); Fail($"no {_item} in your packs"); return; }
+ var npc = Nearest(wo => wo.Name.Contains(_npc, StringComparison.OrdinalIgnoreCase));
+ if (npc == null) { Fail($"{_npc} isn't nearby"); return; }
+
+ int stack = _ctx.Inventory.StackSize(item);
+ bool ok = _ctx.Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)npc.Id), stack > 1 ? 1 : 0);
+ RynthLog.Write(LogCat.IltHub, $"[IltGuardian] give '{item.Name}' 0x{(uint)item.Id:X8} (stack {stack}) -> {npc.Name} 0x{(uint)npc.Id:X8}: {ok}");
+ if (ok)
+ {
+ _step = Step.Idle;
+ SetStatus($"gave {item.Name} to {npc.Name}");
+ _ctx.Chat($"[ILT Guardian] Gave {item.Name} to {npc.Name}.");
+ return;
+ }
+ if (++_giveAttempts >= MaxGiveAttempts) { Fail("the give was refused"); return; }
+ _nextStepAt = nowMs + BusyRetryMs;
+ }
+
+ private static string TimeoutText(Step step) => step switch
+ {
+ Step.WaitVendor => "the vendor didn't open",
+ Step.WaitBuy => "the vendor didn't answer the purchase",
+ Step.WaitItem => "the bought item didn't arrive",
+ _ => "timed out",
+ };
+
+ private static bool IsTempleGuardian(string npc) =>
+ npc.Contains(IltGuardianPhrasebook.TempleGuardian, StringComparison.OrdinalIgnoreCase);
+
+ ///
+ /// A carried (not wielded) item named like the answer (case and spacing ignored). Reads AC's
+ /// live container contents: the cache's inventory set lags a purchase and also holds the open
+ /// vendor's stock, which can't be given.
+ ///
+ private WorldObject? FindHandInItem()
+ {
+ string want = NormalizeName(_item);
+ return CarriedItems().FirstOrDefault(wo => NormalizeName(wo.Name) == want && !_ctx.Inventory.IsEquipped(wo));
+ }
+
+ /// Live walk of the player's pack and side packs (falls back to the cache without the engine call).
+ private System.Collections.Generic.IReadOnlyList CarriedItems()
+ => _ctx.Inventory.Cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty();
+
+ /// Lower-case, trimmed, single-spaced name for comparisons.
+ private static string NormalizeName(string name)
+ => string.Join(' ', (name ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
+
+ /// Logs carried items sharing a word with the answer, so a name mismatch shows in the log.
+ private void LogItemNearMisses()
+ {
+ var items = CarriedItems();
+ var words = NormalizeName(_item).Split(' ').Where(w => w.Length > 3).ToArray();
+ var similar = items.Where(wo => words.Any(w => wo.Name.Contains(w, StringComparison.OrdinalIgnoreCase)))
+ .Take(8).Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8}").ToArray();
+ RynthLog.Write(LogCat.IltHub,
+ $"[IltGuardian] no '{_item}' among {items.Count} carried items; similar names: {(similar.Length > 0 ? string.Join(", ", similar) : "none")}");
+ }
+
+ /// A vendor (weenie BF_VENDOR flag, or a cache entry already classed Vendor).
+ private bool IsVendor(WorldObject wo)
+ {
+ if (wo.ObjectClass == AcObjectClass.Vendor) return true;
+ var host = _ctx.Host;
+ return host.HasGetObjectBitfield && host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) && (bf & BfVendor) != 0;
+ }
+
+ /// Logs every vendor the cache sees with its distance (vendor search found none in range).
+ private void LogVendorSearch()
+ {
+ var cache = _ctx.Inventory.Cache;
+ int playerId = unchecked((int)_ctx.Inventory.PlayerId);
+ if (cache == null || playerId == 0) { RynthLog.Write(LogCat.IltHub, "[IltGuardian] vendor search: no world cache / player"); return; }
+ var landscape = cache.GetLandscapeObjects().ToList();
+ var vendors = landscape.Where(IsVendor).Take(8)
+ .Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8} {cache.Distance(playerId, wo.Id):0.0} m").ToArray();
+ RynthLog.Write(LogCat.IltHub,
+ $"[IltGuardian] vendor search: {landscape.Count} landscape objects, bitfield={(_ctx.Host.HasGetObjectBitfield ? "yes" : "no")}, "
+ + $"vendors: {(vendors.Length > 0 ? string.Join(", ", vendors) : "none")}");
+ }
+
+ /// Nearest landscape object matching within SearchRangeMeters.
+ private WorldObject? Nearest(Func match)
+ {
+ var cache = _ctx.Inventory.Cache;
+ int playerId = unchecked((int)_ctx.Inventory.PlayerId);
+ if (cache == null || playerId == 0) return null;
+ WorldObject? best = null;
+ double bestDist = SearchRangeMeters;
+ foreach (var wo in cache.GetLandscapeObjects())
+ {
+ if (!match(wo)) continue;
+ double d = cache.Distance(playerId, wo.Id);
+ if (d <= bestDist) { bestDist = d; best = wo; }
+ }
+ return best;
+ }
+
+ // ── Commands ────────────────────────────────────────────────────────────
+
+ ///
+ /// "/ra guardian translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status".
+ /// "window" is handled by the controller. Pump thread.
+ ///
+ public void HandleCommand(string[] args)
+ {
+ string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
+ string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
+ switch (sub)
+ {
+ case "translate":
+ case "t":
+ _ctx.Chat("[ILT Guardian] " + TranslateManual(rest));
+ break;
+ case "handin":
+ case "give":
+ _ctx.Chat("[ILT Guardian] " + StartHandIn(_lastAnswer, _lastNpc, asked: true));
+ break;
+ case "stop":
+ StopHandIn();
+ _ctx.Chat("[ILT Guardian] Hand-in stopped.");
+ break;
+ case "chat":
+ S.AutoDetectFromChat = Toggle(rest, S.AutoDetectFromChat);
+ _ctx.Chat($"[ILT Guardian] Chat auto-detect {(S.AutoDetectFromChat ? "on" : "off")}.");
+ break;
+ case "auto":
+ S.AutoHandIn = Toggle(rest, S.AutoHandIn);
+ _ctx.Chat($"[ILT Guardian] Auto hand-in {(S.AutoHandIn ? "on" : "off")}.");
+ break;
+ case "buy":
+ S.BuyMissingFromVendor = Toggle(rest, S.BuyMissingFromVendor);
+ _ctx.Chat($"[ILT Guardian] Buy missing Temple items {(S.BuyMissingFromVendor ? "on" : "off")}.");
+ break;
+ case "refresh":
+ _ctx.Chat("[ILT Guardian] " + Attributes.Refresh());
+ break;
+ case "status":
+ _ctx.Chat($"[ILT Guardian] chat={(S.AutoDetectFromChat ? "on" : "off")} auto={(S.AutoHandIn ? "on" : "off")} buy={(S.BuyMissingFromVendor ? "on" : "off")} "
+ + $"answer={(_lastAnswer.Length > 0 ? $"{_lastAnswer} -> {_lastNpc}" : "-")} hand-in: {_handInStatus}");
+ foreach (var r in Attributes.Snapshot)
+ _ctx.Chat($"[ILT Guardian] {r.Attribute,-12} {r.Npc,-16} #{r.Count} {r.Status} {r.Eta}");
+ break;
+ default:
+ _ctx.Chat("[ILT Guardian] /ra guardian [window [show|hide]|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
+ break;
+ }
+ }
+
+ private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch
+ {
+ "on" or "true" or "1" or "show" => true,
+ "off" or "false" or "0" or "hide" => false,
+ _ => !current,
+ };
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ /// Guardian window body.
+ public void Render()
+ {
+ if (ImGui.CollapsingHeader("Riddle translator", ImGuiTreeNodeFlags.DefaultOpen)) RenderTranslator();
+ ImGui.Spacing();
+ if (ImGui.CollapsingHeader("Attribute turn-ins", ImGuiTreeNodeFlags.DefaultOpen)) RenderTracker();
+ }
+
+ private void RenderTranslator()
+ {
+ var s = S;
+ // Plain bool writes; the pump thread reads them on its next tick.
+ bool chat = s.AutoDetectFromChat;
+ if (ImGui.Checkbox("Detect from chat##grdchat", ref chat)) s.AutoDetectFromChat = chat;
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate the guardians' tells as they arrive and show the answer here and on the Mini Remote.");
+ ImGui.SameLine();
+ bool auto = s.AutoHandIn;
+ if (ImGui.Checkbox("Auto hand-in##grdauto", ref auto)) s.AutoHandIn = auto;
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a chat answer, give one of the item to the guardian automatically.");
+ ImGui.SameLine();
+ bool buy = s.BuyMissingFromVendor;
+ if (ImGui.Checkbox("Buy if missing##grdbuy", ref buy)) s.BuyMissingFromVendor = buy;
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Temple guardian: when you carry none, buy one from the open or nearest vendor first.");
+
+ string line = _lastLine;
+ if (line.Length > 0)
+ {
+ ImGui.TextDisabled("Heard:");
+ ImGui.SameLine();
+ ImGui.PushTextWrapPos(0f);
+ ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
+ ImGui.PopTextWrapPos();
+ }
+
+ string answer = _lastAnswer, npc = _lastNpc;
+ if (answer.Length > 0)
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
+ ImGui.SameLine();
+ ImGui.TextDisabled("-> " + npc);
+ if (HandInRunning)
+ {
+ if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn());
+ }
+ else if (ImGui.SmallButton("Hand in##grdgive"))
+ {
+ _ctx.Post(() => StartHandIn(answer, npc, asked: true));
+ }
+ }
+ else ImGui.TextDisabled("No guardian answer yet.");
+ ImGui.TextDisabled("Hand-in: " + _handInStatus);
+
+ ImGui.Spacing();
+ ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54));
+ if (ImGui.Button("Translate##grdtr"))
+ {
+ string text = _input;
+ _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + TranslateManual(text)));
+ }
+ ImGui.SameLine();
+ if (ImGui.Button("Clear##grdclr")) _input = string.Empty;
+ ImGui.SameLine();
+ ImGui.TextDisabled("Paste a spell word or the riddle's question line.");
+ }
+
+ private void RenderTracker()
+ {
+ if (ImGui.SmallButton("Refresh##grdref")) _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()));
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute).");
+ ImGui.SameLine();
+ DateTime synced = Attributes.SyncedUtc;
+ ImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}");
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Reset counts##grdreset"))
+ _ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)",
+ Attributes.ResetCounts, "Reset");
+
+ var rows = Attributes.Snapshot;
+ if (rows.Length > 0 && ImGui.BeginTable("##grdattr", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp))
+ {
+ ImGui.TableSetupColumn("Attribute", ImGuiTableColumnFlags.None, 1.0f);
+ ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.3f);
+ ImGui.TableSetupColumn("#", ImGuiTableColumnFlags.None, 0.35f);
+ ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.None, 0.9f);
+ ImGui.TableSetupColumn("Next", ImGuiTableColumnFlags.None, 1.5f);
+ ImGui.TableHeadersRow();
+ foreach (var r in rows)
+ {
+ ImGui.TableNextRow();
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Attribute);
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Npc);
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Count.ToString());
+ ImGui.TableNextColumn();
+ var col = r.Ready ? LegacyDashboardRenderer.ColGreen
+ : r.Status == "Unknown" ? LegacyDashboardRenderer.ColTextMute
+ : LegacyDashboardRenderer.ColAmber;
+ ImGui.TextColored(col, r.Status);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates).");
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta);
+ }
+ ImGui.EndTable();
+ }
+
+ int hours = S.CooldownHoursAssumed;
+ ImGui.SetNextItemWidth(140);
+ if (ImGui.SliderInt("Assumed cooldown (h)##grdhours", ref hours, 1, 72)) S.CooldownHoursAssumed = hours;
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Used only for rows /myquests doesn't report: how long a /qb wait stamp lasts.");
+ }
+
+ ///
+ /// Mini Remote line: the last answer (for AnswerShownFor) with a Give / Stop button.
+ /// Draws nothing when there is no recent answer. Render thread.
+ ///
+ public void RenderRemoteLine()
+ {
+ string answer = _lastAnswer, npc = _lastNpc;
+ if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return;
+ ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "Guardian:");
+ ImGui.SameLine();
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}");
+ ImGui.SameLine();
+ if (HandInRunning)
+ {
+ if (ImGui.SmallButton("Stop##mrgrd")) _ctx.Post(() => StopHandIn());
+ }
+ else if (ImGui.SmallButton("Give##mrgrd"))
+ {
+ _ctx.Post(() => StartHandIn(answer, npc, asked: true));
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardianPhrasebook.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardianPhrasebook.cs
new file mode 100644
index 0000000..62491e8
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltGuardianPhrasebook.cs
@@ -0,0 +1,220 @@
+// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute
+// Enlightenment riddles mapped to the item each guardian wants (Infinite Leaftide).
+//
+// Pure functions only (no host calls), so the Guardian window may translate on the render thread.
+// The riddle table matches on the closing question line; lead-in lines alone return "No match".
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal static class IltGuardianPhrasebook
+{
+ public const string TempleGuardian = "Guardian of the Temple of Enlightenment";
+ public const string AttributeGuardian = "Guardian of Attribute Enlightenment";
+
+ /// Chat prefixes of an incoming guardian line ("tells you" or ACE's environmental "says").
+ private static readonly string[] IncomingPrefixes =
+ {
+ TempleGuardian + " tells you",
+ AttributeGuardian + " tells you",
+ TempleGuardian + " says",
+ AttributeGuardian + " says",
+ };
+
+ /// Help text returned when nothing was pasted.
+ public const string PasteHint = "Paste a spell word or riddle text, then Translate.";
+
+ /// Help text returned when the text didn't match any spell word or riddle.
+ public const string NoMatchHint = "No match: paste more lines from the guardian (especially the question line ending with ?).";
+
+ private static readonly Dictionary TempleSpells = new(StringComparer.OrdinalIgnoreCase)
+ {
+ { "Boquar", "Mugwort" }, { "Feazh", "Damiana" }, { "Kenrak", "Amaranth" },
+ { "Puish", "Saffron" }, { "Shurov", "Comfrey" }, { "Volae", "Eyebright" },
+ { "Cruath", "Ginseng" }, { "Helkas", "Wormwood" }, { "Malar", "Hyssop" },
+ { "Quavosh", "Dragonsblood" }, { "Tugak", "Vervain" }, { "Yanoi", "Bistort" },
+ { "Equin", "Mandrake" }, { "Jevak", "Myrrh" }, { "Ozhur", "Frankincense" },
+ { "Roiga", "Yarrow" }, { "Uthoi", "Henbane" }, { "Zojak", "Hawthorn" },
+ };
+
+ /// Spell words longest first so a short word never shadows a longer one.
+ private static readonly KeyValuePair[] TempleSpellsByLength =
+ TempleSpells.OrderByDescending(p => p.Key.Length).ToArray();
+
+ /// Normalized riddle phrases (longest first) and the item each answers.
+ private static readonly (string Needle, string Item)[] AttributeClues = BuildAttributeClues();
+
+ /// The same riddles split into meaningful words for the fuzzy fallback.
+ private static readonly (string Item, string[] Words)[] AttributeClueWords =
+ AttributeClues.Select(c => (c.Item, TokenizeMeaningfulWords(c.Needle))).ToArray();
+
+ private static (string, string)[] BuildAttributeClues()
+ {
+ var raw = new (string Phrase, string Item)[]
+ {
+ ("what stone of shadow wields such arm", "Powdered Onyx"),
+ ("what stone defends the mortal clay", "Powdered Agate"),
+ ("what heavy stone keeps adventurers healed", "Powdered Hematite"),
+ ("what heavy stone keeps adventure's healed", "Powdered Hematite"),
+ ("what honeyed stone bids pain to leave", "Powdered Amber"),
+ ("what draught unweaves that mages send", "Chorizite"),
+ ("what gem of life beats deep within", "Powdered Bloodstone"),
+ ("what ruddy gem calls vigor nigh", "Powdered Carnelian"),
+ ("what lunar gem gives peace to mind", "Powdered Moonstone"),
+ ("what verdant gem reveals the way", "Powdered Malachite"),
+ ("what crystal tunes the life it soothes", "Powdered Quartz"),
+ ("what gem of sky makes items nice", "Powdered Turquoise"),
+ ("what vial holds my burning scar", "Brimstone"),
+ ("which draught brings forth the fire's scent", "Turpeth"),
+ ("race the wind yet leave no trace", "Cadmia"),
+ ("grant the hand a dancer grace", "Cadmia"),
+ ("no wings I bear yet fleet I flee", "Cadmia"),
+ ("what draught awakens speed in thee", "Cadmia"),
+ ("what deaught awakens speed in thee", "Cadmia"),
+ ("what potion turns mana-use to one", "Cinnabar"),
+ ("what azure draught makes thunder weep", "Cobalt"),
+ ("what draught commands the winter's tide", "Colcothar"),
+ ("what pale draught prevents acid's writhe", "Gypsum"),
+ ("whate pale draught prevents acid's writhe", "Gypsum"),
+ ("what liquid turns heart grey between", "Quicksilver"),
+ ("what potion pierces the unseen end", "Realgar"),
+ ("what shadowed draught makes swiftness lie", "Stibnite"),
+ ("what verdant vial hides cuts unseen", "Verdigris"),
+ ("what potion shakes both flesh and floor", "Vitriol"),
+ ("what river wood trades life as art", "Alder Talisman"),
+ ("what wood enchants both bane and skill", "Ashwood Talisman"),
+ ("what pale wood casts the striker's bane", "Birch Talisman"),
+ ("what sacred stem keeps harm outside", "Cedar Talisman"),
+ ("what dark wood diminishes the foe's own tune", "Blackthorn Talisman"),
+ ("what hardwood charm makes others stand", "Ebony Talisman"),
+ ("what aged branch makes circles run", "Elder Talisman"),
+ ("what mystic bough binds here to yore", "Hazel Talisman"),
+ ("what poisoned branch brings creeping death", "Hemlock Talisman"),
+ ("what steadfast wood makes volleys rained", "Oak Talisman"),
+ ("what living wand makes allies mend", "Poplar Talisman"),
+ ("what sacred wood the self amends", "Rowan Talisman"),
+ ("what supple wood restores me here", "Willow Talisman"),
+ ("what ancient bough lets lifeblood grow", "Yew Talisman"),
+ };
+ return raw.Select(t => (NormalizePhrase(t.Phrase), t.Item))
+ .OrderByDescending(t => t.Item1.Length)
+ .ToArray();
+ }
+
+ /// Lowercase, curly apostrophes folded, punctuation collapsed to single spaces.
+ private static string NormalizePhrase(string s)
+ {
+ if (string.IsNullOrWhiteSpace(s)) return string.Empty;
+ string lower = s.Trim().ToLowerInvariant().Replace('\u2019', '\'');
+ var sb = new StringBuilder(lower.Length);
+ bool pendingSpace = false;
+ foreach (char c in lower)
+ {
+ bool wordCh = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '\'';
+ if (!wordCh) { pendingSpace = true; continue; }
+ if (pendingSpace && sb.Length > 0) { sb.Append(' '); pendingSpace = false; }
+ sb.Append(c);
+ }
+ return sb.ToString().Trim();
+ }
+
+ /// Words of 3+ letters minus question / filler words.
+ private static string[] TokenizeMeaningfulWords(string normalized) =>
+ normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries)
+ .Where(w => w.Length >= 3 && w is not ("what" or "which" or "the" or "and" or "for"))
+ .ToArray();
+
+ ///
+ /// Typo-tolerant fallback: the riddle whose words overlap the input best, needing at least four
+ /// shared words and 72% of the riddle's words so a near-miss never maps to the wrong item.
+ ///
+ private static string? TryFuzzyAttributeMatch(string blob)
+ {
+ var inputWords = TokenizeMeaningfulWords(blob);
+ if (inputWords.Length == 0) return null;
+ var inputSet = new HashSet(inputWords, StringComparer.Ordinal);
+ string? bestItem = null;
+ double bestScore = 0d;
+ foreach (var (item, words) in AttributeClueWords)
+ {
+ if (words.Length == 0) continue;
+ int matches = words.Count(inputSet.Contains);
+ double score = (double)matches / words.Length;
+ if (matches >= 4 && score >= 0.72d && score > bestScore)
+ {
+ bestScore = score;
+ bestItem = item;
+ }
+ }
+ return bestItem;
+ }
+
+ /// Resolves guardian text to an item name, or one of the help strings.
+ public static string Translate(string raw)
+ {
+ string blob = NormalizePhrase(raw);
+ if (blob.Length == 0) return PasteHint;
+
+ var tokens = Regex.Split(blob, @"[^a-z0-9']+").Where(t => t.Length > 0).ToList();
+ foreach (var pair in TempleSpellsByLength)
+ if (tokens.Any(t => t.Equals(pair.Key, StringComparison.OrdinalIgnoreCase)))
+ return pair.Value;
+ foreach (var pair in TempleSpellsByLength)
+ if (blob.Contains(pair.Key.ToLowerInvariant(), StringComparison.Ordinal))
+ return pair.Value;
+ foreach (var (needle, item) in AttributeClues)
+ if (needle.Length > 0 && blob.Contains(needle, StringComparison.Ordinal))
+ return item;
+ return TryFuzzyAttributeMatch(blob) ?? NoMatchHint;
+ }
+
+ /// False for the help strings Translate returns when nothing matched.
+ public static bool IsAnswer(string translation) =>
+ !string.IsNullOrWhiteSpace(translation) && translation != PasteHint && translation != NoMatchHint;
+
+ /// True when the line starts like an incoming guardian tell / say.
+ public static bool LooksLikeIncomingGuardianLine(string raw)
+ {
+ if (string.IsNullOrWhiteSpace(raw)) return false;
+ string t = raw.TrimStart();
+ foreach (string prefix in IncomingPrefixes)
+ if (t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
+ return true;
+ return false;
+ }
+
+ /// The guardian to give the item to, read from an incoming line (Attribute when unclear).
+ public static string TurnInNpcFromLine(string raw)
+ {
+ if (!string.IsNullOrEmpty(raw) && raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase))
+ return TempleGuardian;
+ return AttributeGuardian;
+ }
+
+ ///
+ /// The guardian for manually pasted text: the name in a pasted chat line, else a Temple spell
+ /// word means the Temple guardian, else the Attribute guardian.
+ ///
+ public static string TurnInNpcFromInput(string raw)
+ {
+ if (string.IsNullOrWhiteSpace(raw)) return AttributeGuardian;
+ if (raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase)) return TempleGuardian;
+ if (raw.Contains(AttributeGuardian, StringComparison.OrdinalIgnoreCase)) return AttributeGuardian;
+ foreach (string word in TempleSpells.Keys)
+ if (raw.Contains(word, StringComparison.OrdinalIgnoreCase))
+ return TempleGuardian;
+ return AttributeGuardian;
+ }
+
+ /// The quoted message of a guardian line ("... tells you, \"text\"" → text); the line itself otherwise.
+ public static string MessageOf(string line)
+ {
+ int open = line.IndexOf('"');
+ int close = line.LastIndexOf('"');
+ return open >= 0 && close > open ? line.Substring(open + 1, close - open - 1).Trim() : line.Trim();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubContext.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubContext.cs
new file mode 100644
index 0000000..a2873c3
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubContext.cs
@@ -0,0 +1,105 @@
+// IltHubContext.cs — Shared services handed to every ILT Hub feature.
+//
+// Threading contract:
+// * Feature Tick / OnChat run on the plugin pump thread and may call the host freely.
+// * Feature Render runs on the ImGui render thread and must NOT call AC actions directly.
+// It calls Post(...) to run work on the next pump tick, or Confirm(...) to ask the
+// player first (the confirmed action is then posted). This mirrors the existing
+// DrainMetaCommands pattern in RynthAiPlugin.
+using System;
+using System.Collections.Concurrent;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+/// A yes/no question waiting for the player in the Hub window.
+internal sealed class IltConfirmRequest
+{
+ public string Title = "Confirm";
+ public string Message = string.Empty;
+ public string YesLabel = "Yes";
+ /// Runs on the pump thread after the player clicks Yes.
+ public Action? OnYes;
+}
+
+internal sealed class IltHubContext
+{
+ private readonly ConcurrentQueue _posted = new();
+ private readonly ConcurrentQueue _confirms = new();
+ private readonly Func _settings;
+
+ public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture,
+ IltServerOptions options, IltInventory inventory, Func settings)
+ {
+ Host = host;
+ State = state;
+ Store = store;
+ Capture = capture;
+ Options = options;
+ Inventory = inventory;
+ _settings = settings;
+ }
+
+ public RynthCoreHost Host { get; }
+ public IltHubState State { get; }
+ public IltHubStore Store { get; }
+ public IltChatCapture Capture { get; }
+ public IltServerOptions Options { get; }
+ public IltInventory Inventory { get; }
+
+ /// The live combat settings (rule lists the Pet picker / USD importer edit). Null before login.
+ public LegacyUiSettings? Settings => _settings();
+
+ /// Set by the controller when combat settings were edited and must be saved.
+ public Action? SaveCombatSettings;
+
+ /// Logged-in character name (resolved at login).
+ public string CharName = string.Empty;
+
+ /// True when the Hub window is open (features use it to gate auto-refreshes).
+ public bool WindowOpen => State.WindowVisible;
+
+ /// Writes a local chat line (never sent to the server).
+ public void Chat(string text)
+ {
+ if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
+ }
+
+ /// Queues work for the next pump tick (safe from the render thread).
+ public void Post(Action action) => _posted.Enqueue(action);
+
+ /// Asks the player to confirm before runs on the pump thread.
+ public void Confirm(string title, string message, Action onYes, string yesLabel = "Yes")
+ => _confirms.Enqueue(new IltConfirmRequest { Title = title, Message = message, OnYes = onYes, YesLabel = yesLabel });
+
+ /// Render thread: takes the next pending confirmation, if any.
+ public bool TryTakeConfirm(out IltConfirmRequest request) => _confirms.TryDequeue(out request!);
+
+ /// Pump thread: runs everything posted since the last tick.
+ public void DrainPosted()
+ {
+ int guard = 0;
+ while (guard++ < 64 && _posted.TryDequeue(out var a))
+ {
+ try { a(); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "posted action"); }
+ }
+ }
+
+ /// Elapsed-ms clock used for every Hub timer.
+ public static long NowMs => Environment.TickCount64;
+}
+
+/// Contract every Hub feature module implements.
+internal interface IIltFeature
+{
+ /// Pump-thread tick (~every plugin tick).
+ void Tick(long nowMs);
+
+ /// Pump-thread chat line. Return true to hide the line from the chat window.
+ bool OnChat(string text);
+
+ /// Logout / teardown: stop automation, drop transient state.
+ void OnLogout();
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubController.cs
new file mode 100644
index 0000000..7acf2f3
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubController.cs
@@ -0,0 +1,499 @@
+// IltHubController.cs — Owns the ILT Hub: state, services, feature modules, commands.
+//
+// RynthAiPlugin creates one controller per login session and forwards:
+// OnTick → Tick() (pump thread)
+// OnChatWindowText → OnChat() (pump thread; returns true to eat the line)
+// OnKillNotification → RecordKill()
+// OnRender → Render() (render thread)
+// /ra hub ..., /ra quests ... → HandleCommand()
+// OnLogout / teardown → OnLogout()
+// The Hub only appears on ACECustom/ILT worlds where at least one server feature is on;
+// on every other world it stays dormant (no probes, no chat, no window).
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Meta;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltHubController
+{
+ private const long SaveIntervalMs = 5000;
+
+ private readonly IltHubContext _ctx;
+ private readonly IltHubUi _ui;
+ private readonly Func _quests;
+ private readonly List _features = new();
+ private long _lastSaveAt;
+ private bool _questOutcomeHooked;
+ private bool _availabilityAnnounced; // "/ra hub to open" hint printed this session
+
+ public IltBanking Banking { get; }
+ public IltPets Pets { get; }
+ public IltSessionRates Rates { get; }
+ public IltQuests Quests { get; }
+ public IltProgression Progression { get; }
+ public IltGear Gear { get; }
+ public IltGames Games { get; }
+ /// Registry charm acquired / active / server state (Charms Tracking tab).
+ public IltCharmTracker Charms { get; }
+ /// Temple guardians: riddle translator, hand-in, attribute turn-in tracker.
+ public IltGuardian Guardian { get; }
+
+ public IltHubController(RynthCoreHost host, string charFolder, Func cache,
+ Func settings, Func quests, Action saveCombatSettings)
+ {
+ var store = new IltHubStore(host, charFolder);
+ var state = store.LoadState();
+ var capture = new IltChatCapture(host);
+ var inventory = new IltInventory(host, cache);
+ IltHubContext? ctxRef = null;
+ var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text));
+ _ctx = new IltHubContext(host, state, store, capture, options, inventory, settings) { SaveCombatSettings = saveCombatSettings };
+ ctxRef = _ctx;
+ _quests = quests;
+
+ Banking = new IltBanking(_ctx);
+ Pets = new IltPets(_ctx);
+ Rates = new IltSessionRates(_ctx);
+ Quests = new IltQuests(_ctx, quests);
+ Progression = new IltProgression(_ctx);
+ Gear = new IltGear(_ctx);
+ Games = new IltGames(_ctx);
+ Charms = new IltCharmTracker(_ctx);
+ Guardian = new IltGuardian(_ctx, quests, Quests);
+ _features.AddRange(new IIltFeature[] { Banking, Pets, Rates, Quests, Progression, Gear, Games, Guardian });
+
+ Banking.BalanceChanged += Rates.OnBankBalanceChanged;
+ options.ProbeReplyTap = OnProbeReply;
+ _ui = new IltHubUi(this, _ctx);
+ }
+
+ public IltHubState State => _ctx.State;
+ public IltServerOptions Options => _ctx.Options;
+
+ ///
+ /// Shows / hides / toggles the Mini Remote, which is the Hub's main window ("show", "hide",
+ /// "toggle"). Set by RynthAiPlugin; returns the chat reply. Pump thread.
+ ///
+ public Func? MiniRemoteCommand { get; set; }
+
+ /// True while the Mini Remote is on screen (set by RynthAiPlugin).
+ public Func? MiniRemoteVisible { get; set; }
+
+ /// World is ILT-like and the server has at least one Hub feature on.
+ public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
+
+ ///
+ /// Whether a section window can be shown now. Character always can (it explains why the Hub is
+ /// idle and holds the Force-ILT override); the rest need server features.
+ ///
+ public bool SectionAvailable(IltSection section) => section switch
+ {
+ IltSection.Character => true,
+ IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
+ IltSection.Games => Available && Games.AnyGameAvailable,
+ _ => Available,
+ };
+
+ public bool IsSectionOpen(IltSection section) => IltSections.IsOpen(_ctx.State.Character, section);
+
+ /// Opens / closes a section window (render or pump thread; a plain bool write).
+ public void SetSectionOpen(IltSection section, bool open) => IltSections.SetOpen(_ctx.State.Character, section, open);
+
+ /// The Force-ILT world override (world identity only; features still come from the server).
+ public bool ForceIltWorld
+ {
+ get => _ctx.State.ForceLeaftideFeatures;
+ set => _ctx.State.ForceLeaftideFeatures = value;
+ }
+
+ /// Re-asks the server which features are on (safe from the render thread: posted to the pump).
+ public void RequestOptionsRefresh() => _ctx.Post(() => _ctx.Options.Refresh(manual: true));
+
+ /// True when the cached options already say /myquests is off (skip the login refresh).
+ public bool SkipLoginQuestRefresh => _ctx.Options.IsIltLikeWorld && _ctx.Options.IsOff(IltFeature.Quests);
+
+ // ── Lifecycle ───────────────────────────────────────────────────────────
+
+ /// Login: remember the character, hook PetManager, schedule the options check, import UB data once.
+ public void OnLoginComplete(string charName, PetManager? petManager)
+ {
+ _ctx.CharName = charName ?? string.Empty;
+ RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'");
+ _ctx.Options.OnLoginComplete();
+ _ctx.Inventory.Reset();
+ Rates.Reset();
+
+ if (petManager != null)
+ {
+ petManager.AllowSummonOnEmpty = Pets.AllowSummonOnEmpty;
+ petManager.HoldSummons = Pets.HoldCombatSummons;
+ petManager.YieldPetForCombat = Pets.YieldPetForCombat;
+ }
+
+ HookQuestOutcome();
+
+ if (!_ctx.State.UbSidecarsImported && _ctx.CharName.Length > 0)
+ {
+ _ctx.State.UbSidecarsImported = true;
+ string world = _ctx.Options.WorldName;
+ Banking.ImportUb(tx => _ctx.Store.ImportUbSidecars(_ctx.State, tx, world, _ctx.CharName));
+ }
+ }
+
+ private void HookQuestOutcome()
+ {
+ if (_questOutcomeHooked) return;
+ var t = _quests();
+ if (t == null) return;
+ t.RefreshCompleted += () => _ctx.Options.NoteQuestTrackerOutcome(t.Disabled, t.Count);
+ _questOutcomeHooked = true;
+ }
+
+ /// Pump-thread tick.
+ public void Tick()
+ {
+ long now = IltHubContext.NowMs;
+ _ctx.DrainPosted();
+ _ctx.Capture.Tick();
+ _ctx.Options.Tick();
+ HookQuestOutcome();
+
+ // "Hub UI on screen" gates bank auto-refresh and the gear / split-arrow scans.
+ _ctx.State.WindowVisible = (MiniRemoteVisible?.Invoke() ?? false) || IltSections.AnyOpen(_ctx.State.Character);
+
+ // One hint per session once the server confirms Hub features. The Mini Remote is separate
+ // from the main RynthAi panel, so say how to open it.
+ if (!_availabilityAnnounced && Available)
+ {
+ _availabilityAnnounced = true;
+ if (!_ctx.State.WindowVisible)
+ _ctx.Chat("[ILT Hub] ILT server features detected. Type /ra hub to open the Mini Remote (Options lists the Hub windows).");
+ }
+
+ // Features run only on ILT-like worlds; elsewhere the Hub is fully dormant.
+ if (_ctx.Options.IsIltLikeWorld)
+ {
+ foreach (var f in _features)
+ {
+ try { f.Tick(now); }
+ catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.Tick"); }
+ }
+ }
+
+ // Expire an unanswered chat confirmation so a stale "/ra hub confirm" can't fire it later.
+ if (_pendingAction != null && now - _pendingAt > ConfirmWindowMs)
+ {
+ RynthLog.Event(LogEvents.IltConfirmation, $"confirmation expired: {_pendingLabel}");
+ _ctx.Chat($"[ILT Hub] Confirmation for '{_pendingLabel}' expired.");
+ ClearPending();
+ }
+
+ if (now - _lastSaveAt >= SaveIntervalMs)
+ {
+ _lastSaveAt = now;
+ _ctx.Store.SaveStateIfDirty(_ctx.State);
+ }
+ }
+
+ /// Pump-thread chat line. Returns true when the line should be hidden.
+ public bool OnChat(string text)
+ {
+ if (string.IsNullOrEmpty(text)) return false;
+ string line = text.TrimEnd('\r', '\n');
+ _ctx.Options.OnChatLine(line);
+ bool eat = _ctx.Capture.OnChatLine(line);
+ if (!_ctx.Options.IsIltLikeWorld) return eat;
+ foreach (var f in _features)
+ {
+ try { eat |= f.OnChat(line); }
+ catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnChat"); }
+ }
+ return eat;
+ }
+
+ /// Maps a feature module to its diagnostics category so its trace/exception lines land in its own file.
+ private static LogCat CategoryOf(IIltFeature f) => f switch
+ {
+ IltBanking => LogCat.IltBanking,
+ IltPets => LogCat.IltPets,
+ IltSessionRates => LogCat.IltRates,
+ IltQuests => LogCat.IltQuests,
+ IltProgression => LogCat.IltProgression,
+ IltGear => LogCat.IltGear,
+ IltGames => LogCat.IltGames,
+ _ => LogCat.IltHub,
+ };
+
+ public void RecordKill() => Rates.RecordKill();
+
+ /// Logout / teardown: stop automation and flush to disk.
+ public void OnLogout()
+ {
+ RynthLog.Event(LogEvents.IltLogout, $"logout: stopping features for '{_ctx.CharName}'");
+ ClearPending();
+ foreach (var f in _features)
+ {
+ try { f.OnLogout(); }
+ catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnLogout"); }
+ }
+ _ctx.Capture.Clear();
+ _ctx.Store.SaveStateIfDirty(_ctx.State);
+ }
+
+ ///
+ /// JSON for the engine Skills panel's Progression tab (RynthPluginGetProgressionJson).
+ /// "available" is false off ILT-like worlds; the panel then hides the ILT sections. Pump thread.
+ ///
+ public string BuildProgressionJson()
+ {
+ var sb = new System.Text.StringBuilder(2048);
+ sb.Append("{\"available\":").Append(Available ? "true" : "false");
+ sb.Append(",\"world\":\"").Append(RynthAiPlugin.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\",");
+ Progression.AppendSnapshotJson(sb);
+ sb.Append('}');
+ return sb.ToString();
+ }
+
+ /// JSON for the engine Settings panel's Charms Tracking tab (RynthPluginGetCharmsJson). Pump thread.
+ public string BuildCharmsJson() => Charms.BuildJson();
+
+ /// Render thread: section windows, confirm popups, games HUD.
+ public void Render() => _ui.Render();
+
+ // ── Probe taps: reuse login-probe replies so tabs fill without extra commands ──
+
+ private void OnProbeReply(string key, IltChatResult r)
+ {
+ if (r.Lines.Count == 0) return;
+ switch (key)
+ {
+ case IltFeature.Aug: Progression.ApplyAugLines(r.Lines); break;
+ case IltFeature.Pets: Pets.ApplyRoster(false, r.Lines); break;
+ case IltFeature.Shinies: Pets.ApplyRoster(true, r.Lines); break;
+ case IltFeature.Qb: Quests.ApplyQbProbe(r.Lines); break;
+ // Bank lines are parsed passively by IltBanking.OnChat as they arrive.
+ }
+ }
+
+ // ── Commands ────────────────────────────────────────────────────────────
+
+ ///
+ /// "/ra hub [show|hide|toggle|open <section> [show|hide|toggle]|refresh|bank|status|force on|off|
+ /// profile save|load|list ...|suit list|test|load ...]" (show/hide/toggle drive the Mini Remote),
+ /// "/ra quests [refresh|check <regex>|window|favhud]", "/ra pets [show|hide|toggle]" and
+ /// "/ra guardian ..." (see IltGuardian.HandleCommand).
+ /// Pump thread. Returns false if not handled.
+ ///
+ public bool HandleCommand(string verb, string[] args)
+ {
+ RynthLog.Event(LogEvents.IltCommand, $"command: /ra {verb} {string.Join(" ", args)}".TrimEnd());
+ if (verb.Equals("quests", StringComparison.OrdinalIgnoreCase))
+ {
+ string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "refresh";
+ string mode = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle";
+ var cs = _ctx.State.Character;
+ switch (sub)
+ {
+ case "check" when args.Length > 1:
+ Quests.CheckCommand(string.Join(" ", args.Skip(1)));
+ break;
+ case "window":
+ OpenSection(IltSection.Quests, mode);
+ break;
+ case "favhud":
+ case "favorites":
+ cs.ShowQuestFavoritesHud = ResolveToggle(mode, cs.ShowQuestFavoritesHud);
+ _ctx.Chat(cs.ShowQuestFavoritesHud ? "[ILT Hub] Quest favorites HUD shown." : "[ILT Hub] Quest favorites HUD hidden.");
+ break;
+ default:
+ _ctx.Chat("[ILT Hub] " + Quests.RefreshQuests());
+ break;
+ }
+ return true;
+ }
+ if (verb.Equals("pets", StringComparison.OrdinalIgnoreCase))
+ {
+ // "/ra pets [show|hide|toggle]": same as "/ra hub open pets".
+ OpenSection(IltSection.Pet, args.Length > 0 ? args[0] : "toggle");
+ return true;
+ }
+ if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase))
+ {
+ // "/ra guardian window [show|hide|toggle]" opens the window; everything else is the Guardian's.
+ if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase))
+ OpenSection(IltSection.Guardian, args.Length > 1 ? args[1] : "toggle");
+ else
+ Guardian.HandleCommand(args);
+ return true;
+ }
+ if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false;
+
+ string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "toggle";
+ string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
+ switch (cmd)
+ {
+ case "show":
+ case "hide":
+ case "toggle":
+ // The Mini Remote is the Hub's main window.
+ if (MiniRemoteCommand != null) _ctx.Chat(MiniRemoteCommand(cmd));
+ else _ctx.Chat("[ILT Hub] The Mini Remote is not available yet.");
+ break;
+ case "open":
+ if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section))
+ {
+ _ctx.Chat("[ILT Hub] Usage: /ra hub open character|quests|pets|banking|gear|games|guardian [show|hide|toggle]");
+ break;
+ }
+ OpenSection(section, args.Length > 2 ? args[2] : "toggle");
+ break;
+ case "refresh": _ctx.Options.Refresh(manual: true); break;
+ case "bank": Banking.RequestRefresh(quiet: false); break;
+ case "status": PrintStatus(); break;
+ case "force":
+ _ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
+ _ctx.Chat($"[ILT Hub] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
+ break;
+ case "profile": HandleProfile(args.Skip(1).ToArray()); break;
+ case "suit": HandleSuit(args.Skip(1).ToArray()); break;
+ case "clap": Gear.ChunkClap.ClapNow(manual: true); break;
+ case "confirm": RunPending(); break;
+ case "cancel":
+ _ctx.Chat(_pendingAction != null ? $"[ILT Hub] Cancelled '{_pendingLabel}'." : "[ILT Hub] Nothing to cancel.");
+ ClearPending();
+ break;
+ default:
+ _ctx.Chat("[ILT Hub] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|clap|confirm|cancel");
+ _ctx.Chat("[ILT Hub] /ra hub open character|quests|pets|banking|gear|games|guardian [show|hide|toggle]");
+ _ctx.Chat("[ILT Hub] /ra hub profile list|save [shared]|load /ra hub suit list|test|load [name]");
+ _ctx.Chat("[ILT Hub] /ra quests [refresh|check |window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
+ _ctx.Chat("[ILT Hub] /ra guardian [window|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
+ break;
+ }
+ return true;
+ }
+
+ /// Applies show / hide / toggle to a section window and says what happened.
+ private void OpenSection(IltSection section, string mode)
+ {
+ bool open = IltSections.Resolve(mode, IsSectionOpen(section));
+ SetSectionOpen(section, open);
+ string label = IltSections.Label(section);
+ _ctx.Chat(!open ? $"[ILT Hub] {label} window hidden."
+ : SectionAvailable(section) ? $"[ILT Hub] {label} window shown."
+ : $"[ILT Hub] {label} window will show once the server reports that feature on.");
+ }
+
+ /// "show"/"on" → true, "hide"/"off" → false, anything else flips .
+ private static bool ResolveToggle(string mode, bool current) => mode switch
+ {
+ "show" or "on" or "true" or "1" => true,
+ "hide" or "off" or "false" or "0" => false,
+ _ => !current,
+ };
+
+ private void PrintStatus()
+ {
+ var o = _ctx.Options;
+ _ctx.Chat($"[ILT Hub] World '{o.WorldName}' ILT={o.IsIltLikeWorld} force={_ctx.State.ForceLeaftideFeatures} source={(o.Source.Length > 0 ? o.Source : "none")} "
+ + $"refreshed={(o.LastRefreshUtc == DateTime.MinValue ? "never" : o.LastRefreshUtc.ToLocalTime().ToString("t"))}");
+ var bits = o.SnapshotBits();
+ string on = string.Join(", ", bits.Where(b => b.Value == 1).Select(b => b.Key));
+ string off = string.Join(", ", bits.Where(b => b.Value == 0).Select(b => b.Key));
+ _ctx.Chat("[ILT Hub] on: " + (on.Length > 0 ? on : "-"));
+ _ctx.Chat("[ILT Hub] off: " + (off.Length > 0 ? off : "-"));
+ }
+
+ private void HandleProfile(string[] a)
+ {
+ string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
+ if (sub == "list")
+ {
+ var names = _ctx.Store.ListProfiles();
+ _ctx.Chat("[ILT Hub] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)"));
+ return;
+ }
+ if (a.Length < 2) { _ctx.Chat("[ILT Hub] Usage: /ra hub profile save [shared] | load "); return; }
+ if (sub == "save")
+ {
+ bool shared = a.Length > 2 && a[2].Equals("shared", StringComparison.OrdinalIgnoreCase);
+ _ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, a[1], shared, out string err)
+ ? $"[ILT Hub] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[ILT Hub] Save failed: " + err);
+ }
+ else if (sub == "load")
+ {
+ // Loading replaces the Hub's current settings, so it needs an explicit confirm.
+ string profile = a[1];
+ RequestConfirm($"load Hub profile '{profile}' (replaces current Hub settings)", () =>
+ _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, profile, out string err)
+ ? $"[ILT Hub] Loaded profile '{profile}'." : "[ILT Hub] Load failed: " + err));
+ }
+ }
+
+ // ── Chat confirmations for destructive commands ─────────────────────────
+
+ /// How long a "/ra hub confirm" stays valid after the prompt.
+ private const long ConfirmWindowMs = 20000;
+
+ private string? _pendingLabel;
+ private Action? _pendingAction;
+ private long _pendingAt;
+
+ /// Arms a single pending action; a newer request replaces an older one.
+ private void RequestConfirm(string label, Action action)
+ {
+ _pendingLabel = label;
+ _pendingAction = action;
+ _pendingAt = IltHubContext.NowMs;
+ RynthLog.Event(LogEvents.IltConfirmation, $"confirmation requested: {label}");
+ _ctx.Chat($"[ILT Hub] About to {label}. Type /ra hub confirm within {ConfirmWindowMs / 1000} s, or /ra hub cancel.");
+ }
+
+ /// Runs the pending action if one is armed and still inside its window.
+ private void RunPending()
+ {
+ var action = _pendingAction;
+ string? label = _pendingLabel;
+ bool fresh = action != null && IltHubContext.NowMs - _pendingAt <= ConfirmWindowMs;
+ ClearPending();
+ if (!fresh || action == null) { _ctx.Chat("[ILT Hub] Nothing to confirm."); return; }
+
+ RynthLog.Event(LogEvents.IltConfirmation, $"confirmed: {label}");
+ try { action(); }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"confirmed action '{label}'"); }
+ }
+
+ private void ClearPending()
+ {
+ _pendingAction = null;
+ _pendingLabel = null;
+ _pendingAt = 0;
+ }
+
+ private void HandleSuit(string[] a)
+ {
+ string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
+ string? name = a.Length > 1 ? string.Join(" ", a.Skip(1)) : null;
+ switch (sub)
+ {
+ case "list":
+ var list = Gear.Suits.ListProfiles();
+ _ctx.Chat("[ILT Hub] Suits: " + (list.Count > 0 ? string.Join(", ", list.Select(p => p.Name)) : "(none)"));
+ break;
+ case "test":
+ foreach (string l in Gear.Suits.Test(name)) _ctx.Chat("[ILT Hub] " + l);
+ break;
+ case "load":
+ // Equipping a suit swaps gear mid-session, so it needs an explicit confirm.
+ RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[ILT Hub] " + Gear.Suits.Load(name)));
+ break;
+ default:
+ _ctx.Chat("[ILT Hub] Usage: /ra hub suit list|test [name]|load [name]");
+ break;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubState.cs
new file mode 100644
index 0000000..8aeadef
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubState.cs
@@ -0,0 +1,285 @@
+// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools).
+//
+// Lives in \ilt-hub.json, deliberately separate from the combat settings
+// profile (Default.json / /ra settings) so ILT data never leaks into combat profiles and
+// non-ILT characters stay untouched. Serialized with the NativeAOT source-generated
+// RynthAiJsonContext (IncludeFields = true), so plain public fields are used throughout.
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+/// Root of everything the Hub remembers between sessions.
+public sealed class IltHubState
+{
+ /// Bumped when the shape changes in a way that needs a migration.
+ public int SchemaVersion = 1;
+
+ // ── Window / shell ──────────────────────────────────────────────────────
+ ///
+ /// Hub UI on screen: the Mini Remote or any ILT section window (IltHubController.Tick keeps it
+ /// current). Bank auto-refresh and the gear / split-arrow scans run only while it is true.
+ ///
+ public bool WindowVisible;
+ /// Unused since the tabbed Hub window was retired; kept so old files still load.
+ public int SelectedTab;
+ public bool GamesHudVisible = true;
+
+ ///
+ /// "This world is an ACECustom/ILT shard even though its name isn't InfiniteLeaftide."
+ /// World-identity override ONLY: it makes the Hub ask the server for its options, it
+ /// never turns a feature on by itself.
+ ///
+ public bool ForceLeaftideFeatures;
+
+ /// True once the one-time UtilityBelt sidecar import has run for this character.
+ public bool UbSidecarsImported;
+
+ /// Last-seen server feature bits. Cache only — overwritten by every login refresh.
+ public IltServerOptionsSnapshot ServerOptions = new();
+
+ public IltBankState Bank = new();
+ public IltPetState Pet = new();
+ public IltCharacterState Character = new();
+ public IltGearState Gear = new();
+ public IltGamesState Games = new();
+ public IltGuardianState Guardian = new();
+}
+
+/// Cached result of the server-options check (see IltServerOptions).
+public sealed class IltServerOptionsSnapshot
+{
+ public string WorldName = string.Empty;
+ /// "ilt-features" (structured dump), "probe" (command probing) or "" (never refreshed).
+ public string Source = string.Empty;
+ public DateTime LastRefreshUtc = DateTime.MinValue;
+ /// Feature key → -1 unknown, 0 off, 1 on.
+ public Dictionary Bits = new(StringComparer.OrdinalIgnoreCase);
+}
+
+// ── Banking ─────────────────────────────────────────────────────────────────
+
+public sealed class IltBankState
+{
+ public long Pyreals;
+ public long Luminance;
+ public long LegendaryKeys;
+ public long MythicalKeys;
+ public long EnlightenedCoins;
+ public long WeaklyEnlightenedCoins;
+ public DateTime LastUpdated = DateTime.MinValue;
+
+ /// Last transfer recipient typed into the transfer form.
+ public string TransferTarget = string.Empty;
+ public int TransferCurrencyIndex;
+
+ /// Re-issue /bank every N seconds while the Hub is open (0 = manual only).
+ public int AutoRefreshSeconds = 120;
+}
+
+/// One "Transferred …" / "Received …" bank line seen in chat.
+public sealed class IltBankTransaction
+{
+ public DateTime Timestamp;
+ /// "Sent" or "Received".
+ public string Type = string.Empty;
+ public string Currency = string.Empty;
+ public long Amount;
+ public string OtherPlayer = string.Empty;
+ public string Description = string.Empty;
+}
+
+// ── Pet ─────────────────────────────────────────────────────────────────────
+
+public sealed class IltPetState
+{
+ // Healing-pet automation (UB "HealingBuddy" subset).
+ public bool HealingEnabled;
+ /// Exact name of the heal-pet essence to use; empty = auto-detect (Healing Buddy / Dule box).
+ public string HealPetName = string.Empty;
+ public int HealthThresholdPercent = 80;
+ /// Do not summon when current HP is below this (summoning mid-death wastes the use). 0 = off.
+ public int MinHealthPoints = 100;
+ public bool AutoDespawnAfterHeal = true;
+ public int RespawnDelaySeconds = 2;
+ public int PetTimeoutSeconds = 30;
+
+ ///
+ /// Allow a combat summon from an EMPTY essence when the Summon Essence Refill Charm is
+ /// active (server refills from banked pyreals). Still requires the server flag to be on.
+ ///
+ public bool UsePyrealRefillPath;
+
+ /// Last captured /pets and /shinies rosters (display only).
+ public List PetLog = new();
+ public List ShinyLog = new();
+
+ // ── Pet roster (UB Pets-tab style) ──
+ /// Roster type shown in the Pet tab (IltPetKind: 0 Combat, 1 Healing, 2 Cosmetic).
+ public int RosterKind;
+ /// Roster sort (IltPetSort: 0 Priority, 1 Bond, 2 Potency, 3 Breed ready, 4 Level, 5 Uses, 6 Name).
+ public int RosterSort;
+ /// User type overrides by essence name; essences not listed are auto-classified.
+ public List Assignments = new();
+
+ /// Essence name of the chosen cosmetic (display) pet; empty = none.
+ public string CosmeticPetName = string.Empty;
+ /// Keep the cosmetic pet summoned while in peace mode; it is dismissed when a combat pet is needed.
+ public bool KeepCosmeticOut;
+ /// Seconds to wait before re-summoning the cosmetic pet after it despawns.
+ public int CosmeticRespawnSeconds = 15;
+}
+
+/// A user's choice of summon type for one essence (matched by name, case-insensitive).
+public sealed class IltPetAssignment
+{
+ public string Name = string.Empty;
+ /// IltPetKind as int (0 Combat, 1 Healing, 2 Cosmetic).
+ public int Kind;
+}
+
+// ── Character ───────────────────────────────────────────────────────────────
+
+public sealed class IltCharacterState
+{
+ /// Item → coin conversion table used by the session-rates strip.
+ public List ItemConversions = new()
+ {
+ new IltItemConversion { ItemName = "Strawberry Jam Jar", ItemsPerConversion = 100, CoinsPerConversion = 10 },
+ new IltItemConversion { ItemName = "Ancient Pyreal", ItemsPerConversion = 100, CoinsPerConversion = 37 },
+ };
+
+ /// Augmentation planner targets, keyed by aug type (lowercase).
+ public Dictionary AugTargets = new(StringComparer.OrdinalIgnoreCase);
+ /// Luminance price of one Enlightened Coin (planner math only; 0 = don't price coins).
+ public long LumPerEnlightenedCoin;
+
+ /// Enlightenment planner target level (0 = current + 5).
+ public int EnlTargetLevel;
+ public int EnlightenedCoinsPerToken = 20;
+ ///
+ /// Auto-enlighten preference. Even when true it stays DISARMED each session until the
+ /// player confirms in the Hub, and the server's own Yes/No dialog is never auto-clicked.
+ ///
+ public bool AutoEnlightenEnabled;
+ public int AutoEnlightenCheckSeconds = 30;
+ /// Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP).
+ public bool AutoEnlightenSpendXpFirst;
+
+ /// Quest Tracker search box contents.
+ public string QuestFilter = string.Empty;
+ public string QbFilter = string.Empty;
+
+ /// Starred quest flag keys (lowercase), shown on the floating favorites HUD.
+ public List QuestFavorites = new();
+ /// Quest tracker lists starred quests only.
+ public bool QuestFavoritesOnly;
+ /// Floating quest favorites HUD is shown.
+ public bool ShowQuestFavoritesHud;
+ public bool QuestFavoritesHudLocked;
+ // ILT section windows, opened from the Mini Remote's Options (IltSections).
+ /// The "Quests" window (tracker + quest bonus) is open.
+ public bool QuestTrackerPoppedOut;
+ /// The "Pets" window is open.
+ public bool PetsWindowOpen;
+ /// The "ILT Character" window (world status, session rates) is open.
+ public bool CharacterWindowOpen;
+ /// The "Banking" window is open.
+ public bool BankingWindowOpen;
+ /// The "Gear" window is open.
+ public bool GearWindowOpen;
+ /// The "Games" window is open.
+ public bool GamesWindowOpen;
+ /// The "Guardian" window (riddle translator, attribute tracker) is open.
+ public bool GuardianWindowOpen;
+
+ ///
+ /// Registry charms this character has carried, keyed by charm name. Lets the Charms Tracking
+ /// tab report "acquired" for charms that are now in storage (the client only sees carried items).
+ ///
+ public Dictionary CharmsSeen = new(StringComparer.OrdinalIgnoreCase);
+}
+
+/// Last time a charm was seen in the character's possession, with its best tier.
+public sealed class IltCharmSeen
+{
+ public int Tier;
+ public int MaxTier;
+ public DateTime LastSeenUtc;
+}
+
+public sealed class IltItemConversion
+{
+ public string ItemName = string.Empty;
+ public int ItemsPerConversion = 100;
+ public int CoinsPerConversion;
+}
+
+// ── Gear ────────────────────────────────────────────────────────────────────
+
+public sealed class IltGearState
+{
+ // Dispel (Rune of Dispel on harmful debuffs)
+ public bool AutoDispel;
+ public int DispelCooldownSeconds = 10;
+ /// Spell-name substrings that are ALWAYS dispelled.
+ public List DispelInclusions = new();
+ /// Spell-name substrings that are NEVER dispelled.
+ public List DispelExclusions = new();
+
+ // Surging Strength (Empowered Volcanic Ember keeper)
+ public bool SurgingStrength;
+ public int SurgingCooldownSeconds = 15;
+
+ // Aetheria / corrupted-weapon chunking
+ public bool AutoChunkAetheria;
+ public bool AutoChunkCorrupted;
+ public bool ChunkInCombat;
+ public int ChunkIntervalMs = 2000;
+ /// Only chunk aetheria whose max level is below this (Coalesced always chunks).
+ public int ChunkAetheriaUnderLevel = 4;
+
+ // Auto-clap (/clap all)
+ public bool AutoClap;
+ public int ClapIntervalMinutes = 30;
+
+ // Guardian Hand charm (WCID unpublished — name match until set)
+ public uint GuardianHandWcid;
+ public string GuardianHandName = "Guardian Hand";
+
+ // Split arrows (White Quartz imbue on missile weapons)
+ public int SplitArrowTarget = 3;
+ public bool SplitIgnoreImbued = true;
+
+ // Equipment profiles (.utl suits) and VTank .usd import
+ public string LastEquipProfile = string.Empty;
+ public string LastUsdPath = string.Empty;
+}
+
+// ── Games ───────────────────────────────────────────────────────────────────
+
+public sealed class IltGamesState
+{
+ public long BlackjackBet = 1_000_000;
+ public long FellowshipBlackjackBet = 1_000_000;
+ public int PowerballQuantity = 1;
+}
+
+// ── Guardian (Temple of Enlightenment) ──────────────────────────────────────
+
+public sealed class IltGuardianState
+{
+ /// Translate incoming guardian tells and show the answer (Guardian window + Mini Remote).
+ public bool AutoDetectFromChat = true;
+ /// After a chat answer, give the item to the guardian automatically.
+ public bool AutoHandIn;
+ /// Temple guardian only: buy one of the item from the nearest vendor when none is carried.
+ public bool BuyMissingFromVendor = true;
+
+ /// Assumed attribute turn-in cooldown when only /qb wait stamps are known (hours).
+ public int CooldownHoursAssumed = 20;
+ /// Turn-ins counted from /qb wait-stamp transitions, keyed by attribute (fallback when /myquests lacks the flag).
+ public Dictionary TurnInCounts = new(StringComparer.OrdinalIgnoreCase);
+ /// Estimated end of each attribute's cooldown (UTC), keyed by attribute (same fallback).
+ public Dictionary CooldownUntilUtc = new(StringComparer.OrdinalIgnoreCase);
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubStore.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubStore.cs
new file mode 100644
index 0000000..6b51e84
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubStore.cs
@@ -0,0 +1,404 @@
+// IltHubStore.cs — Disk persistence for the ILT Hub.
+//
+// Files (all under the per-character settings folder the dashboard already uses):
+// \ilt-hub.json live Hub state (IltHubState)
+// \ilt-hub-transactions.json bank transaction log (capped)
+// \ilt-hub-profiles\.json named per-character Hub profiles
+// \IltHubProfiles\.json named profiles shared by every character
+// Saves are dirty-checked (the serialized JSON is compared to what was last written) so
+// the periodic save in Tick costs nothing when nothing changed. A one-time import pulls
+// UtilityBelt's bankdata sidecars so players keep their balances and history.
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.Json;
+using RynthCore.PluginSdk;
+using RynthCore.Install;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltHubStore
+{
+ /// Maximum bank transactions kept on disk (oldest dropped first).
+ public const int MaxTransactions = 1000;
+
+ /// Shared root (\RynthAi) for profiles usable by every character.
+ public static readonly string SharedRoot = RynthInstallPaths.RynthAiDir;
+
+ private readonly RynthCoreHost _host;
+ private readonly string _charFolder;
+ private string _lastStateJson = string.Empty;
+ private string _lastTxJson = string.Empty;
+
+ public IltHubStore(RynthCoreHost host, string charFolder)
+ {
+ _host = host;
+ _charFolder = charFolder ?? string.Empty;
+ }
+
+ public string CharFolder => _charFolder;
+ private string StatePath => Path.Combine(_charFolder, "ilt-hub.json");
+ private string TxPath => Path.Combine(_charFolder, "ilt-hub-transactions.json");
+ private string CharProfileDir => Path.Combine(_charFolder, "ilt-hub-profiles");
+ private static string SharedProfileDir => Path.Combine(SharedRoot, "IltHubProfiles");
+
+ // ── State ───────────────────────────────────────────────────────────────
+
+ /// Loads the live state, returning defaults when the file is missing or unreadable.
+ public IltHubState LoadState()
+ {
+ try
+ {
+ if (_charFolder.Length > 0 && File.Exists(StatePath))
+ {
+ string json = File.ReadAllText(StatePath);
+ var s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.IltHubState);
+ if (s != null)
+ {
+ Normalize(s);
+ _lastStateJson = json;
+ return s;
+ }
+ }
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {StatePath}"); }
+ return new IltHubState();
+ }
+
+ /// Writes the state only when its JSON differs from the last write.
+ public void SaveStateIfDirty(IltHubState state)
+ {
+ if (_charFolder.Length == 0) return;
+ try
+ {
+ string json = JsonSerializer.Serialize(state, RynthAiJsonContext.Default.IltHubState);
+ if (json == _lastStateJson) return;
+ Directory.CreateDirectory(_charFolder);
+ WriteAtomic(StatePath, json);
+ _lastStateJson = json;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {StatePath}"); }
+ }
+
+ /// Repairs null collections / out-of-range values after deserialization.
+ private static void Normalize(IltHubState s)
+ {
+ s.ServerOptions ??= new IltServerOptionsSnapshot();
+ s.ServerOptions.Bits = new Dictionary(s.ServerOptions.Bits ?? new(), StringComparer.OrdinalIgnoreCase);
+ s.Bank ??= new IltBankState();
+ s.Pet ??= new IltPetState();
+ s.Pet.PetLog ??= new();
+ s.Pet.ShinyLog ??= new();
+ s.Pet.Assignments ??= new();
+ s.Pet.Assignments.RemoveAll(a => a == null || string.IsNullOrWhiteSpace(a.Name));
+ s.Pet.CosmeticPetName ??= string.Empty;
+ 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.Character ??= new IltCharacterState();
+ s.Character.ItemConversions ??= new();
+ s.Character.QuestFavorites ??= new();
+ s.Character.QuestFavorites.RemoveAll(string.IsNullOrWhiteSpace);
+ s.Character.AugTargets = new Dictionary(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
+ s.Character.CharmsSeen = new Dictionary(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase);
+ s.Gear ??= new IltGearState();
+ s.Gear.DispelInclusions ??= new();
+ s.Gear.DispelExclusions ??= new();
+ s.Games ??= new IltGamesState();
+ s.Guardian ??= new IltGuardianState();
+ s.Guardian.TurnInCounts = new Dictionary(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
+ s.Guardian.CooldownUntilUtc = new Dictionary(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase);
+ s.Guardian.CooldownHoursAssumed = Math.Clamp(s.Guardian.CooldownHoursAssumed, 1, 72);
+ s.SelectedTab = Math.Clamp(s.SelectedTab, 0, 4);
+ s.Gear.SplitArrowTarget = Math.Clamp(s.Gear.SplitArrowTarget, 0, 10);
+ }
+
+ // ── Transactions ────────────────────────────────────────────────────────
+
+ public List LoadTransactions()
+ {
+ try
+ {
+ if (_charFolder.Length > 0 && File.Exists(TxPath))
+ {
+ string json = File.ReadAllText(TxPath);
+ var list = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.IltBankTransactionList);
+ if (list != null) { _lastTxJson = json; return list; }
+ }
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {TxPath}"); }
+ return new List();
+ }
+
+ public void SaveTransactionsIfDirty(List list)
+ {
+ if (_charFolder.Length == 0) return;
+ try
+ {
+ if (list.Count > MaxTransactions)
+ list.RemoveRange(0, list.Count - MaxTransactions);
+ string json = JsonSerializer.Serialize(list, RynthAiJsonContext.Default.IltBankTransactionList);
+ if (json == _lastTxJson) return;
+ Directory.CreateDirectory(_charFolder);
+ WriteAtomic(TxPath, json);
+ _lastTxJson = json;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {TxPath}"); }
+ }
+
+ // ── Profiles ────────────────────────────────────────────────────────────
+
+ /// Lists profile names. Shared ones are prefixed "shared:".
+ public List ListProfiles()
+ {
+ var names = new List();
+ try
+ {
+ if (Directory.Exists(CharProfileDir))
+ names.AddRange(Directory.GetFiles(CharProfileDir, "*.json").Select(Path.GetFileNameWithoutExtension).OfType());
+ if (Directory.Exists(SharedProfileDir))
+ names.AddRange(Directory.GetFiles(SharedProfileDir, "*.json").Select(p => "shared:" + Path.GetFileNameWithoutExtension(p)));
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"list profiles"); }
+ names.Sort(StringComparer.OrdinalIgnoreCase);
+ return names;
+ }
+
+ /// Saves the preference parts of as a named profile.
+ public bool SaveProfile(IltHubState state, string name, bool shared, out string error)
+ {
+ error = string.Empty;
+ string safe = SanitizeName(name);
+ if (safe.Length == 0) { error = "Profile name is empty."; return false; }
+ try
+ {
+ string dir = shared ? SharedProfileDir : CharProfileDir;
+ Directory.CreateDirectory(dir);
+ var copy = Clone(state);
+ StripRuntime(copy);
+ WriteAtomic(Path.Combine(dir, safe + ".json"), JsonSerializer.Serialize(copy, RynthAiJsonContext.Default.IltHubState));
+ return true;
+ }
+ catch (Exception ex) { error = ex.Message; return false; }
+ }
+
+ ///
+ /// Loads a profile onto , keeping runtime data (balances,
+ /// server bits, rosters, import flag) from the current state.
+ ///
+ public bool LoadProfile(IltHubState target, string name, out string error)
+ {
+ error = string.Empty;
+ bool shared = name.StartsWith("shared:", StringComparison.OrdinalIgnoreCase);
+ string safe = SanitizeName(shared ? name.Substring(7) : name);
+ string path = Path.Combine(shared ? SharedProfileDir : CharProfileDir, safe + ".json");
+ try
+ {
+ if (!File.Exists(path)) { error = $"Profile not found: {name}"; return false; }
+ var p = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.IltHubState);
+ if (p == null) { error = "Profile file is empty."; return false; }
+ Normalize(p);
+ target.Pet = KeepRosters(p.Pet, target.Pet);
+ target.Character = p.Character;
+ target.Gear = p.Gear;
+ target.Games = p.Games;
+ target.Bank.AutoRefreshSeconds = p.Bank.AutoRefreshSeconds;
+ target.ForceLeaftideFeatures = p.ForceLeaftideFeatures;
+ target.GamesHudVisible = p.GamesHudVisible;
+ return true;
+ }
+ catch (Exception ex) { error = ex.Message; return false; }
+ }
+
+ private static IltPetState KeepRosters(IltPetState incoming, IltPetState current)
+ {
+ incoming.PetLog = current.PetLog;
+ incoming.ShinyLog = current.ShinyLog;
+ return incoming;
+ }
+
+ private static IltHubState Clone(IltHubState s)
+ => JsonSerializer.Deserialize(JsonSerializer.Serialize(s, RynthAiJsonContext.Default.IltHubState),
+ RynthAiJsonContext.Default.IltHubState) ?? new IltHubState();
+
+ /// Removes character-specific runtime data before a profile is written.
+ private static void StripRuntime(IltHubState s)
+ {
+ s.ServerOptions = new IltServerOptionsSnapshot();
+ var keepRefresh = s.Bank.AutoRefreshSeconds;
+ s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh };
+ s.Pet.PetLog = new();
+ s.Pet.ShinyLog = new();
+ s.UbSidecarsImported = false;
+ s.WindowVisible = false;
+ }
+
+ private static string SanitizeName(string name)
+ {
+ var invalid = Path.GetInvalidFileNameChars();
+ return new string((name ?? string.Empty).Trim().Where(c => !invalid.Contains(c)).ToArray());
+ }
+
+ // ── UtilityBelt sidecar import ──────────────────────────────────────────
+
+ ///
+ /// One-time import of UB's bankdata (balances, transactions) and item conversions.
+ /// Searches Documents\Decal Plugins\UtilityBelt\<world>\<char>; when the world is
+ /// unknown every world folder containing the character is tried. Returns a summary.
+ ///
+ public string ImportUbSidecars(IltHubState state, List txLog, string world, string charName)
+ {
+ if (string.IsNullOrWhiteSpace(charName)) return "character name unknown";
+ string ubRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
+ if (!Directory.Exists(ubRoot)) return "no UtilityBelt folder";
+
+ var charDirs = new List();
+ if (!string.IsNullOrWhiteSpace(world))
+ charDirs.Add(Path.Combine(ubRoot, world, charName));
+ try
+ {
+ foreach (string w in Directory.GetDirectories(ubRoot))
+ {
+ string d = Path.Combine(w, charName);
+ if (!charDirs.Contains(d, StringComparer.OrdinalIgnoreCase)) charDirs.Add(d);
+ }
+ }
+ catch { /* unreadable Documents subfolder: fall through with what we have */ }
+
+ foreach (string dir in charDirs)
+ {
+ string bankDir = Path.Combine(dir, "bankdata");
+ if (!Directory.Exists(bankDir) && !Directory.Exists(dir)) continue;
+
+ int parts = 0;
+ parts += ImportBalances(Path.Combine(bankDir, "bankbalances.json"), state.Bank) ? 1 : 0;
+ int tx = ImportTransactions(Path.Combine(bankDir, "transactions.json"), txLog);
+ int conv = ImportConversions(new[]
+ {
+ Path.Combine(bankDir, "itemconversions.json"),
+ Path.Combine(dir, "itemconversions.json"),
+ }, state.Character.ItemConversions);
+
+ if (parts + tx + conv > 0)
+ return $"imported from {dir}: balances {(parts > 0 ? "yes" : "no")}, {tx} transactions, {conv} conversions";
+ }
+ return "no UtilityBelt bank data found for " + charName;
+ }
+
+ private bool ImportBalances(string path, IltBankState bank)
+ {
+ if (!File.Exists(path)) return false;
+ try
+ {
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ var root = doc.RootElement;
+ if (root.ValueKind != JsonValueKind.Object) return false;
+ bank.Pyreals = ReadLong(root, "Pyreals");
+ bank.Luminance = ReadLong(root, "Luminance");
+ bank.LegendaryKeys = ReadLong(root, "LegendaryKeys");
+ bank.MythicalKeys = ReadLong(root, "MythicalKeys");
+ bank.EnlightenedCoins = ReadLong(root, "EnlightenedCoins");
+ bank.WeaklyEnlightenedCoins = ReadLong(root, "WeaklyEnlightenedCoins");
+ if (TryGetProp(root, "LastUpdated", out var lu) && lu.ValueKind == JsonValueKind.String && lu.TryGetDateTime(out var dt))
+ bank.LastUpdated = dt;
+ return true;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB balances import"); return false; }
+ }
+
+ private int ImportTransactions(string path, List txLog)
+ {
+ if (!File.Exists(path)) return 0;
+ try
+ {
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ if (doc.RootElement.ValueKind != JsonValueKind.Array) return 0;
+ int added = 0;
+ foreach (var e in doc.RootElement.EnumerateArray())
+ {
+ if (e.ValueKind != JsonValueKind.Object) continue;
+ var t = new IltBankTransaction
+ {
+ Type = ReadString(e, "Type"),
+ Currency = ReadString(e, "Currency"),
+ Amount = ReadLong(e, "Amount"),
+ OtherPlayer = ReadString(e, "OtherPlayer"),
+ Description = ReadString(e, "Description"),
+ };
+ if (TryGetProp(e, "Timestamp", out var ts) && ts.ValueKind == JsonValueKind.String && ts.TryGetDateTime(out var dt))
+ t.Timestamp = dt;
+ // Skip exact duplicates so re-running the import can't double the log.
+ if (txLog.Any(x => x.Timestamp == t.Timestamp && x.Amount == t.Amount && x.OtherPlayer == t.OtherPlayer)) continue;
+ txLog.Add(t);
+ added++;
+ }
+ txLog.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp));
+ return added;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB transactions import"); return 0; }
+ }
+
+ private int ImportConversions(string[] paths, List table)
+ {
+ foreach (string path in paths)
+ {
+ if (!File.Exists(path)) continue;
+ try
+ {
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ if (doc.RootElement.ValueKind != JsonValueKind.Array) continue;
+ int added = 0;
+ foreach (var e in doc.RootElement.EnumerateArray())
+ {
+ string name = ReadString(e, "ItemName");
+ if (name.Length == 0) continue;
+ var existing = table.FirstOrDefault(c => c.ItemName.Equals(name, StringComparison.OrdinalIgnoreCase));
+ if (existing == null) { existing = new IltItemConversion { ItemName = name }; table.Add(existing); added++; }
+ existing.ItemsPerConversion = Math.Max(1, (int)ReadLong(e, "ItemsPerConversion"));
+ existing.CoinsPerConversion = (int)ReadLong(e, "CoinsPerConversion");
+ }
+ return added;
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB conversions import"); }
+ }
+ return 0;
+ }
+
+ // ── JSON helpers (case-insensitive property access) ─────────────────────
+
+ private static bool TryGetProp(JsonElement obj, string name, out JsonElement value)
+ {
+ foreach (var p in obj.EnumerateObject())
+ if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { value = p.Value; return true; }
+ value = default;
+ return false;
+ }
+
+ private static long ReadLong(JsonElement obj, string name)
+ {
+ if (!TryGetProp(obj, name, out var v)) return 0;
+ if (v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l)) return l;
+ if (v.ValueKind == JsonValueKind.String) return IltParse.ParseLeadingLong(v.GetString() ?? string.Empty);
+ return 0;
+ }
+
+ private static string ReadString(JsonElement obj, string name)
+ {
+ if (!TryGetProp(obj, name, out var v)) return string.Empty;
+ return v.ValueKind switch
+ {
+ JsonValueKind.String => v.GetString() ?? string.Empty,
+ JsonValueKind.Number => v.GetRawText(),
+ _ => string.Empty,
+ };
+ }
+
+ /// Write-then-rename so a crash mid-write never leaves a truncated file.
+ private static void WriteAtomic(string path, string contents)
+ {
+ string tmp = path + ".tmp";
+ File.WriteAllText(tmp, contents);
+ File.Move(tmp, path, overwrite: true);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubUi.cs
new file mode 100644
index 0000000..27f2112
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltHubUi.cs
@@ -0,0 +1,242 @@
+// IltHubUi.cs — The ILT Hub's ImGui windows (render thread only).
+//
+// The Mini Remote is the Hub. Each former tab is its own window, opened from the Mini Remote's
+// Options or "/ra hub open ": ILT Character (world status, Force-ILT, profiles, session
+// rates), Quests (IltQuests), Pets, Banking, Gear, Games and Guardian (IltGuardian: Temple riddle
+// translator, hand-in, attribute turn-in tracker). A section window draws only while the
+// server reports its feature on. Augmentations / Enlightenment / XP planning live on the engine
+// Skills panel. All AC actions go through IltHubContext.Post / Confirm so nothing here touches
+// the game directly.
+using System;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltHubUi
+{
+ private const string ConfirmPopupId = "Confirm##iltconfirm";
+ private static readonly int SectionCount = IltSections.All.Length;
+
+ private readonly IltHubController _hub;
+ private readonly IltHubContext _ctx;
+ private IltConfirmRequest? _confirm;
+ private bool _confirmOpened;
+ private string _profileName = string.Empty;
+ private bool _profileShared;
+ private string[] _profileList = Array.Empty();
+ private int _profileIdx;
+
+ // Per section (indexed by IltSection): drawn last frame (for shown/hidden log events) and
+ // whether the off-screen check already ran for the current show.
+ private readonly bool[] _wasDrawn = new bool[SectionCount];
+ private readonly bool[] _rescueChecked = new bool[SectionCount];
+
+ // Cached so the per-frame window calls don't allocate a delegate each time.
+ private readonly Action _characterBody, _petsBody, _bankingBody, _gearBody, _gamesBody, _guardianBody;
+
+ public IltHubUi(IltHubController hub, IltHubContext ctx)
+ {
+ _hub = hub;
+ _ctx = ctx;
+ _characterBody = RenderCharacterBody;
+ _petsBody = () => _hub.Pets.Render();
+ _bankingBody = () => _hub.Banking.Render();
+ _gearBody = () => _hub.Gear.Render();
+ _gamesBody = () => _hub.Games.Render();
+ _guardianBody = () => _hub.Guardian.Render();
+ }
+
+ public void Render()
+ {
+ // Distinct first-use offsets so sections opened together don't stack exactly.
+ RenderSectionWindow(IltSection.Character, "ILT Character##iltcharwin", new Vector2(520, 480), Vector2.Zero, _characterBody);
+ RenderSectionWindow(IltSection.Pet, "Pets##iltpetswin", new Vector2(560, 620), Vector2.Zero, _petsBody);
+ RenderSectionWindow(IltSection.Banking, "Banking##iltbankwin", new Vector2(560, 560), new Vector2(80, 80), _bankingBody);
+ RenderSectionWindow(IltSection.Gear, "Gear##iltgearwin", new Vector2(560, 560), new Vector2(120, 120), _gearBody);
+ RenderSectionWindow(IltSection.Games, "Games##iltgameswin", new Vector2(520, 480), new Vector2(160, 160), _gamesBody);
+ RenderSectionWindow(IltSection.Guardian, "Guardian##iltguardianwin", new Vector2(540, 520), new Vector2(200, 120), _guardianBody);
+ LogSectionTransition(IltSection.Quests, _ctx.State.Character.QuestTrackerPoppedOut && _hub.SectionAvailable(IltSection.Quests));
+ _hub.Games.RenderHud();
+ _hub.Quests.RenderFloatingWindows();
+ RenderConfirm();
+ }
+
+ ///
+ /// One section window: drawn while its open flag is set and the section is available, centred
+ /// on first use and moved back on screen once per show if a saved spot left it off-screen.
+ /// Closing it with the title-bar X clears the open flag.
+ ///
+ private void RenderSectionWindow(IltSection section, string title, Vector2 size, Vector2 offset, Action body)
+ {
+ var cs = _ctx.State.Character;
+ int i = (int)section;
+ bool drawn = IltSections.IsOpen(cs, section) && _hub.SectionAvailable(section);
+ LogSectionTransition(section, drawn);
+ if (!drawn) { _rescueChecked[i] = false; return; }
+
+ UiPlacement.CenterFirstUse(offset);
+ ImGui.SetNextWindowSize(size, ImGuiCond.FirstUseEver);
+ bool open = true;
+ if (ImGui.Begin(title, ref open))
+ {
+ if (UiPlacement.RescueOncePerShow(ref _rescueChecked[i]))
+ {
+ Vector2 moved = ImGui.GetWindowPos();
+ RynthLog.Write(LogCat.IltHub, $"[IltHub] {IltSections.Label(section)} window was off-screen - moved to ({moved.X:0},{moved.Y:0}).");
+ }
+ body();
+ }
+ ImGui.End();
+ if (!open) IltSections.SetOpen(cs, section, false);
+ }
+
+ /// Logs the first frame a section window is (or stops being) drawn, proving the overlay renders it.
+ private void LogSectionTransition(IltSection section, bool drawn)
+ {
+ int i = (int)section;
+ if (drawn == _wasDrawn[i]) return;
+ _wasDrawn[i] = drawn;
+ string label = IltSections.Label(section);
+ if (drawn)
+ RynthLog.Event(LogEvents.IltWindowShown, $"{label} window shown (world='{_ctx.Options.WorldName}', available={_hub.Available})");
+ else
+ RynthLog.Event(LogEvents.IltWindowHidden, $"{label} window hidden");
+ }
+
+ /// ILT Character window: world / options header, then session rates (or why the Hub is idle).
+ private void RenderCharacterBody()
+ {
+ RenderHeader();
+ ImGui.Separator();
+ if (!_hub.Available) { RenderUnavailable(); return; }
+ if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render();
+ ImGui.Spacing();
+ ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab");
+ ImGui.TextDisabled("(right-click the dashboard's Char button > Progression).");
+ }
+
+ private void RenderHeader()
+ {
+ var o = _ctx.Options;
+ string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
+ ImGui.TextColored(o.IsIltLikeWorld ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute, world);
+ ImGui.SameLine();
+ ImGui.TextDisabled(o.IsRefreshing ? "checking server options..."
+ : o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet"
+ : $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}");
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true));
+
+ bool force = _ctx.State.ForceLeaftideFeatures;
+ if (ImGui.Checkbox("Treat this world as ILT", ref force)) _ctx.State.ForceLeaftideFeatures = force;
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip("World-identity override only: the Hub asks the server which features exist.\nIt never turns a feature on by itself.");
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); }
+ RenderProfilesPopup();
+ }
+
+ private void RenderProfilesPopup()
+ {
+ if (!ImGui.BeginPopup("##iltprofiles")) return;
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Hub profiles (settings only; no balances)");
+ ImGui.SetNextItemWidth(180);
+ ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u);
+ ImGui.SameLine();
+ ImGui.Checkbox("shared", ref _profileShared);
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Save"))
+ {
+ string n = _profileName; bool sh = _profileShared;
+ _ctx.Post(() =>
+ {
+ _ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[ILT Hub] Saved profile '{n}'." : "[ILT Hub] Save failed: " + err);
+ _profileList = _ctx.Store.ListProfiles().ToArray();
+ });
+ }
+ var list = _profileList;
+ if (list.Length > 0)
+ {
+ _profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1);
+ ImGui.SetNextItemWidth(180);
+ ImGui.Combo("##proflist", ref _profileIdx, list, list.Length);
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Load"))
+ {
+ string n = list[_profileIdx];
+ _ctx.Confirm("Load Hub profile", $"Replace the current Hub settings with profile '{n}'?",
+ () => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[ILT Hub] Loaded profile '{n}'." : "[ILT Hub] Load failed: " + err),
+ "Load");
+ }
+ }
+ else ImGui.TextDisabled("No saved profiles.");
+ ImGui.EndPopup();
+ }
+
+ private void RenderUnavailable()
+ {
+ var o = _ctx.Options;
+ if (!o.IsIltLikeWorld)
+ {
+ ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT Hub is idle. "
+ + "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh.");
+ }
+ else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue)
+ {
+ ImGui.TextWrapped("Checking which ILT features this server has enabled...");
+ }
+ else
+ {
+ ImGui.TextWrapped("The server did not report any ILT Hub features as enabled. Press Refresh to check again.");
+ }
+ }
+
+ // ── Confirmation modal ──────────────────────────────────────────────────
+
+ private void RenderConfirm()
+ {
+ if (_confirm == null)
+ {
+ if (!_ctx.TryTakeConfirm(out var next)) return;
+ _confirm = next;
+ _confirmOpened = false;
+ }
+ if (!_confirmOpened)
+ {
+ ImGui.OpenPopup(ConfirmPopupId);
+ _confirmOpened = true;
+ }
+
+ ImGui.SetNextWindowSize(new Vector2(420, 0), ImGuiCond.Appearing);
+ bool keepOpen = true;
+ if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize))
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _confirm.Title);
+ ImGui.Separator();
+ ImGui.TextWrapped(_confirm.Message);
+ ImGui.Spacing();
+ if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0)))
+ {
+ var act = _confirm.OnYes;
+ if (act != null) _ctx.Post(act);
+ _confirm = null;
+ ImGui.CloseCurrentPopup();
+ }
+ ImGui.SameLine();
+ if (ImGui.Button("Cancel##iltno", new Vector2(120, 0)))
+ {
+ _confirm = null;
+ ImGui.CloseCurrentPopup();
+ }
+ ImGui.EndPopup();
+ }
+ else
+ {
+ // Closed with the title-bar X (or never opened): treat as cancel.
+ _confirm = null;
+ }
+ if (!keepOpen) _confirm = null;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltInventory.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltInventory.cs
new file mode 100644
index 0000000..147779b
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltInventory.cs
@@ -0,0 +1,309 @@
+// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature.
+//
+// One place for: WCID lookups (cached — the engine call is cheap but not free), stack
+// counting, "is it equipped", appraisal requests (throttled), charm ON/OFF status from the
+// appraisal Use text, and player int/bool/quad reads. Features never talk to the cache or
+// the host for item facts directly, so behaviour (and its edge cases) stays consistent.
+// Pump-thread only.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Loot;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+///
+/// Registered ACECustom charm (CharmAbilityRegistry): display name, every known WCID (base +
+/// tier variants), the player PropertyBool the server sets while the ability is active (0 when
+/// it is kept in memory only, like Auto-Rebuff) and a one-line effect summary.
+///
+internal sealed record IltCharmDef(string Name, uint[] Wcids, uint PlayerFlag = 0, string Effect = "");
+
+internal sealed class IltInventory
+{
+ // ── Well-known WCIDs (ACECustom content) ────────────────────────────────
+ public const uint WcidPyreal = 273;
+ public const uint WcidEnlightenedCoin = 300004;
+ public const uint WcidEnlToken = 300000;
+ public const uint WcidEnlMedallion = 90000217;
+ public const uint WcidEnlSigil = 300101189;
+ public const uint WcidEnlCrest = 98769999;
+ public const uint WcidEncapsulatedSpirit = 49485;
+ public const uint WcidRuneOfDispel = 30133;
+ 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;
+
+ // ── Property ids used by several features ───────────────────────────────
+ public const uint IntStackSize = 12;
+ public const uint IntValidLocations = 9;
+ public const uint IntLevel = 25;
+ public const uint IntMaxStructure = 91;
+ public const uint IntStructure = 92;
+ public const uint IntNumTimesTinkered = 171;
+ public const uint IntImbuedEffect = 179;
+ public const uint IntCleaving = 292;
+ public const uint IntItemMaxLevel = 319;
+ public const uint IntSummoningMastery = 362;
+ public const uint IntEnlightenment = 390;
+ public const uint IntSplitArrowCount = 9031;
+ public const uint IntMaterialType = 131;
+ public const uint IntUses = 92;
+ /// ACECustom charm item: current tier (PropertyInt.CharmLevel).
+ public const uint IntCharmLevel = 50005;
+ /// ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel).
+ public const uint IntCharmMaxLevel = 50006;
+ public const uint StrUse = 14;
+ public const uint QuadTotalXp = 1;
+ public const uint QuadAvailableXp = 2;
+ public const uint QuadItemTotalXp = 4;
+ public const uint BoolNeverChunk = 9030;
+ public const uint BoolPyrealRefillActive = 9049;
+ public const uint BoolUniversalMasteryActive = 50038;
+
+ ///
+ /// Every charm in ACECustom's CharmAbilityRegistry (WCIDs and player flags match the server's
+ /// WCIDToAbilityId map and PropertyBool ids). Guardian Hand is not a registry charm and has no
+ /// published WCID — see IltGear.
+ ///
+ public static readonly IltCharmDef[] Charms =
+ {
+ new("Mana Barrier", new uint[] { 777700001, 777700054, 777710004, 777720004 }, 50010,
+ "Mana absorbs incoming damage (better ratio at higher tiers)."),
+ new("Infinite Casting", WcidInfiniteCastingStone, 50028,
+ "Infinite Casting Stone: spells cast without consuming components."),
+ new("Asheron's Favor", new uint[] { 777700020, 777710002, 777720002 }, 50030,
+ "+10 / 15 / 20% health and +50 / 100 / 250 natural armor."),
+ new("Artisan's", new uint[] { 777700021, 777710003, 777720003 }, 50031,
+ "Imbue success chance +4 / 8 / 12%."),
+ new("Shrapnel", new uint[] { 777700022 }, 50032,
+ "Tectonic Rifts cast as Rocky Shrapnel (Rocky Shrapnel must be learned)."),
+ new("Agony", new uint[] { 777700023 }, 50033,
+ "Tectonic Rifts I casts as Ring of Unspeakable Agony (the spell must be learned)."),
+ new("Split Cast", new uint[] { 777700024 }, 50035,
+ "Streak, Arc and Bolt spells split to several nearby targets."),
+ new("Explosive Arrow", new uint[] { 777700025, 777710005, 777720005 }, 50036,
+ "Arrow hits detonate an elemental ring at the target."),
+ new("Omni Strike", new uint[] { 777700026 }, 50037,
+ "Melee hits use the damage type the target is weakest to."),
+ new("Fork", new uint[] { 777700027, 777710007, 777720007 }, 50039,
+ "Streak, Arc and Bolt projectiles fork to nearby enemies (50 / 75 / 100% damage)."),
+ new("Auto-Rebuff", new uint[] { 777700300 }, 0,
+ "Keeps your buffs up automatically."),
+ new("Summon Essence Refill", new uint[] { WcidSummonRefillCharm }, BoolPyrealRefillActive,
+ "Refills an empty pet essence from banked pyreals when you summon."),
+ new("Universal Summoning Mastery", new uint[] { WcidUniversalMasteryCharm }, BoolUniversalMasteryActive,
+ "Use pet essences of any summoning mastery."),
+ };
+
+ private readonly RynthCoreHost _host;
+ private readonly Func _cache;
+ private readonly Dictionary _wcidCache = new();
+ private readonly Dictionary _lastIdRequest = new();
+
+ /// Don't re-request appraisal for the same object more often than this.
+ private const long IdRequestThrottleMs = 30_000;
+
+ public IltInventory(RynthCoreHost host, Func cache)
+ {
+ _host = host;
+ _cache = cache;
+ }
+
+ public RynthCoreHost Host => _host;
+ public WorldObjectCache? Cache => _cache();
+ public uint PlayerId => _host.GetPlayerId();
+
+ // ── Player state ────────────────────────────────────────────────────────
+
+ /// The client busy hourglass is up (an action is in progress).
+ public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
+
+ /// Player is in peace mode (combat mode NonCombat). True when the engine can't tell.
+ public bool InPeaceMode => !_host.HasGetCurrentCombatMode || _host.GetCurrentCombatMode() == CombatMode.NonCombat;
+
+ public int PlayerInt(uint stype, int fallback = 0)
+ => _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(PlayerId, stype, out int v) ? v : fallback;
+
+ public bool PlayerBool(uint stype)
+ => _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(PlayerId, stype, out bool v) && v;
+
+ public long PlayerQuad(uint stype)
+ => _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(PlayerId, stype, out long v) ? v : 0;
+
+ /// Current/max health from the engine vitals read (0/0 when unavailable).
+ public (uint Cur, uint Max) PlayerHealth()
+ {
+ if (_host.HasGetPlayerVitals && _host.TryGetPlayerVitals(out uint h, out uint mh, out _, out _, out _, out _))
+ return (h, mh);
+ return (0, 0);
+ }
+
+ // ── Item facts ──────────────────────────────────────────────────────────
+
+ /// All items the player carries or wears (snapshot).
+ public IEnumerable Items() => _cache()?.GetInventory() ?? Enumerable.Empty();
+
+ /// Weenie class id, cached per object (0 when unknown).
+ public uint Wcid(WorldObject wo)
+ {
+ if (_wcidCache.TryGetValue(wo.Id, out uint w) && w != 0) return w;
+ if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out w))
+ _wcidCache[wo.Id] = w;
+ return w;
+ }
+
+ public int Int(WorldObject wo, uint stype, int fallback = 0) => wo.Values(unchecked((int)stype), fallback);
+
+ public bool Bool(WorldObject wo, uint stype)
+ => _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v;
+
+ public long Quad(WorldObject wo, uint stype)
+ => _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0;
+
+ public string Str(WorldObject wo, uint stype)
+ => _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty;
+
+ /// Stack size (1 for non-stackables).
+ public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1));
+
+ /// Remaining uses on a structure item (essences, kits, salvage bags).
+ public int Uses(WorldObject wo) => Int(wo, IntStructure, 0);
+
+ public bool IsEquipped(WorldObject wo)
+ => wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId);
+
+ public bool HasAppraisal(WorldObject wo)
+ => !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id));
+
+ /// Requests appraisal data, throttled per object. Returns true if a request was sent.
+ public bool RequestAppraisal(WorldObject wo)
+ {
+ if (!_host.HasRequestId) return false;
+ long now = Environment.TickCount64;
+ if (_lastIdRequest.TryGetValue(wo.Id, out long last) && now - last < IdRequestThrottleMs) return false;
+ _lastIdRequest[wo.Id] = now;
+ return _host.RequestId(unchecked((uint)wo.Id));
+ }
+
+ // ── Finders / counters ──────────────────────────────────────────────────
+
+ public WorldObject? FindByWcid(params uint[] wcids)
+ => Items().FirstOrDefault(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
+
+ public IEnumerable AllByWcid(params uint[] wcids)
+ => Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
+
+ public WorldObject? FindByName(Func predicate)
+ => Items().FirstOrDefault(wo => predicate(wo.Name));
+
+ /// Total stack count of items with any of the given WCIDs.
+ public long CountByWcid(params uint[] wcids)
+ => AllByWcid(wcids).Sum(wo => (long)StackSize(wo));
+
+ /// Total stack count of items whose name matches exactly (case-insensitive).
+ public long CountByName(string name)
+ => Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo));
+
+ ///
+ /// True when the player carries spell components or an Infinite Casting Stone that isn't
+ /// known to be switched OFF (an OFF stone doesn't waive components).
+ ///
+ public bool HasCastingSupplies()
+ => AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off)
+ || Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
+
+ /// Free main-pack slots (best effort: capacity minus direct children; -1 when unknown).
+ public int FreeMainPackSlots()
+ {
+ var cache = _cache();
+ if (cache == null) return -1;
+ int player = unchecked((int)PlayerId);
+ int capacity = PlayerInt((uint)LongValueKey.ItemsCapacity, 102);
+ int used = cache.GetDirectInventory()
+ .Count(wo => wo.Container == player && wo.WieldedLocation <= 0 && wo.ObjectClass != AcObjectClass.Container);
+ return Math.Max(0, capacity - used);
+ }
+
+ // ── Charms ──────────────────────────────────────────────────────────────
+
+ ///
+ /// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
+ /// (throttled) when the text isn't loaded yet.
+ ///
+ public IltTri CharmStatus(WorldObject charm)
+ {
+ string use = Str(charm, StrUse);
+ if (use.Length == 0)
+ {
+ RequestAppraisal(charm);
+ return IltTri.Unknown;
+ }
+ if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return IltTri.On;
+ if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return IltTri.Off;
+ return IltTri.Unknown;
+ }
+
+ ///
+ /// Charm tier and max tier from the item's CharmLevel / CharmMaxLevel ints, else parsed from
+ /// the appraisal Use text ("Charm [Tier 2/3]"). (0, 0) until the appraisal is loaded.
+ ///
+ public (int Tier, int MaxTier) CharmTier(WorldObject charm)
+ {
+ int tier = Int(charm, IntCharmLevel, 0), max = Int(charm, IntCharmMaxLevel, 0);
+ if (tier > 0) return (tier, max);
+ var m = CharmTierText.Match(Str(charm, StrUse));
+ if (!m.Success) return (0, 0);
+ int.TryParse(m.Groups[1].Value, out tier);
+ if (m.Groups[2].Success) int.TryParse(m.Groups[2].Value, out max);
+ return (tier, max);
+ }
+
+ private static readonly System.Text.RegularExpressions.Regex CharmTierText =
+ new(@"Charm \[Tier (\d+)(?:/(\d+))?\]", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
+
+ /// Charm definition for an item (by WCID), or null.
+ public IltCharmDef? CharmDefFor(WorldObject wo)
+ {
+ uint w = Wcid(wo);
+ if (w == 0) return null;
+ return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0);
+ }
+
+ ///
+ /// Every charm the player carries: registered WCIDs plus anything whose Use text starts
+ /// with "Charm [Tier" (generic ACECustom charm format, catches charms added later).
+ ///
+ public List CarriedCharms()
+ {
+ var list = new List();
+ foreach (var wo in Items())
+ {
+ if (CharmDefFor(wo) != null) { list.Add(wo); continue; }
+ if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.Armor
+ or AcObjectClass.Clothing or AcObjectClass.Container or AcObjectClass.Corpse)
+ continue;
+ if (Str(wo, StrUse).StartsWith("Charm [Tier", StringComparison.OrdinalIgnoreCase)
+ || wo.Name.EndsWith(" Charm", StringComparison.OrdinalIgnoreCase))
+ list.Add(wo);
+ }
+ return list;
+ }
+
+ // ── Actions ─────────────────────────────────────────────────────────────
+
+ public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id));
+
+ public bool UseOn(WorldObject source, uint targetId)
+ => _host.HasUseObjectOn && _host.UseObjectOn(unchecked((uint)source.Id), targetId);
+
+ /// Forgets cached WCIDs / appraisal throttles (logout).
+ public void Reset()
+ {
+ _wcidCache.Clear();
+ _lastIdRequest.Clear();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltParse.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltParse.cs
new file mode 100644
index 0000000..8d19ed5
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltParse.cs
@@ -0,0 +1,112 @@
+// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output.
+//
+// Centralised so every feature uses the same number parsing (commas, k/m/b/t suffixes),
+// the same compact K/M/B display, and the same regexes. Regexes are static and built once;
+// RegexOptions.Compiled is harmless under NativeAOT (it falls back to the interpreter).
+using System;
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal static class IltParse
+{
+ private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
+
+ /// "/aug" level line: "Creature: 1,234".
+ public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", Opt);
+
+ /// "/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".
+ public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);
+
+ /// Bank-command amount entry: "1.5m", "250,000", "2b".
+ public static readonly Regex AmountInput = new(@"^([\d,.]+)\s*([kmbt]?)$", Opt | RegexOptions.IgnoreCase);
+
+ /// AC character name: starts with a letter, then letters, spaces, apostrophes or hyphens (max 32).
+ public static readonly Regex CharacterName = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", Opt);
+
+ /// A comma-grouped or plain integer as printed by ACE's N0 format.
+ public const string AmountPattern = @"(?:\d{1,3}(?:,\d{3})+|\d+)";
+
+ /// "Transferred 5,000 Pyreals to Bob" (optional " (offline)" / trailing "--- note").
+ public static readonly Regex BankSent = new(
+ @"^Transferred (" + AmountPattern + @") ([^']+?) to ([^-]+?)(?:\s*---.*)?$", Opt);
+
+ /// "Received 5,000 Pyreals from Bob".
+ public static readonly Regex BankReceived = new(
+ @"^Received (" + AmountPattern + @") ([^']+?) from (.+?)(?:\s*---.*)?$", Opt);
+
+ /// "You've banked 1,234 Luminance" (session rates).
+ public static readonly Regex LumBanked = new(@"You've banked (?[\d,]+)\s+Luminance", Opt | RegexOptions.IgnoreCase);
+
+ /// "/xp all" cost line: "[XP] Your XP cost for next 1 Strength level is: 1,234".
+ public static readonly Regex XpCost = new(@"\[XP\] Your XP cost for next 1 (\w+) level is: ([\d,]+)", Opt);
+
+ /// "/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!".
+ public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt);
+
+ /// Strips commas and parses the leading integer; 0 when absent.
+ public static long ParseLeadingLong(string text)
+ {
+ if (string.IsNullOrEmpty(text)) return 0;
+ string s = text.Replace(",", string.Empty).Trim();
+ int end = 0;
+ while (end < s.Length && char.IsDigit(s[end])) end++;
+ return end > 0 && long.TryParse(s.AsSpan(0, end), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0;
+ }
+
+ ///
+ /// Parses a user-entered amount with optional k/m/b/t suffix ("1.5m" → 1,500,000).
+ /// Returns false for empty, negative, or overflowing input.
+ ///
+ public static bool TryParseAmount(string input, out long amount)
+ {
+ amount = 0;
+ var m = AmountInput.Match((input ?? string.Empty).Trim());
+ if (!m.Success) return false;
+ if (!decimal.TryParse(m.Groups[1].Value.Replace(",", string.Empty), NumberStyles.AllowDecimalPoint,
+ CultureInfo.InvariantCulture, out decimal baseVal))
+ return false;
+ decimal mult = char.ToLowerInvariant(m.Groups[2].Value.Length > 0 ? m.Groups[2].Value[0] : ' ') switch
+ {
+ 'k' => 1_000m,
+ 'm' => 1_000_000m,
+ 'b' => 1_000_000_000m,
+ 't' => 1_000_000_000_000m,
+ _ => 1m,
+ };
+ decimal total = Math.Floor(baseVal * mult);
+ if (total <= 0 || total > long.MaxValue) return false;
+ amount = (long)total;
+ return true;
+ }
+
+ /// Compact display: 950 → "950", 12_300 → "12.3K", 4_500_000 → "4.50M", 2e9 → "2.00B".
+ public static string Compact(double value)
+ {
+ double a = Math.Abs(value);
+ string s = a >= 1e12 ? (value / 1e12).ToString("0.00", CultureInfo.InvariantCulture) + "T"
+ : a >= 1e9 ? (value / 1e9).ToString("0.00", CultureInfo.InvariantCulture) + "B"
+ : a >= 1e6 ? (value / 1e6).ToString("0.00", CultureInfo.InvariantCulture) + "M"
+ : a >= 1e3 ? (value / 1e3).ToString("0.0", CultureInfo.InvariantCulture) + "K"
+ : value.ToString("0", CultureInfo.InvariantCulture);
+ return s;
+ }
+
+ /// Full grouped display: 1234567 → "1,234,567".
+ public static string N0(long value) => value.ToString("N0", CultureInfo.InvariantCulture);
+
+ /// "3d 4h 12m 5s" style duration; "ready" when zero or negative.
+ public static string Duration(TimeSpan span)
+ {
+ if (span <= TimeSpan.Zero) return "ready";
+ if (span.TotalDays >= 1) return $"{(int)span.TotalDays}d {span.Hours}h {span.Minutes}m";
+ if (span.TotalHours >= 1) return $"{span.Hours}h {span.Minutes}m {span.Seconds}s";
+ if (span.TotalMinutes >= 1) return $"{span.Minutes}m {span.Seconds}s";
+ return $"{span.Seconds}s";
+ }
+
+ /// Strips "<Tell:…>" style markup the chat window sometimes leaves on names.
+ public static string StripMarkup(string text)
+ => Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim();
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPetStats.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPetStats.cs
new file mode 100644
index 0000000..eb58c6c
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPetStats.cs
@@ -0,0 +1,323 @@
+// IltPetStats.cs — Mag-Tools / UtilityBelt-style stats for one carried pet essence.
+//
+// Line 1: Name, Bond N, Lvl N, Craft N
+// Line 2: Sex, Growth, Mut N, Potency S (A act +P%), Mastery, DamageType
+// Line 3: [D, DR, C, CD, CR, CDR] Uses cur/max Breed Ready|n/m|Rec 4h|Juv|Neut
+//
+// Property ids are ACECustom (ILT) pet-device qualities, the same ones UtilityBelt's Pets
+// tab reads (UB Lib\IltPetAceConstants.cs). Bond, level, craft and ratings are appraisal
+// data: they read 0 until the essence has been ID'd, which HasId reports.
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+/// Pet summon category (UB Pets "Type"). Persisted as int in .
+internal enum IltPetKind { Combat = 0, Healing = 1, Cosmetic = 2 }
+
+/// Roster sort modes (persisted as int in ).
+internal enum IltPetSort { Priority = 0, Bond = 1, Potency = 2, BreedReady = 3, Level = 4, Uses = 5, Name = 6 }
+
+/// One carried essence with its decoded stats. Built on the pump thread, read by the UI.
+internal sealed class IltPetStats
+{
+ public int Id;
+ public string Name = string.Empty;
+ public uint Wcid;
+ public IltPetKind Kind;
+ /// Kind came from a user assignment rather than auto-detection.
+ public bool KindAssigned;
+
+ public bool HasId;
+ public int Bond;
+ public int Level;
+ public int Craft;
+ public string Sex = "?";
+ public string Growth = string.Empty;
+ public int Mutations;
+ public int StoredPotency;
+ public int ActivePotency;
+ public int DamageBonusPercent;
+ public string Mastery = string.Empty;
+ public string DamageType = string.Empty;
+ public int D, DR, C, CD, CR, CDR;
+ public int UsesCur;
+ public int UsesMax;
+ public string Breed = "-";
+ public bool BreedReady;
+
+ /// Chosen for its kind: in the combat summon list, the heal pet, or the cosmetic pet.
+ public bool Selected;
+ /// Combat summon priority (list index), or int.MaxValue when not in the list.
+ public int Priority = int.MaxValue;
+
+ public string Line1 = string.Empty;
+ public string Line2 = string.Empty;
+ public string Line3 = string.Empty;
+}
+
+/// Reads and formats . Pump thread only (host reads).
+internal static class IltPetStatsReader
+{
+ // ── ACECustom / ACE property ids (UB IltPetAceConstants, PetEssenceItemInfoFormatter) ──
+ private const uint IntDamageType = 45;
+ private const uint IntMaxStructure = 91;
+ private const uint IntStructure = 92;
+ private const uint IntWorkmanship = 105;
+ private const uint IntSummoningMastery = 362;
+ private const uint IntUseLevelRequirement = 364;
+ private const uint IntUseRequiresLevel = 369;
+ private const uint IntGearDamage = 370;
+ private const uint IntGearDamageResist = 371;
+ private const uint IntGearCrit = 372;
+ private const uint IntGearCritResist = 373;
+ private const uint IntGearCritDamage = 374;
+ private const uint IntGearCritDamageResist = 375;
+ private const uint IntDamageRating = 307;
+ private const uint IntDamageResistRating = 308;
+ private const uint IntCritRating = 313;
+ private const uint IntCritDamageRating = 314;
+ private const uint IntCritResistRating = 315;
+ private const uint IntCritDamageResistRating = 316;
+ private const uint IntBondLevel = 9053;
+ private const uint IntCapturedDamageType = 9054;
+ private const uint IntPotencyStored = 9056;
+ private const uint IntMaleBreedingCharges = 9057;
+ private const uint IntMutDamage = 9070;
+ private const uint IntMutDamageResist = 9071;
+ private const uint IntMutCrit = 9072;
+ private const uint IntMutVitality = 9073;
+ private const uint IntMutPotency = 9074;
+ private const uint IntMutationCount = 9075;
+ private const uint IntMaturityKills = 9077;
+ private const uint FloatNextBreedingTime = 9056;
+ private const uint BoolNeutered = 9051;
+ private const uint BoolMaleOverride = 50053;
+ private const uint BoolJuvenile = 50054;
+
+ // ACE PetPotencyMath defaults (UB PetEssencePotencyMath).
+ private const int PotencyActiveCap = 150;
+ private const int PotencyBondDivisor = 10;
+ private const double PotencyDamagePerLevelPercent = 2.0;
+ /// ACE pet_breeding_male_max_charges default.
+ private const int MaleMaxBreedingCharges = 10;
+
+ /// Decodes every stat for and fills the three display lines.
+ public static IltPetStats Read(RynthCoreHost host, IltInventory inv, WorldObject wo, long unixNow)
+ {
+ uint id = unchecked((uint)wo.Id);
+ var s = new IltPetStats
+ {
+ Id = wo.Id,
+ Name = wo.Name,
+ Wcid = inv.Wcid(wo),
+ HasId = inv.HasAppraisal(wo),
+ UsesCur = inv.Int(wo, IntStructure),
+ UsesMax = inv.Int(wo, IntMaxStructure),
+ };
+
+ s.Bond = inv.Int(wo, IntBondLevel);
+ s.Level = inv.Int(wo, IntUseRequiresLevel);
+ if (s.Level <= 0) s.Level = inv.Int(wo, IntUseLevelRequirement);
+ s.Craft = inv.Int(wo, IntWorkmanship);
+
+ // Sex: explicit override when the server set one, else ACE PetDevice.IsMale's GUID hash.
+ bool isMale = TryBool(host, id, BoolMaleOverride, out bool male) ? male : DeriveIsMale(wo.Id);
+ bool neutered = TryBool(host, id, BoolNeutered, out bool n) && n;
+ bool juvenile = TryBool(host, id, BoolJuvenile, out bool j) && j;
+ s.Sex = (isMale ? "M" : "F") + (neutered ? "n" : juvenile ? "j" : string.Empty);
+
+ // Growth only exists on bred essences (9077 present, even when 0).
+ if (TryInt(host, id, IntMaturityKills, out int kills))
+ s.Growth = !juvenile ? "Adult" : kills > 0 ? "Juv " + kills.ToString(CultureInfo.InvariantCulture) : "Juv";
+
+ int total = inv.Int(wo, IntMutationCount);
+ s.Mutations = total > 0 ? total
+ : inv.Int(wo, IntMutDamage) + inv.Int(wo, IntMutDamageResist) + inv.Int(wo, IntMutCrit)
+ + inv.Int(wo, IntMutVitality) + inv.Int(wo, IntMutPotency);
+
+ s.StoredPotency = Math.Max(0, inv.Int(wo, IntPotencyStored));
+ s.ActivePotency = ActivePotency(s.StoredPotency, s.Bond);
+ s.DamageBonusPercent = (int)Math.Round(s.ActivePotency * PotencyDamagePerLevelPercent);
+
+ s.Mastery = inv.Int(wo, IntSummoningMastery) switch
+ {
+ 1 => "Primalist",
+ 2 => "Necromancer",
+ 3 => "Naturalist",
+ _ => string.Empty,
+ };
+
+ int dmg = inv.Int(wo, IntCapturedDamageType);
+ if (dmg <= 0) dmg = inv.Int(wo, IntDamageType);
+ s.DamageType = DamageTypeName(dmg);
+
+ // Gear ratings first (what Mag ItemInfo shows), else the base rating ids.
+ s.D = inv.Int(wo, IntGearDamage);
+ s.DR = inv.Int(wo, IntGearDamageResist);
+ s.C = inv.Int(wo, IntGearCrit);
+ s.CR = inv.Int(wo, IntGearCritResist);
+ s.CD = inv.Int(wo, IntGearCritDamage);
+ s.CDR = inv.Int(wo, IntGearCritDamageResist);
+ if (s.D <= 0 && s.DR <= 0 && s.C <= 0 && s.CR <= 0 && s.CD <= 0 && s.CDR <= 0)
+ {
+ s.D = inv.Int(wo, IntDamageRating);
+ s.DR = inv.Int(wo, IntDamageResistRating);
+ s.C = inv.Int(wo, IntCritRating);
+ s.CD = inv.Int(wo, IntCritDamageRating);
+ s.CR = inv.Int(wo, IntCritResistRating);
+ s.CDR = inv.Int(wo, IntCritDamageResistRating);
+ }
+
+ int charges = inv.Int(wo, IntMaleBreedingCharges);
+ double nextBreed = TryDouble(host, id, FloatNextBreedingTime, out double nb) ? nb : 0;
+ (s.Breed, s.BreedReady) = FormatBreed(isMale, neutered, juvenile, charges, nextBreed, unixNow);
+
+ FormatLines(s);
+ return s;
+ }
+
+ /// Builds Line1..Line3 from the decoded fields (Kind/Selected don't affect the text).
+ public static void FormatLines(IltPetStats s)
+ {
+ var l1 = new StringBuilder(s.Name);
+ if (s.Bond > 0) l1.Append(", Bond ").Append(s.Bond.ToString(CultureInfo.InvariantCulture));
+ if (s.Level > 0) l1.Append(", Lvl ").Append(s.Level.ToString(CultureInfo.InvariantCulture));
+ if (s.Craft > 0) l1.Append(", Craft ").Append(s.Craft.ToString(CultureInfo.InvariantCulture));
+ s.Line1 = l1.ToString();
+
+ var l2 = new StringBuilder(s.Sex);
+ if (s.Growth.Length > 0) l2.Append(", Growth ").Append(s.Growth);
+ l2.Append(", Mut ").Append(s.Mutations.ToString(CultureInfo.InvariantCulture));
+ l2.Append(", Potency ").Append(s.StoredPotency.ToString(CultureInfo.InvariantCulture));
+ if (s.StoredPotency > 0)
+ l2.Append(" (").Append(s.ActivePotency.ToString(CultureInfo.InvariantCulture))
+ .Append(" act +").Append(s.DamageBonusPercent.ToString(CultureInfo.InvariantCulture)).Append("%)");
+ if (s.Mastery.Length > 0) l2.Append(", ").Append(s.Mastery);
+ if (s.DamageType.Length > 0) l2.Append(", ").Append(s.DamageType);
+ s.Line2 = l2.ToString();
+
+ var parts = new List(4);
+ string ratings = RatingsBracket(s);
+ if (ratings.Length > 0) parts.Add(ratings);
+ if (s.UsesMax > 0) parts.Add($"Uses {s.UsesCur}/{s.UsesMax}");
+ else if (s.UsesCur > 0) parts.Add($"Uses {s.UsesCur}");
+ if (s.Breed != "-") parts.Add("Breed " + s.Breed);
+ if (!s.HasId) parts.Add("ID pending");
+ s.Line3 = parts.Count > 0 ? string.Join(" ", parts) : "-";
+ }
+
+ /// Orders rows for display; ties keep a stable name order.
+ public static IltPetStats[] Sort(IEnumerable rows, IltPetSort mode)
+ {
+ var list = new List(rows);
+ Comparison byName = (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
+ Comparison cmp = mode switch
+ {
+ // Selected first, then combat priority, then name.
+ IltPetSort.Priority => (a, b) => Chain(b.Selected.CompareTo(a.Selected), a.Priority.CompareTo(b.Priority), byName(a, b)),
+ IltPetSort.Bond => (a, b) => Chain(b.Bond.CompareTo(a.Bond), byName(a, b)),
+ IltPetSort.Potency => (a, b) => Chain(b.StoredPotency.CompareTo(a.StoredPotency), b.ActivePotency.CompareTo(a.ActivePotency), byName(a, b)),
+ IltPetSort.BreedReady => (a, b) => Chain(b.BreedReady.CompareTo(a.BreedReady), b.Bond.CompareTo(a.Bond), byName(a, b)),
+ IltPetSort.Level => (a, b) => Chain(b.Level.CompareTo(a.Level), byName(a, b)),
+ IltPetSort.Uses => (a, b) => Chain(b.UsesCur.CompareTo(a.UsesCur), byName(a, b)),
+ _ => byName,
+ };
+ list.Sort(cmp);
+ return list.ToArray();
+ }
+
+ private static int Chain(params int[] results)
+ {
+ foreach (int r in results) if (r != 0) return r;
+ return 0;
+ }
+
+ /// ACE PetPotencyMath: min(stored, ceil(bond / 10)), at least 1 with any bond, capped at 150.
+ private static int ActivePotency(int stored, int bond)
+ {
+ if (stored <= 0 || bond <= 0) return 0;
+ int cap = Math.Max(1, (bond + PotencyBondDivisor - 1) / PotencyBondDivisor);
+ return Math.Min(stored, Math.Min(cap, PotencyActiveCap));
+ }
+
+ /// ACE PetDevice.IsMale when no override is set (murmur3 fmix32 on the object GUID).
+ private static bool DeriveIsMale(int objectId)
+ {
+ uint h = unchecked((uint)objectId);
+ h ^= h >> 16;
+ h = unchecked(h * 0x7feb352d);
+ h ^= h >> 15;
+ h = unchecked(h * 0x846ca68b);
+ h ^= h >> 16;
+ return (h & 1) == 0;
+ }
+
+ /// Breeding cell: Neut / Juv / male charges n/max / female "Rec Nh" or "Ready".
+ private static (string Text, bool Ready) FormatBreed(bool isMale, bool neutered, bool juvenile,
+ int maleCharges, double nextBreedingUnix, long unixNow)
+ {
+ if (neutered) return ("Neut", false);
+ if (juvenile) return ("Juv", false);
+ if (isMale)
+ {
+ int ch = Math.Max(0, maleCharges);
+ return ($"{ch}/{MaleMaxBreedingCharges}", ch > 0);
+ }
+ if (nextBreedingUnix > 0 && unixNow < (long)nextBreedingUnix)
+ {
+ long remain = (long)nextBreedingUnix - unixNow;
+ int hours = (int)(remain / 3600);
+ return (hours > 0 ? $"Rec {hours}h" : $"Rec {(int)(remain % 3600 / 60)}m", false);
+ }
+ return ("Ready", true);
+ }
+
+ private static string RatingsBracket(IltPetStats s)
+ {
+ var sb = new StringBuilder();
+ void Add(string label, int v)
+ {
+ if (v <= 0) return;
+ if (sb.Length > 0) sb.Append(", ");
+ sb.Append(label).Append(' ').Append(v.ToString(CultureInfo.InvariantCulture));
+ }
+ Add("D", s.D); Add("DR", s.DR); Add("C", s.C); Add("CD", s.CD); Add("CR", s.CR); Add("CDR", s.CDR);
+ return sb.Length > 0 ? "[" + sb + "]" : string.Empty;
+ }
+
+ /// Single AC DamageType flag → name (combined flags return empty).
+ private static string DamageTypeName(int flags) => flags switch
+ {
+ 1 => "Slash",
+ 2 => "Pierce",
+ 4 => "Bludgeon",
+ 8 => "Cold",
+ 16 => "Fire",
+ 32 => "Acid",
+ 64 => "Lightning",
+ 1024 => "Nether",
+ _ => string.Empty,
+ };
+
+ private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
+ {
+ v = false;
+ return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v);
+ }
+
+ private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v)
+ {
+ v = 0;
+ return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v);
+ }
+
+ private static bool TryDouble(RynthCoreHost host, uint id, uint stype, out double v)
+ {
+ v = 0;
+ return host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out v);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPets.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPets.cs
new file mode 100644
index 0000000..bbf510b
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltPets.cs
@@ -0,0 +1,974 @@
+// IltPets.cs — ILT Hub "Pet" tab.
+//
+// * Pet roster (UtilityBelt Pets-tab style): every carried pet essence with three stat
+// lines (bond / level / craft · sex / mutations / potency / mastery · ratings / uses /
+// breeding), filtered by summon type (Combat / Healing / Cosmetic) and sortable.
+// Pets are detected by type (essence WCID block, summoning-gem icon underlay,
+// Summoning use requirement, ACECustom bond/potency) — a pet-like name only nominates
+// an item for appraisal. Healing Buddy / Dule box and cosmetic naming pick the type,
+// else Combat; any essence can be re-typed ("Add sel." or right-click a row).
+// - Combat: the tick list is the existing ConsumableRules Type=="Pet" list that
+// PetManager summons from (list order = summon priority) — no second summoner.
+// - Healing: the tick picks the heal pet the healing state machine uses.
+// - Cosmetic: the tick picks a display pet; "Keep cosmetic pet out" summons it in
+// peace mode and dismisses it when PetManager needs the slot for a fight.
+// Summon / Despawn act on the highlighted row (or the type's chosen pet).
+// * Pet charms: Summon Essence Refill (server refills an empty essence from banked
+// pyreals) and Universal Summoning Mastery, read from the charm appraisal text and the
+// 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.
+// * /pets and /shinies roster capture (read-only display).
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Numerics;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltPets : IIltFeature
+{
+ private static readonly string[] KindNames = { "Combat", "Healing", "Cosmetic" };
+ private static readonly string[] SortNames = { "Priority", "Bond", "Potency", "Breed ready", "Level", "Uses", "Name" };
+
+ /// Un-ID'd essences auto-appraised per 2 s scan (keeps the server request rate low).
+ private const int AutoAppraisePerScan = 2;
+
+ private readonly IltHubContext _ctx;
+
+ // Healing-pet state machine.
+ private enum HealState { Idle, Summoning, Despawning }
+ private HealState _heal = HealState.Idle;
+ private long _healStartedAt;
+ private long _despawnAt;
+ private long _healCooldownUntil;
+ private int _healEssenceId;
+ private long _lastHealThink;
+ private string _healStatus = "idle";
+
+ // Roster snapshot (rebuilt on the pump thread, read by the render thread).
+ private volatile IltPetStats[] _pets = Array.Empty();
+ private long _lastPetScan;
+
+ // Active-pet / cosmetic bookkeeping (pump thread; the ui* copies are for the render thread).
+ private long _lastPresenceThink;
+ private int _lastSummonEssenceId;
+ private int _cosmeticOutEssenceId;
+ private long _cosmeticNextAt;
+ private volatile string _uiActivePet = string.Empty;
+ private volatile string _cosmeticStatus = "off";
+ private volatile string _hudPetName = string.Empty;
+ private volatile string _hudPetStatus = string.Empty;
+
+ /// Mini Remote pet line: the pet that is out, else the first combat essence in priority order.
+ public string HudPetName => _hudPetName;
+ /// Mini Remote pet status: "Out", "Ready", "Empty" or "Healing" (empty when there is no pet).
+ public string HudPetStatus => _hudPetStatus;
+
+ // Charm / supply status cached for the render thread.
+ private volatile bool _uiRefillActive;
+ private volatile bool _uiMasteryActive;
+ private volatile bool _uiHasCasting = true;
+
+ // Render-thread only: highlighted row and the sorted view cache.
+ private int _highlightId;
+ private IltPetStats[]? _viewSource;
+ private int _viewKind = -1;
+ private int _viewSort = -1;
+ private IltPetStats[] _view = Array.Empty();
+
+ public IltPets(IltHubContext ctx) => _ctx = ctx;
+
+ private IltPetState S => _ctx.State.Pet;
+
+ // ── Classification ──────────────────────────────────────────────────────
+
+ // Pet-device type signals (client-visible assessment properties).
+ private const uint IntMaxStructure = 91;
+ private const uint IntUseRequiresSkill = 366;
+ private const uint IntUseRequiresSkillSpec = 368;
+ private const uint IntBondLevel = 9053; // ACECustom pet essence
+ private const uint IntPotencyStored = 9056; // ACECustom pet essence
+ private const int SkillSummoning = 54;
+ private const uint DidIconUnderlay = 52;
+ /// Low 24 bits of the summoning-gem icon underlay (0x06007420) every pet device carries.
+ private const uint SummonGemUnderlay = 0x007420;
+
+ /// Icon-underlay verdict per object id (the DID never changes; only successful reads are cached).
+ private readonly Dictionary _underlayCache = new();
+
+ ///
+ /// True when the item is a pet device by type, not by name: the ACECustom combat
+ /// essence WCID block, the summoning-gem icon underlay, a Summoning-skill use
+ /// requirement, or ACECustom bond/potency properties. Names (" Essence", heal /
+ /// stamina / cosmetic pet naming) only make an item a candidate, which must then show
+ /// charges (MaxStructure) — so augmentation gems like "Jibril's Essence" stay out.
+ /// Spirits, charms, capture devices and summoned pet creatures are never pets.
+ ///
+ public bool IsPetDevice(WorldObject wo)
+ {
+ uint w = _ctx.Inventory.Wcid(wo);
+ if (w == IltInventory.WcidEncapsulatedSpirit) return false;
+ if (w is >= 78780030 and <= 78780089) return false; // charm block
+ if (w is >= 78780001 and <= 78780012) return false; // capture devices
+ if (w is >= 787802001 and <= 787802072) return false; // summoned combat pet creatures
+ if (w is >= 787801001 and <= 787801072) return true; // combat essence block
+
+ if (HasSummonGemUnderlay(wo)) return true;
+ if (RequiresSummoning(wo)) return true;
+ if (_ctx.Inventory.Int(wo, IntBondLevel) > 0 || _ctx.Inventory.Int(wo, IntPotencyStored, -1) >= 0) return true;
+
+ return IsPetNameCandidate(wo.Name) && _ctx.Inventory.Int(wo, IntMaxStructure) > 0;
+ }
+
+ /// Name hints UB's pet scan uses; never sufficient on their own (see ).
+ private static bool IsPetNameCandidate(string n)
+ => n.EndsWith(" Essence", StringComparison.OrdinalIgnoreCase)
+ || LooksLikeHealPet(n) || LooksLikeStaminaPet(n) || LooksLikeCosmeticPet(n);
+
+ /// UseRequiresSkill / UseRequiresSkillSpec is Summoning (appraisal data).
+ private bool RequiresSummoning(WorldObject wo)
+ => _ctx.Inventory.Int(wo, IntUseRequiresSkill) == SkillSummoning
+ || _ctx.Inventory.Int(wo, IntUseRequiresSkillSpec) == SkillSummoning;
+
+ /// Icon underlay is the summoning gem (network-populated, no appraisal needed; engine 2026.10.4.19+).
+ private bool HasSummonGemUnderlay(WorldObject wo)
+ {
+ if (_underlayCache.TryGetValue(wo.Id, out bool known)) return known;
+ var host = _ctx.Host;
+ if (!host.HasGetObjectDataIdProperty
+ || !host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), DidIconUnderlay, out uint did))
+ return false;
+ bool match = (did & 0x00FFFFFF) == SummonGemUnderlay;
+ _underlayCache[wo.Id] = match;
+ return match;
+ }
+
+ /// "Healing Buddy" / "Dule box" naming used by the server's heal pets.
+ private static bool LooksLikeHealPet(string n)
+ => (n.Contains("healing", StringComparison.OrdinalIgnoreCase) && n.Contains("buddy", StringComparison.OrdinalIgnoreCase))
+ || (n.Contains("dule", StringComparison.OrdinalIgnoreCase) && n.Contains("box", StringComparison.OrdinalIgnoreCase));
+
+ /// Stamina buddy / crate / pet naming.
+ private static bool LooksLikeStaminaPet(string n)
+ => n.Contains("stamina", StringComparison.OrdinalIgnoreCase)
+ && (n.Contains("buddy", StringComparison.OrdinalIgnoreCase) || n.Contains("crate", StringComparison.OrdinalIgnoreCase)
+ || n.Contains("pet", StringComparison.OrdinalIgnoreCase));
+
+ /// Cosmetic / plush / display pet naming.
+ private static bool LooksLikeCosmeticPet(string n)
+ => n.Contains("cosmetic", StringComparison.OrdinalIgnoreCase) || n.Contains("plush", StringComparison.OrdinalIgnoreCase)
+ || n.Contains("display pet", StringComparison.OrdinalIgnoreCase);
+
+ /// Name candidate that hasn't been appraised yet, so its type can't be confirmed.
+ private bool IsUnconfirmedCandidate(WorldObject wo)
+ => IsPetNameCandidate(wo.Name) && !IsPetDevice(wo)
+ && _ctx.Host.HasHasAppraisalData && !_ctx.Inventory.HasAppraisal(wo);
+
+ private IltPetAssignment? FindAssignment(string name)
+ => S.Assignments.FirstOrDefault(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+
+ ///
+ /// Summon type for a carried item: the user's override wins, then the configured heal
+ /// pet. Anything else must be a pet device by type (); its
+ /// naming then picks Healing / Cosmetic, defaulting to Combat. Null = not a pet.
+ ///
+ private IltPetKind? ClassifyKind(WorldObject wo, out bool assigned)
+ {
+ var a = FindAssignment(wo.Name);
+ if (a != null)
+ {
+ assigned = true;
+ return (IltPetKind)Math.Clamp(a.Kind, 0, 2);
+ }
+ assigned = false;
+ if (NameIs(wo, S.HealPetName)) return IltPetKind.Healing;
+ if (!IsPetDevice(wo)) return null;
+ if (LooksLikeHealPet(wo.Name)) return IltPetKind.Healing;
+ if (LooksLikeCosmeticPet(wo.Name)) return IltPetKind.Cosmetic;
+ return IltPetKind.Combat;
+ }
+
+ private static bool NameIs(WorldObject wo, string name)
+ => !string.IsNullOrWhiteSpace(name) && wo.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase);
+
+ private WorldObject? FindCarried(string name)
+ => string.IsNullOrWhiteSpace(name) ? null : _ctx.Inventory.Items().FirstOrDefault(wo => NameIs(wo, name));
+
+ /// Heal-pet essence: the ticked heal pet, else the first Healing-typed essence.
+ private WorldObject? FindHealEssence()
+ {
+ if (!string.IsNullOrWhiteSpace(S.HealPetName)) return FindCarried(S.HealPetName);
+ return _ctx.Inventory.Items().FirstOrDefault(wo => ClassifyKind(wo, out _) == IltPetKind.Healing);
+ }
+
+ // ── Charms / gates ──────────────────────────────────────────────────────
+
+ /// Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).
+ public bool RefillCharmActive()
+ {
+ if (_ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true;
+ var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidSummonRefillCharm);
+ return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
+ }
+
+ public bool MasteryCharmActive()
+ {
+ if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false;
+ if (_ctx.Inventory.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true;
+ var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidUniversalMasteryCharm);
+ return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
+ }
+
+ ///
+ /// PetManager hook: summon from an empty essence (spends banked pyreals) only when the
+ /// player opted in, the refill charm is active, and the server has positively confirmed
+ /// the feature: either /ilt features reported pet_refill on, or the server stamped the
+ /// player's refill bool. An unknown feature state never spends.
+ ///
+ public bool AllowSummonOnEmpty()
+ {
+ if (!S.UsePyrealRefillPath || !_ctx.Options.IsIltLikeWorld || !RefillCharmActive()) return false;
+ bool confirmed = _ctx.Options.IsOn(IltFeature.PetRefill)
+ || _ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive);
+ if (!confirmed) RynthLog.Trace(LogCat.IltPets, "summon-on-empty refused: pet_refill not confirmed by the server");
+ return confirmed;
+ }
+
+ /// PetManager hook: hold combat summons while the heal pet cycle is running.
+ public bool HoldCombatSummons() => _heal != HealState.Idle;
+
+ ///
+ /// PetManager hook (pump thread): a pet already holds the slot and monsters are near.
+ /// When that pet is the cosmetic pet, dismiss it so a combat pet can be summoned.
+ /// Returns true when a dismiss was issued.
+ ///
+ public bool YieldPetForCombat()
+ {
+ if (_heal != HealState.Idle || string.IsNullOrWhiteSpace(S.CosmeticPetName)) return false;
+ var pet = FindOwnPet();
+ var essence = FindCarried(S.CosmeticPetName);
+ if (pet == null || essence == null) return false;
+ if (!PetMatchesEssence(pet, essence) && _cosmeticOutEssenceId != essence.Id) return false;
+ if (_ctx.Inventory.IsBusy || !_ctx.Inventory.Use(essence)) return false;
+
+ long now = IltHubContext.NowMs;
+ _cosmeticOutEssenceId = 0;
+ _cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
+ _cosmeticStatus = "dismissed for combat";
+ RynthLog.Trace(LogCat.IltPets, $"cosmetic pet '{pet.Name}' dismissed so a combat pet can be summoned");
+ return true;
+ }
+
+ // ── Rosters ─────────────────────────────────────────────────────────────
+
+ /// Captures /pets or /shinies into the state (quiet).
+ public void RequestRoster(bool shinies)
+ {
+ RynthLog.Trace(LogCat.IltPets, $"RequestRoster(shinies={shinies})");
+ string cmd = shinies ? "/shinies" : "/pets";
+ if (_ctx.Capture.IsPending(cmd)) return;
+ string header = shinies ? "Your Shiny Log" : "Your Pet Log";
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = cmd,
+ IsResponseLine = t => t.Contains(header, StringComparison.OrdinalIgnoreCase) || IltParse.RosterLine.IsMatch(t),
+ IsTerminator = t => t.Contains(header + " is empty", StringComparison.OrdinalIgnoreCase),
+ IdleEndMs = 1500,
+ FirstLineTimeoutMs = 10000,
+ Eat = true,
+ OnComplete = r =>
+ {
+ if (r.UnknownCommand) { _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.Off); return; }
+ if (r.Lines.Count == 0) return;
+ _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.On);
+ ApplyRoster(shinies, r.Lines);
+ },
+ });
+ }
+
+ /// Also used by the login probe tap so the roster fills without a second command.
+ public void ApplyRoster(bool shinies, List lines)
+ {
+ RynthLog.Trace(LogCat.IltPets, $"ApplyRoster(shinies={shinies}, lines={lines.Count})");
+ var list = new List();
+ foreach (string l in lines)
+ {
+ var m = IltParse.RosterLine.Match(l);
+ if (m.Success) list.Add(m.Groups[2].Value.Trim());
+ }
+ if (shinies) S.ShinyLog = list; else S.PetLog = list;
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ if (nowMs - _lastPetScan >= 2000)
+ {
+ _lastPetScan = nowMs;
+ RebuildPetSnapshot(autoAppraise: true);
+ // Host reads (and appraisal requests) happen here, never on the render thread.
+ _uiRefillActive = RefillCharmActive();
+ _uiMasteryActive = MasteryCharmActive();
+ _uiHasCasting = _ctx.Inventory.HasCastingSupplies();
+ }
+ if (nowMs - _lastHealThink >= 250)
+ {
+ _lastHealThink = nowMs;
+ TickHealing(nowMs);
+ }
+ if (nowMs - _lastPresenceThink >= 1000)
+ {
+ _lastPresenceThink = nowMs;
+ var pet = FindOwnPet();
+ _uiActivePet = pet?.Name ?? string.Empty;
+ TickCosmetic(nowMs, pet);
+ UpdateHudPetLine(pet);
+ }
+ }
+
+ /// Refreshes the Mini Remote's pet name / status pair (pump thread).
+ private void UpdateHudPetLine(WorldObject? pet)
+ {
+ if (pet != null)
+ {
+ _hudPetName = ResolveActiveEssence(pet)?.Name ?? pet.Name;
+ _hudPetStatus = _heal != HealState.Idle ? "Healing" : "Out";
+ return;
+ }
+ var next = ChosenEssence(IltPetKind.Combat);
+ if (next == null) { _hudPetName = string.Empty; _hudPetStatus = string.Empty; return; }
+ _hudPetName = next.Name;
+ _hudPetStatus = _ctx.Inventory.Uses(next) == 0 && !AllowSummonOnEmpty() ? "Empty" : "Ready";
+ }
+
+ public bool OnChat(string text)
+ {
+ // " casts Heal Other ... and restores N points of your health."
+ if (_heal == HealState.Summoning
+ && text.Contains("casts", StringComparison.OrdinalIgnoreCase)
+ && text.Contains("heal other", StringComparison.OrdinalIgnoreCase)
+ && text.Contains("restores", StringComparison.OrdinalIgnoreCase)
+ && text.Contains("points of your health", StringComparison.OrdinalIgnoreCase))
+ {
+ if (S.AutoDespawnAfterHeal)
+ {
+ _heal = HealState.Despawning;
+ _despawnAt = IltHubContext.NowMs + 1000;
+ _healStatus = "heal landed, dismissing";
+ }
+ else
+ {
+ EndHealCycle(IltHubContext.NowMs, "heal landed");
+ }
+ }
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ _heal = HealState.Idle;
+ _pets = Array.Empty();
+ _uiActivePet = string.Empty;
+ _lastSummonEssenceId = 0;
+ _cosmeticOutEssenceId = 0;
+ _cosmeticNextAt = 0;
+ }
+
+ // ── Healing pet ─────────────────────────────────────────────────────────
+
+ private void TickHealing(long now)
+ {
+ if (!S.HealingEnabled)
+ {
+ if (_heal != HealState.Idle) { _heal = HealState.Idle; _healStatus = "off"; }
+ return;
+ }
+
+ switch (_heal)
+ {
+ case HealState.Idle:
+ {
+ if (now < _healCooldownUntil) return;
+ var (cur, max) = _ctx.Inventory.PlayerHealth();
+ if (max == 0) return;
+ int pct = (int)(cur * 100 / max);
+ if (pct >= Math.Clamp(S.HealthThresholdPercent, 1, 99)) { _healStatus = $"HP {pct}% ok"; return; }
+ if (S.MinHealthPoints > 0 && cur < S.MinHealthPoints) { _healStatus = "HP below minimum, not summoning"; return; }
+ if (_ctx.Inventory.IsBusy) return;
+ if (AnyOwnPetPresent()) { _healStatus = "another pet is out"; return; }
+ var essence = FindHealEssence();
+ if (essence == null) { _healStatus = "no heal-pet essence found"; return; }
+ if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _healStatus = "heal-pet essence is empty"; return; }
+ if (!_ctx.Inventory.Use(essence)) return;
+ _healEssenceId = essence.Id;
+ _lastSummonEssenceId = essence.Id;
+ _healStartedAt = now;
+ _heal = HealState.Summoning;
+ _healStatus = $"summoning heal pet (HP {pct}%)";
+ break;
+ }
+ case HealState.Summoning:
+ {
+ long timeout = Math.Max(5, S.PetTimeoutSeconds) * 1000L;
+ if (now - _healStartedAt < timeout) return;
+ // No heal seen in time: dismiss only if the pet is actually up.
+ if (AnyOwnPetPresent()) UseHealEssence();
+ EndHealCycle(now, "timed out waiting for heal");
+ break;
+ }
+ case HealState.Despawning:
+ {
+ if (now < _despawnAt || _ctx.Inventory.IsBusy) return;
+ if (AnyOwnPetPresent()) UseHealEssence();
+ EndHealCycle(now, "dismissed");
+ break;
+ }
+ }
+ }
+
+ private void EndHealCycle(long now, string why)
+ {
+ _heal = HealState.Idle;
+ _healCooldownUntil = now + Math.Max(1, S.RespawnDelaySeconds) * 1000L;
+ _healStatus = why;
+ }
+
+ private void UseHealEssence()
+ {
+ var cache = _ctx.Inventory.Cache;
+ var essence = cache?[_healEssenceId];
+ if (essence != null) _ctx.Inventory.Use(essence);
+ }
+
+ // ── Active pet ──────────────────────────────────────────────────────────
+
+ /// The live "<Me>'s …" creature (server pet naming), or null.
+ private WorldObject? FindOwnPet()
+ {
+ var cache = _ctx.Inventory.Cache;
+ if (cache == null || _ctx.CharName.Length == 0) return null;
+ string prefix = _ctx.CharName + "'s ";
+ return cache.GetLandscape().FirstOrDefault(wo => wo != null && wo.Name.StartsWith(prefix, StringComparison.Ordinal));
+ }
+
+ private bool AnyOwnPetPresent() => FindOwnPet() != null;
+
+ /// "Fire Banshee Essence (250)" → "Fire Banshee": the part the summoned creature is named after.
+ private static string EssenceBaseName(string essenceName)
+ {
+ int i = essenceName.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
+ return (i > 0 ? essenceName[..i] : essenceName).Trim();
+ }
+
+ private static bool PetMatchesEssence(WorldObject pet, WorldObject essence) => PetMatchesEssence(pet, essence.Name);
+
+ private static bool PetMatchesEssence(WorldObject pet, string essenceName)
+ {
+ string b = EssenceBaseName(essenceName);
+ return b.Length > 0 && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Essence that summoned : the longest essence base name contained
+ /// in the creature's name, else the last essence this tab / the heal cycle used.
+ ///
+ private WorldObject? ResolveActiveEssence(WorldObject pet)
+ {
+ WorldObject? best = null;
+ int bestLen = 0;
+ WorldObject? last = null;
+ foreach (var wo in _ctx.Inventory.Items())
+ {
+ if (wo.Id == _lastSummonEssenceId) last = wo;
+ if (ClassifyKind(wo, out _) == null) continue;
+ string b = EssenceBaseName(wo.Name);
+ if (b.Length > bestLen && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase))
+ {
+ best = wo;
+ bestLen = b.Length;
+ }
+ }
+ return best ?? last;
+ }
+
+ // ── Cosmetic pet ────────────────────────────────────────────────────────
+
+ /// Keeps the chosen cosmetic pet summoned while nothing else needs the pet slot.
+ private void TickCosmetic(long now, WorldObject? pet)
+ {
+ if (!S.KeepCosmeticOut) { _cosmeticStatus = "off"; return; }
+ if (string.IsNullOrWhiteSpace(S.CosmeticPetName)) { _cosmeticStatus = "no cosmetic pet ticked"; return; }
+ if (pet != null)
+ {
+ _cosmeticStatus = PetMatchesEssence(pet, S.CosmeticPetName) ? "out" : "another pet is out";
+ return;
+ }
+ if (now < _cosmeticNextAt || _heal != HealState.Idle || _ctx.Inventory.IsBusy) return;
+ if (!_ctx.Inventory.InPeaceMode) { _cosmeticStatus = "waiting for peace mode"; return; }
+ var settings = _ctx.Settings;
+ if (settings != null && settings.IsMacroRunning && settings.SummonPets) { _cosmeticStatus = "combat summoner is active"; return; }
+
+ var essence = FindCarried(S.CosmeticPetName);
+ if (essence == null) { _cosmeticStatus = "essence not carried"; return; }
+ if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty())
+ {
+ _cosmeticStatus = "essence is empty";
+ _cosmeticNextAt = now + 30_000;
+ return;
+ }
+ if (!_ctx.Inventory.Use(essence)) return;
+ _cosmeticOutEssenceId = essence.Id;
+ _lastSummonEssenceId = essence.Id;
+ // Covers the summon round-trip so the pet isn't re-summoned before it appears.
+ _cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
+ _cosmeticStatus = "summoning";
+ RynthLog.Trace(LogCat.IltPets, $"cosmetic pet summon: {essence.Name}");
+ }
+
+ // ── Manual actions (pump thread) ────────────────────────────────────────
+
+ /// Summons from , or the current type's chosen pet when 0.
+ private void SummonPet(int essenceId, IltPetKind kind)
+ {
+ if (FindOwnPet() is { } outPet) { _ctx.Chat($"[ILT Hub] {outPet.Name} is already out — Despawn it first."); return; }
+ if (_heal != HealState.Idle) { _ctx.Chat("[ILT Hub] The heal-pet cycle is running."); return; }
+ if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy — try again in a moment."); return; }
+
+ WorldObject? essence = essenceId != 0 ? _ctx.Inventory.Items().FirstOrDefault(w => w.Id == essenceId) : ChosenEssence(kind);
+ if (essence == null) { _ctx.Chat($"[ILT Hub] No {KindNames[(int)kind].ToLowerInvariant()} pet selected."); return; }
+ if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _ctx.Chat($"[ILT Hub] {essence.Name} has no uses left."); return; }
+ if (!_ctx.Inventory.Use(essence)) return;
+
+ _lastSummonEssenceId = essence.Id;
+ if (NameIs(essence, S.CosmeticPetName)) _cosmeticOutEssenceId = essence.Id;
+ RynthLog.Trace(LogCat.IltPets, $"manual summon: {essence.Name}");
+ }
+
+ /// Dismisses the pet that is out by using the essence that summoned it again.
+ private void DespawnPet()
+ {
+ var pet = FindOwnPet();
+ if (pet == null) { _ctx.Chat("[ILT Hub] No pet is out."); return; }
+ if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy — try again in a moment."); return; }
+ var essence = ResolveActiveEssence(pet);
+ if (essence == null) { _ctx.Chat($"[ILT Hub] Couldn't find the essence for {pet.Name}."); return; }
+ if (!_ctx.Inventory.Use(essence)) return;
+
+ // A manual dismiss shouldn't be undone straight away by "Keep cosmetic pet out".
+ _cosmeticNextAt = IltHubContext.NowMs + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
+ if (essence.Id == _cosmeticOutEssenceId) _cosmeticOutEssenceId = 0;
+ RynthLog.Trace(LogCat.IltPets, $"manual despawn: {pet.Name} via {essence.Name}");
+ }
+
+ /// The pet the type's tick selects: first combat priority, the heal pet, or the cosmetic pet.
+ private WorldObject? ChosenEssence(IltPetKind kind)
+ {
+ switch (kind)
+ {
+ case IltPetKind.Healing:
+ return FindHealEssence();
+ case IltPetKind.Cosmetic:
+ return FindCarried(S.CosmeticPetName);
+ default:
+ var rules = PetRules();
+ foreach (var r in rules)
+ {
+ var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == r.Id || NameIs(w, r.Name));
+ if (wo != null) return wo;
+ }
+ return null;
+ }
+ }
+
+ ///
+ /// Requests appraisal for every carried pet (refreshes bond / potency after fights) and
+ /// for un-appraised pet-named items, whose type is only known once the appraisal lands.
+ ///
+ private void ScanPack()
+ {
+ int pets = 0, candidates = 0;
+ foreach (var wo in _ctx.Inventory.Items())
+ {
+ if (ClassifyKind(wo, out _) != null)
+ {
+ if (_ctx.Inventory.RequestAppraisal(wo)) pets++;
+ }
+ else if (IsUnconfirmedCandidate(wo) && _ctx.Inventory.RequestAppraisal(wo))
+ {
+ candidates++;
+ }
+ }
+ if (pets == 0 && candidates == 0)
+ _ctx.Chat("[ILT Hub] Pets were appraised recently.");
+ else
+ _ctx.Chat(candidates > 0
+ ? $"[ILT Hub] Appraising {pets} pet(s) and checking {candidates} pet-named item(s)…"
+ : $"[ILT Hub] Appraising {pets} pet(s)…");
+ RebuildPetSnapshot(autoAppraise: false);
+ }
+
+ /// Gives the item selected in the game a summon type (pump thread).
+ private void AddSelectedAs(IltPetKind kind)
+ {
+ if (!_ctx.Host.HasGetSelectedItemId) { _ctx.Chat("[ILT Hub] This client build can't read the selected item."); return; }
+ int id = unchecked((int)_ctx.Host.GetSelectedItemId());
+ var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == id);
+ if (wo == null) { _ctx.Chat("[ILT Hub] Select a pet essence in your pack first."); return; }
+ SetKind(wo.Id, wo.Name, kind);
+ _ctx.Chat($"[ILT Hub] {wo.Name} added as a {KindNames[(int)kind].ToLowerInvariant()} pet.");
+ }
+
+ ///
+ /// Re-types an essence (null = back to auto classification) and drops it from the other
+ /// types' selections so a pet is only ever chosen under one type.
+ ///
+ private void SetKind(int id, string name, IltPetKind? kind)
+ {
+ S.Assignments.RemoveAll(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ if (kind is { } k) S.Assignments.Add(new IltPetAssignment { Name = name, Kind = (int)k });
+
+ if (kind != IltPetKind.Combat && PetRules().Any(r => r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
+ SetCombatSelected(id, name, false);
+ if (kind != IltPetKind.Healing && S.HealPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
+ S.HealPetName = string.Empty;
+ if (kind != IltPetKind.Cosmetic && S.CosmeticPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
+ S.CosmeticPetName = string.Empty;
+ RebuildPetSnapshot(autoAppraise: false);
+ }
+
+ /// Applies a roster tick for the row's type (pump thread).
+ private void SetSelected(int id, string name, IltPetKind kind, bool on)
+ {
+ switch (kind)
+ {
+ case IltPetKind.Healing: S.HealPetName = on ? name : string.Empty; break;
+ case IltPetKind.Cosmetic: S.CosmeticPetName = on ? name : string.Empty; break;
+ default: SetCombatSelected(id, name, on); break;
+ }
+ RebuildPetSnapshot(autoAppraise: false);
+ }
+
+ // ── Combat summon list (ConsumableRules Type=="Pet") ────────────────────
+
+ private List PetRules()
+ => _ctx.Settings?.ConsumableRules.Where(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)).ToList()
+ ?? new List();
+
+ /// Adds or removes an essence from the PetManager list (pump thread).
+ private void SetCombatSelected(int id, string name, bool on)
+ {
+ var settings = _ctx.Settings;
+ if (settings == null) return;
+ settings.ConsumableRules.RemoveAll(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)
+ && (r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
+ if (on) settings.ConsumableRules.Add(new ConsumableRule { Id = id, Name = name, Type = "Pet" });
+ _ctx.SaveCombatSettings?.Invoke();
+ }
+
+ /// Moves a configured essence up (-1) or down (+1) in summon priority (pump thread).
+ private void MovePriority(int id, int delta)
+ {
+ var settings = _ctx.Settings;
+ if (settings == null) return;
+ var list = settings.ConsumableRules;
+ int idx = list.FindIndex(r => r.Id == id && r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase));
+ if (idx < 0) return;
+ // Find the neighbouring Pet rule in the requested direction.
+ int j = idx + delta;
+ while (j >= 0 && j < list.Count && !list[j].Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) j += delta;
+ if (j < 0 || j >= list.Count) return;
+ (list[idx], list[j]) = (list[j], list[idx]);
+ _ctx.SaveCombatSettings?.Invoke();
+ RebuildPetSnapshot(autoAppraise: false);
+ }
+
+ // ── Roster snapshot (pump thread) ───────────────────────────────────────
+
+ private void RebuildPetSnapshot(bool autoAppraise)
+ {
+ var rules = PetRules();
+ long unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ var rows = new List();
+ int appraised = 0;
+ foreach (var wo in _ctx.Inventory.Items())
+ {
+ var kind = ClassifyKind(wo, out bool assigned);
+ if (kind == null)
+ {
+ // Pet-named but unconfirmed: its appraisal decides whether it is a pet device.
+ if (autoAppraise && appraised < AutoAppraisePerScan && IsUnconfirmedCandidate(wo)
+ && _ctx.Inventory.RequestAppraisal(wo))
+ appraised++;
+ continue;
+ }
+
+ var s = IltPetStatsReader.Read(_ctx.Host, _ctx.Inventory, wo, unixNow);
+ s.Kind = kind.Value;
+ s.KindAssigned = assigned;
+ int pri = rules.FindIndex(r => r.Id == wo.Id || r.Name.Equals(wo.Name, StringComparison.OrdinalIgnoreCase));
+ s.Priority = pri >= 0 ? pri : int.MaxValue;
+ s.Selected = s.Kind switch
+ {
+ IltPetKind.Healing => NameIs(wo, S.HealPetName),
+ IltPetKind.Cosmetic => NameIs(wo, S.CosmeticPetName),
+ _ => pri >= 0,
+ };
+ rows.Add(s);
+
+ // Stats beyond uses need an appraisal; trickle the requests for un-ID'd essences.
+ if (autoAppraise && !s.HasId && appraised < AutoAppraisePerScan && _ctx.Inventory.RequestAppraisal(wo))
+ appraised++;
+ }
+ _pets = rows.ToArray();
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ public void Render()
+ {
+ var settings = _ctx.Settings;
+ if (settings == null) { ImGui.TextDisabled("Not logged in."); return; }
+
+ RenderRosterHeader(settings);
+ RenderRosterTable();
+ ImGui.Separator();
+ RenderCharms();
+ ImGui.Separator();
+ RenderHealing();
+ ImGui.Separator();
+ RenderRosters();
+ }
+
+ /// Type / Sort combos, action buttons, the active-summon line and per-type options.
+ private void RenderRosterHeader(LegacyUiSettings settings)
+ {
+ var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
+
+ ImGui.TextUnformatted("Type");
+ ImGui.SameLine();
+ ImGui.SetNextItemWidth(100);
+ int k = (int)kind;
+ if (ImGui.Combo("##iltpetkind", ref k, KindNames, KindNames.Length)) { S.RosterKind = k; kind = (IltPetKind)k; _highlightId = 0; }
+ ImGui.SameLine();
+ ImGui.TextUnformatted("Sort");
+ ImGui.SameLine();
+ ImGui.SetNextItemWidth(110);
+ int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
+ if (ImGui.Combo("##iltpetsort", ref sort, SortNames, SortNames.Length)) S.RosterSort = sort;
+
+ int target = _highlightId;
+ var summonKind = kind;
+ if (ImGui.Button("Summon")) _ctx.Post(() => SummonPet(target, summonKind));
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Summon the highlighted pet (or this type's ticked pet).");
+ ImGui.SameLine();
+ if (ImGui.Button("Despawn")) _ctx.Post(DespawnPet);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Dismiss the pet that is out.");
+ ImGui.SameLine();
+ if (ImGui.Button("Scan pack")) _ctx.Post(ScanPack);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device).");
+ ImGui.SameLine();
+ if (ImGui.Button("Add sel.")) _ctx.Post(() => AddSelectedAs(summonKind));
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet.");
+
+ string active = _uiActivePet;
+ if (active.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Active summon: " + active);
+ else ImGui.TextDisabled("Active summon: none");
+
+ switch (kind)
+ {
+ case IltPetKind.Combat:
+ {
+ bool summon = settings.SummonPets;
+ if (ImGui.Checkbox("Summon when monsters are near", ref summon)) _ctx.Post(() => { settings.SummonPets = summon; _ctx.SaveCombatSettings?.Invoke(); });
+ ImGui.SameLine();
+ int minMobs = settings.PetMinMonsters;
+ ImGui.SetNextItemWidth(90);
+ if (ImGui.InputInt("Min monsters", ref minMobs)) _ctx.Post(() => { settings.PetMinMonsters = Math.Max(1, minMobs); _ctx.SaveCombatSettings?.Invoke(); });
+ bool refill = settings.PetAutoRefill;
+ if (ImGui.Checkbox("Refill empty essences with Encapsulated Spirit", ref refill)) _ctx.Post(() => { settings.PetAutoRefill = refill; _ctx.SaveCombatSettings?.Invoke(); });
+ ImGui.TextDisabled("Tick pets to add them to the summon list; with Sort = Priority the arrows set the order.");
+ break;
+ }
+ case IltPetKind.Healing:
+ ImGui.TextDisabled("Tick one heal pet (none ticked = first Healing Buddy / Dule box). Settings are below.");
+ break;
+ case IltPetKind.Cosmetic:
+ {
+ bool keep = S.KeepCosmeticOut;
+ if (ImGui.Checkbox("Keep cosmetic pet out", ref keep)) S.KeepCosmeticOut = keep;
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("Peace mode only. Dismissed automatically when the combat summoner needs the pet slot.");
+ ImGui.SameLine();
+ int resp = S.CosmeticRespawnSeconds;
+ ImGui.SetNextItemWidth(90);
+ if (ImGui.InputInt("Respawn (s)", ref resp)) S.CosmeticRespawnSeconds = Math.Clamp(resp, 5, 600);
+ ImGui.TextDisabled("Tick one cosmetic pet. Status: " + _cosmeticStatus);
+ break;
+ }
+ }
+ }
+
+ /// Sorted rows of the current type, cached until the snapshot / type / sort changes.
+ private IltPetStats[] CurrentView()
+ {
+ var src = _pets;
+ int kind = Math.Clamp(S.RosterKind, 0, 2);
+ int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
+ if (!ReferenceEquals(src, _viewSource) || kind != _viewKind || sort != _viewSort)
+ {
+ _view = IltPetStatsReader.Sort(src.Where(p => (int)p.Kind == kind), (IltPetSort)sort);
+ _viewSource = src;
+ _viewKind = kind;
+ _viewSort = sort;
+ }
+ return _view;
+ }
+
+ /// One table row per pet: tick · three stat lines (highlight / right-click menu) · priority arrows.
+ private void RenderRosterTable()
+ {
+ var rows = CurrentView();
+ var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
+ bool showArrows = kind == IltPetKind.Combat && S.RosterSort == (int)IltPetSort.Priority;
+
+ if (rows.Length == 0)
+ {
+ ImGui.TextDisabled(kind == IltPetKind.Cosmetic
+ ? "No cosmetic pets yet — select an essence in your pack and press Add sel., or right-click a pet in another type."
+ : $"No {KindNames[(int)kind].ToLowerInvariant()} pet essences carried.");
+ return;
+ }
+
+ float lineH = ImGui.GetTextLineHeightWithSpacing();
+ float tableH = Math.Min(320f, rows.Length * (lineH * 3 + 6) + 8);
+ if (!ImGui.BeginTable("##iltpets", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.ScrollY, new Vector2(0, tableH)))
+ return;
+ ImGui.TableSetupColumn("##sel", ImGuiTableColumnFlags.WidthFixed, 26);
+ ImGui.TableSetupColumn("##pet");
+ ImGui.TableSetupColumn("##ord", ImGuiTableColumnFlags.WidthFixed, showArrows ? 52 : 1);
+
+ foreach (var r in rows)
+ {
+ ImGui.TableNextRow();
+ ImGui.TableNextColumn();
+ bool on = r.Selected;
+ if (ImGui.Checkbox($"##psel{r.Id}", ref on))
+ {
+ var row = r;
+ _ctx.Post(() => SetSelected(row.Id, row.Name, row.Kind, on));
+ }
+
+ ImGui.TableNextColumn();
+ Vector2 start = ImGui.GetCursorPos();
+ if (ImGui.Selectable($"##prow{r.Id}", _highlightId == r.Id, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, lineH * 3 - ImGui.GetStyle().ItemSpacing.Y)))
+ _highlightId = _highlightId == r.Id ? 0 : r.Id;
+ RenderRowContextMenu(r);
+ ImGui.SetCursorPos(start);
+ ImGui.TextColored(DamageColor(r.DamageType), r.Line1);
+ ImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2);
+ if (r.UsesMax > 0 && r.UsesCur == 0) ImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3);
+ else ImGui.TextDisabled(" " + r.Line3);
+
+ ImGui.TableNextColumn();
+ if (showArrows && r.Selected)
+ {
+ int id = r.Id;
+ if (ImGui.ArrowButton($"##pup{r.Id}", ImGuiDir.Up)) _ctx.Post(() => MovePriority(id, -1));
+ ImGui.SameLine();
+ if (ImGui.ArrowButton($"##pdn{r.Id}", ImGuiDir.Down)) _ctx.Post(() => MovePriority(id, +1));
+ }
+ }
+ ImGui.EndTable();
+ }
+
+ /// Right-click menu on a roster row: summon / move to another type / clear override.
+ private void RenderRowContextMenu(IltPetStats r)
+ {
+ if (!ImGui.BeginPopupContextItem($"##pctx{r.Id}")) return;
+ var row = r;
+ if (ImGui.MenuItem("Summon")) _ctx.Post(() => SummonPet(row.Id, row.Kind));
+ ImGui.Separator();
+ for (int i = 0; i < KindNames.Length; i++)
+ {
+ if (i == (int)r.Kind) continue;
+ var to = (IltPetKind)i;
+ if (ImGui.MenuItem("Move to " + KindNames[i])) _ctx.Post(() => SetKind(row.Id, row.Name, to));
+ }
+ if (r.KindAssigned && ImGui.MenuItem("Clear type override"))
+ _ctx.Post(() => SetKind(row.Id, row.Name, null));
+ ImGui.EndPopup();
+ }
+
+ /// Line-1 colour by the pet's damage type (white when unknown / not appraised).
+ private static Vector4 DamageColor(string damageType) => damageType switch
+ {
+ "Fire" => new Vector4(1.00f, 0.55f, 0.30f, 1f),
+ "Cold" => new Vector4(0.55f, 0.80f, 1.00f, 1f),
+ "Acid" => new Vector4(0.55f, 0.95f, 0.45f, 1f),
+ "Lightning" => new Vector4(0.85f, 0.70f, 1.00f, 1f),
+ "Nether" => new Vector4(0.75f, 0.50f, 0.90f, 1f),
+ _ => new Vector4(0.95f, 0.95f, 0.95f, 1f),
+ };
+
+ private void RenderCharms()
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms");
+ bool refillOff = _ctx.Options.IsOff(IltFeature.PetRefill);
+ ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried"));
+ ImGui.BeginDisabled(refillOff);
+ bool usePath = S.UsePyrealRefillPath;
+ if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath))
+ S.UsePyrealRefillPath = usePath;
+ ImGui.EndDisabled();
+ ImGui.TextUnformatted("Universal Summoning Mastery: "
+ + (_ctx.Options.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried"));
+ if (!_ctx.Options.IsOff(IltFeature.RequireComps) && !_uiHasCasting)
+ ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "No spell components or Infinite Casting Stone carried.");
+ }
+
+ private void RenderHealing()
+ {
+ if (!ImGui.CollapsingHeader("Healing pet settings")) return;
+ bool en = S.HealingEnabled;
+ if (ImGui.Checkbox("Summon heal pet when health is low", ref en)) S.HealingEnabled = en;
+ string healPet = S.HealPetName;
+ ImGui.TextDisabled("Heal pet: " + (string.IsNullOrWhiteSpace(healPet) ? "auto (Healing Buddy / Dule box)" : healPet)
+ + " — tick one under Type = Healing.");
+ int thr = S.HealthThresholdPercent;
+ ImGui.SetNextItemWidth(160);
+ if (ImGui.SliderInt("Health % trigger", ref thr, 10, 99)) S.HealthThresholdPercent = thr;
+ int minHp = S.MinHealthPoints;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Don't summon below HP", ref minHp, 10)) S.MinHealthPoints = Math.Max(0, minHp);
+ bool desp = S.AutoDespawnAfterHeal;
+ if (ImGui.Checkbox("Dismiss after the heal", ref desp)) S.AutoDespawnAfterHeal = desp;
+ int resp = S.RespawnDelaySeconds;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Respawn delay (s)", ref resp)) S.RespawnDelaySeconds = Math.Max(1, resp);
+ int to = S.PetTimeoutSeconds;
+ ImGui.SetNextItemWidth(100);
+ if (ImGui.InputInt("Heal timeout (s)", ref to)) S.PetTimeoutSeconds = Math.Max(5, to);
+ ImGui.TextDisabled("Status: " + _healStatus);
+ }
+
+ private void RenderRosters()
+ {
+ RenderRoster("Pet log", false, IltFeature.Pets, S.PetLog);
+ RenderRoster("Shiny log", true, IltFeature.Shinies, S.ShinyLog);
+ }
+
+ private void RenderRoster(string label, bool shinies, string key, List list)
+ {
+ if (_ctx.Options.IsOff(key)) return;
+ var snap = list.ToArray();
+ if (ImGui.TreeNode($"{label} ({snap.Length})##{key}"))
+ {
+ if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies));
+ foreach (string s in snap) ImGui.BulletText(s);
+ ImGui.TreePop();
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltProgression.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltProgression.cs
new file mode 100644
index 0000000..29af6f9
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltProgression.cs
@@ -0,0 +1,459 @@
+// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's
+// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote.
+//
+// Augs : "/aug" levels + the SERVER cost formula (per level n: base + n*(base*LP/100),
+// times a soft-cap multiplier 1/4/8/16/24 at thresholds S1..S4), coins per level.
+// Enl : tier material/luminance table, requirement checklist, "/enl" on confirm. The
+// server pops its own Yes/No dialog — the host cannot (and must not) click it.
+// Optional auto-enlighten is disarmed every session and needs a hard confirm.
+// XP : the Skills panel plans attribute/vital raises from the client's exact XP tables;
+// this module only spends unassigned XP ("/attr") before an auto-enlighten.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltProgression : IIltFeature
+{
+ // ── Augmentation table (server values) ──────────────────────────────────
+
+ private sealed record AugDef(string Key, string Label, long Base, int LinearPercent, int CoinsPerLevel,
+ int S1, int S2, int S3, int S4, int Cap);
+
+ private static readonly AugDef[] Augs =
+ {
+ new("creature", "Creature", 750_000, 130, 3, 2750, 4000, 4750, 5250, 6000),
+ new("item", "Item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500, 4000),
+ new("life", "Life", 975_000, 195, 12, 1000, 2000, 3000, 3750, 4000),
+ new("war", "War", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
+ new("void", "Void", 800_000, 160, 5, 1750, 2500, 3000, 3750, 4000),
+ new("duration", "Duration", 400_000, 120, 5, 1000, 2000, 2500, 3000, 4000),
+ new("melee", "Melee", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
+ new("missile", "Missile", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
+ new("specialization", "Specialization", 3_000_000, 200, 50, 1750, 2000, 2250, 2750, 266),
+ new("summon", "Summon", 500_000, 125, 36, 1250, 2000, 3000, 3500, 4000),
+ };
+
+ /// Luminance for raising one aug from to .
+ private static decimal AugLumCost(AugDef a, int cur, int tgt)
+ {
+ decimal total = 0;
+ decimal step = a.Base * (decimal)a.LinearPercent / 100m;
+ for (int n = Math.Max(0, cur); n < tgt; n++)
+ {
+ int mult = n >= a.S4 ? 24 : n >= a.S3 ? 16 : n >= a.S2 ? 8 : n >= a.S1 ? 4 : 1;
+ total += (a.Base + n * step) * mult;
+ }
+ return total;
+ }
+
+ // ── Enlightenment ───────────────────────────────────────────────────────
+
+ private const int BaseLevelForEnl = 275;
+ private const long AutoEnlCooldownMs = 60_000;
+ private const uint SpellVitae = 666;
+
+ /// Materials for reaching enlightenment level (one step).
+ public static (string Item, uint Wcid, int Count, decimal Lum) EnlStepCost(int t)
+ {
+ if (t <= 5) return ("none", 0, 0, 0);
+ int count = t - 5;
+ if (t <= 50) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, 0);
+ if (t <= 150) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, t * 100_000_000m);
+ if (t <= 300) return ("Enlightenment Medallions", IltInventory.WcidEnlMedallion, count, t * 1_000_000_000m);
+ decimal mult = 1m + 0.5m * ((t - 300 - 1) / 50);
+ decimal lum = Math.Ceiling(t * 2_000_000_000m * mult);
+ return t <= 325 ? ("Enlightenment Sigils", IltInventory.WcidEnlSigil, count, lum)
+ : ("Enlightenment Crests", IltInventory.WcidEnlCrest, count, lum);
+ }
+
+ // ── XP ──────────────────────────────────────────────────────────────────
+
+ /// /attr abbreviation, display name, attribute stype (0 = vital), vital stype.
+ private static readonly (string Abbr, string Name, uint Attr, uint Vital)[] Stats =
+ {
+ ("str", "Strength", 1, 0), ("end", "Endurance", 2, 0), ("coo", "Coordination", 4, 0),
+ ("qui", "Quickness", 3, 0), ("foc", "Focus", 5, 0), ("sel", "Self", 6, 0),
+ ("hea", "Health", 0, 1), ("sta", "Stamina", 0, 3), ("man", "Mana", 0, 5),
+ };
+
+ private readonly IltHubContext _ctx;
+ private readonly Dictionary _augLevels = new(StringComparer.OrdinalIgnoreCase);
+ private volatile string _augStatus = "not loaded";
+
+ // Cached player facts for the render thread (refreshed in Tick).
+ private volatile int _enl, _level, _freeSlots;
+ private long _unassignedXp;
+ private volatile bool _peace, _hasVitae;
+ private readonly long[] _enlHave = new long[4]; // tokens, medallions, sigils, crests
+ private long _lastFactsAt;
+ private readonly uint[] _enchIds = new uint[256];
+ private readonly double[] _enchExp = new double[256];
+
+ // Auto-enlighten (armed only after the in-session confirm).
+ private bool _autoArmed;
+ private long _lastAutoCheck;
+ private long _lastEnlSentAt = -AutoEnlCooldownMs;
+ private volatile string _enlStatus = string.Empty;
+
+ // XP spend-before-enlighten loop.
+ private bool _spending;
+ private int _spendIdx, _spendSent, _spendNoProgress;
+ private long _spendLastAt, _spendLastXp;
+ private Action? _afterSpend;
+
+ public IltProgression(IltHubContext ctx) => _ctx = ctx;
+
+ private IltCharacterState C => _ctx.State.Character;
+
+ // ── Commands ────────────────────────────────────────────────────────────
+
+ public void RequestAugs()
+ {
+ RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()");
+ if (_ctx.Options.IsOff(IltFeature.Aug) || _ctx.Capture.IsPending("/aug")) return;
+ _augStatus = "loading...";
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = "/aug",
+ IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
+ IdleEndMs = 2000,
+ FirstLineTimeoutMs = 15000,
+ Eat = true,
+ OnComplete = r =>
+ {
+ if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; }
+ ApplyAugLines(r.Lines);
+ },
+ });
+ }
+
+ /// Parses "/aug" output (also fed from the login probe).
+ public void ApplyAugLines(List lines)
+ {
+ RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
+ int n = 0;
+ foreach (string l in lines)
+ {
+ var m = IltParse.AugLine.Match(l.Trim());
+ if (!m.Success) continue;
+ string key = m.Groups[1].Value.ToLowerInvariant();
+ if (key == "specialize") key = "specialization";
+ lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
+ n++;
+ }
+ _augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
+ }
+
+ /// Sends "/enl" (server shows the confirmation dialog). Pump thread.
+ public void SendEnlighten(string why)
+ {
+ RynthLog.Trace(LogCat.IltProgression, $"SendEnlighten(why='{why}')");
+ if (!_ctx.Host.HasInvokeChatParser) return;
+ _lastEnlSentAt = IltHubContext.NowMs;
+ _ctx.Host.InvokeChatParser("/enl");
+ _enlStatus = $"/enl sent ({why}) - click Yes in the AC dialog to confirm.";
+ _ctx.Chat("[ILT Hub] " + _enlStatus);
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs)
+ {
+ if (nowMs - _lastFactsAt >= 2000)
+ {
+ _lastFactsAt = nowMs;
+ RefreshFacts();
+ }
+ TickSpend(nowMs);
+
+ if (_autoArmed && C.AutoEnlightenEnabled && !_spending
+ && nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L)
+ {
+ _lastAutoCheck = nowMs;
+ TryAutoEnlighten(nowMs);
+ }
+ }
+
+ public bool OnChat(string text)
+ {
+ if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase)
+ || text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase))
+ {
+ _enlStatus = "Enlightened! " + DateTime.Now.ToString("t");
+ _lastFactsAt = 0;
+ }
+ return false;
+ }
+
+ public void OnLogout()
+ {
+ _autoArmed = false;
+ _spending = false;
+ lock (_augLevels) _augLevels.Clear();
+ }
+
+ // ── Facts / auto ────────────────────────────────────────────────────────
+
+ private void RefreshFacts()
+ {
+ var inv = _ctx.Inventory;
+ _enl = inv.PlayerInt(IltInventory.IntEnlightenment);
+ _level = inv.PlayerInt(IltInventory.IntLevel);
+ _unassignedXp = inv.PlayerQuad(IltInventory.QuadAvailableXp);
+ _peace = inv.InPeaceMode;
+ _freeSlots = inv.FreeMainPackSlots();
+ _enlHave[0] = inv.CountByWcid(IltInventory.WcidEnlToken);
+ _enlHave[1] = inv.CountByWcid(IltInventory.WcidEnlMedallion);
+ _enlHave[2] = inv.CountByWcid(IltInventory.WcidEnlSigil);
+ _enlHave[3] = inv.CountByWcid(IltInventory.WcidEnlCrest);
+
+ _hasVitae = false;
+ if (_ctx.Host.HasReadPlayerEnchantments)
+ {
+ int n = _ctx.Host.ReadPlayerEnchantments(_enchIds, _enchExp, _enchIds.Length);
+ for (int i = 0; i < Math.Min(n, _enchIds.Length); i++)
+ if (_enchIds[i] == SpellVitae) { _hasVitae = true; break; }
+ }
+ }
+
+ private long HaveFor(uint wcid) => wcid switch
+ {
+ IltInventory.WcidEnlToken => _enlHave[0],
+ IltInventory.WcidEnlMedallion => _enlHave[1],
+ IltInventory.WcidEnlSigil => _enlHave[2],
+ IltInventory.WcidEnlCrest => _enlHave[3],
+ _ => 0,
+ };
+
+ /// Checks the client-visible requirements for the next enlightenment. Empty = ready.
+ private List NextEnlBlockers()
+ {
+ var list = new List();
+ int next = _enl + 1;
+ if (_level < BaseLevelForEnl + _enl) list.Add($"Need character level {BaseLevelForEnl + _enl} (have {_level}).");
+ if (!_peace) list.Add("Must be in peace mode.");
+ if (_hasVitae) list.Add("Must not have vitae.");
+ var cost = EnlStepCost(next);
+ if (cost.Count > 0 && HaveFor(cost.Wcid) < cost.Count) list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}).");
+ if (cost.Lum > 0 && _ctx.State.Bank.Luminance < cost.Lum) list.Add($"Need {IltParse.Compact((double)cost.Lum)} banked luminance.");
+ return list;
+ }
+
+ private void TryAutoEnlighten(long now)
+ {
+ if (_ctx.Options.IsOff(IltFeature.Enl)) return;
+ if (now - _lastEnlSentAt < AutoEnlCooldownMs) return;
+ if (NextEnlBlockers().Count > 0) return;
+ if (C.AutoEnlightenSpendXpFirst && _unassignedXp > 0)
+ StartSpend(() => SendEnlighten("auto"));
+ else
+ SendEnlighten("auto");
+ }
+
+ // ── XP spend loop: cycles /attr 1 until unassigned XP stops dropping ──
+
+ private void StartSpend(Action then)
+ {
+ _spending = true;
+ _spendIdx = 0;
+ _spendSent = 0;
+ _spendNoProgress = 0;
+ _spendLastAt = 0;
+ _spendLastXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
+ _afterSpend = then;
+ _enlStatus = "Spending unassigned XP before enlightening...";
+ }
+
+ private void TickSpend(long now)
+ {
+ if (!_spending || now - _spendLastAt < 300) return;
+ _spendLastAt = now;
+
+ long xp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
+ if (xp < _spendLastXp) _spendNoProgress = 0; else if (_spendSent > 0) _spendNoProgress++;
+ _spendLastXp = xp;
+
+ // Stop after a full stat cycle with no XP drop, when XP is gone, or at the safety cap.
+ if (xp <= 0 || _spendNoProgress >= Stats.Length || _spendSent >= 300)
+ {
+ _spending = false;
+ var next = _afterSpend;
+ _afterSpend = null;
+ next?.Invoke();
+ return;
+ }
+ if (_ctx.Inventory.IsBusy) return;
+ _ctx.Host.InvokeChatParser($"/attr {Stats[_spendIdx].Abbr} 1");
+ _spendIdx = (_spendIdx + 1) % Stats.Length;
+ _spendSent++;
+ }
+
+ // ── Engine Skills panel bridge (pump thread) ────────────────────────────
+ // The engine's Skills panel draws Augmentations and Enlightenment from this snapshot and
+ // sends edits back as "prog ..." remote commands (HandleRemote). Planner math stays here so
+ // the Hub and the Skills panel can never disagree. Numbers are preformatted for display.
+
+ /// Appends "aug":{...},"enl":{...} to . Pump thread.
+ public void AppendSnapshotJson(StringBuilder sb)
+ {
+ AppendAugJson(sb);
+ sb.Append(',');
+ AppendEnlJson(sb);
+ }
+
+ private void AppendAugJson(StringBuilder sb)
+ {
+ Dictionary levels;
+ lock (_augLevels) levels = new Dictionary(_augLevels, StringComparer.OrdinalIgnoreCase);
+
+ sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug)));
+ Str(sb, "status", _augStatus);
+ sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":[");
+ decimal totalLum = 0;
+ long totalCoins = 0;
+ for (int i = 0; i < Augs.Length; i++)
+ {
+ var a = Augs[i];
+ int cur = levels.TryGetValue(a.Key, out int c) ? c : 0;
+ int ceiling = Math.Max(cur, a.Cap);
+ int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling);
+ decimal lum = AugLumCost(a, cur, tgt);
+ long coins = (long)(tgt - cur) * a.CoinsPerLevel;
+ totalLum += lum;
+ totalCoins += coins;
+ if (i > 0) sb.Append(',');
+ sb.Append('{');
+ Str(sb, "key", a.Key, first: true);
+ Str(sb, "label", a.Label);
+ sb.Append(",\"cur\":").Append(cur).Append(",\"tgt\":").Append(tgt).Append(",\"cap\":").Append(ceiling);
+ Str(sb, "lum", lum > 0 ? IltParse.Compact((double)lum) : "-");
+ sb.Append(",\"coins\":").Append(coins).Append('}');
+ }
+ sb.Append(']');
+ Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins");
+ long bankCoins = _ctx.State.Bank.EnlightenedCoins;
+ long lumPerCoin = C.LumPerEnlightenedCoin;
+ string shortText = totalCoins > bankCoins
+ ? $"Coins short: {IltParse.N0(totalCoins - bankCoins)}"
+ + (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)(totalCoins - bankCoins) * lumPerCoin)} luminance to buy)" : "")
+ : string.Empty;
+ Str(sb, "short", shortText);
+ Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}");
+ sb.Append('}');
+ }
+
+ private void AppendEnlJson(StringBuilder sb)
+ {
+ int enl = _enl;
+ sb.Append("\"enl\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Enl)));
+ Str(sb, "header", $"Enlightenment {enl} Level {_level} Unassigned XP {IltParse.Compact(_unassignedXp)}");
+ var next = EnlStepCost(enl + 1);
+ Str(sb, "next", $"Next ({enl + 1}): " + (next.Count > 0
+ ? $"{next.Count} {next.Item} (have {HaveFor(next.Wcid)})" + (next.Lum > 0 ? $" + {IltParse.Compact((double)next.Lum)} lum" : "")
+ : "no materials"));
+
+ int target = C.EnlTargetLevel <= enl ? enl + 5 : C.EnlTargetLevel;
+ sb.Append(",\"enl\":").Append(enl).Append(",\"target\":").Append(target).Append(",\"plan\":[");
+ var totals = new Dictionary();
+ decimal lumTotal = 0;
+ for (int t = enl + 1; t <= Math.Max(enl + 1, target) && t <= enl + 500; t++)
+ {
+ var s = EnlStepCost(t);
+ if (s.Count > 0) totals[s.Item] = (totals.TryGetValue(s.Item, out long v) ? v : 0) + s.Count;
+ lumTotal += s.Lum;
+ }
+ bool firstLine = true;
+ foreach (var kv in totals) { StrItem(sb, $"{IltParse.N0(kv.Value)} {kv.Key}", ref firstLine); }
+ if (lumTotal > 0)
+ StrItem(sb, $"{IltParse.Compact((double)lumTotal)} luminance (banked {IltParse.Compact(_ctx.State.Bank.Luminance)})", ref firstLine);
+ sb.Append(']');
+
+ int coinsPerToken = C.EnlightenedCoinsPerToken;
+ sb.Append(",\"coinsPerToken\":").Append(coinsPerToken);
+ string tokensShort = string.Empty;
+ if (totals.TryGetValue("Enlightenment Tokens", out long tokNeed) && coinsPerToken > 0)
+ {
+ long shortTok = Math.Max(0, tokNeed - _enlHave[0]);
+ if (shortTok > 0) tokensShort = $"Tokens short: {shortTok} (~{IltParse.N0(shortTok * coinsPerToken)} coins)";
+ }
+ Str(sb, "tokensShort", tokensShort);
+
+ var blockers = NextEnlBlockers();
+ sb.Append(",\"blockers\":[");
+ bool firstBlocker = true;
+ foreach (string b in blockers) StrItem(sb, b, ref firstBlocker);
+ sb.Append(']');
+ Str(sb, "serverChecks", $"Server also checks: not in a dungeon, free pack slots ({(_freeSlots >= 0 ? _freeSlots.ToString() : "?")} free), "
+ + "all luminance augs (past 10), society master (past 30).");
+ sb.Append(",\"auto\":").Append(Bool(C.AutoEnlightenEnabled))
+ .Append(",\"armed\":").Append(Bool(_autoArmed))
+ .Append(",\"spendFirst\":").Append(Bool(C.AutoEnlightenSpendXpFirst))
+ .Append(",\"checkEvery\":").Append(C.AutoEnlightenCheckSeconds);
+ Str(sb, "status", _enlStatus);
+ sb.Append('}');
+ }
+
+ private static string Bool(bool b) => b ? "true" : "false";
+
+ private static void Str(StringBuilder sb, string name, string value, bool first = false)
+ {
+ if (!first) sb.Append(',');
+ sb.Append('"').Append(name).Append("\":\"").Append(RynthAiPlugin.JsonEscape(value ?? string.Empty)).Append('"');
+ }
+
+ private static void StrItem(StringBuilder sb, string value, ref bool first)
+ {
+ if (!first) sb.Append(',');
+ first = false;
+ sb.Append('"').Append(RynthAiPlugin.JsonEscape(value)).Append('"');
+ }
+
+ ///
+ /// "prog" remote command from the engine Skills panel. Pump thread. The panel asks its own
+ /// confirmation before "enlighten" and "autoenl on|arm", so none is asked here.
+ ///
+ public void HandleRemote(string[] a)
+ {
+ if (a.Length == 0) return;
+ RynthLog.Trace(LogCat.IltProgression, $"HandleRemote({string.Join(" ", a)})");
+ string arg1 = a.Length > 1 ? a[1] : string.Empty;
+ int.TryParse(a.Length > 2 ? a[2] : arg1, out int n);
+ switch (a[0].ToLowerInvariant())
+ {
+ case "augload": RequestAugs(); break;
+ case "augtarget" when a.Length > 2:
+ foreach (var def in Augs)
+ {
+ if (!def.Key.Equals(arg1, StringComparison.OrdinalIgnoreCase)) continue;
+ int cur;
+ lock (_augLevels) cur = _augLevels.TryGetValue(def.Key, out int c) ? c : 0;
+ C.AugTargets[def.Key] = Math.Clamp(n, 0, Math.Max(cur, def.Cap));
+ break;
+ }
+ break;
+ case "lumpercoin":
+ if (IltParse.TryParseAmount(arg1, out long lpc)) C.LumPerEnlightenedCoin = Math.Max(0, lpc);
+ break;
+ case "enltarget": C.EnlTargetLevel = Math.Max(_enl + 1, n); break;
+ case "coinspertoken": C.EnlightenedCoinsPerToken = Math.Max(0, n); break;
+ case "enlighten": SendEnlighten("manual, Skills panel"); break;
+ case "autoenl":
+ switch (arg1.ToLowerInvariant())
+ {
+ case "on":
+ C.AutoEnlightenEnabled = true;
+ _autoArmed = true;
+ _ctx.Chat("[ILT Hub] Auto-enlighten armed for this session.");
+ break;
+ case "arm": if (C.AutoEnlightenEnabled) _autoArmed = true; break;
+ default: C.AutoEnlightenEnabled = false; _autoArmed = false; break;
+ }
+ break;
+ case "spendfirst": C.AutoEnlightenSpendXpFirst = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); break;
+ case "checkevery": C.AutoEnlightenCheckSeconds = Math.Max(10, n); break;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltQuests.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltQuests.cs
new file mode 100644
index 0000000..1419f12
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltQuests.cs
@@ -0,0 +1,474 @@
+// IltQuests.cs — Quest Tracker UI and Quest Bonus (/qb) list for the ILT Hub Character tab.
+//
+// Quest Tracker reuses the meta QuestTracker (the same /myquests cache the meta
+// expression engine reads) — it never runs a second parser. Friendly names come from:
+// 1. an optional user-supplied quests.xml (\RynthAi\quests.xml),
+// 2. the description the server prints in /myquests,
+// 3. the raw flag key.
+// UB's bundled quests.xml is NOT embedded (no license on UB content).
+//
+// QB: "/qb list" prints a completed and an incomplete section; both are tracked
+// separately (UB merged them). Server throttles /qb to once per minute.
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Numerics;
+using System.Text.RegularExpressions;
+using System.Xml;
+using ImGuiNET;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Meta;
+using RynthCore.Install;
+
+namespace RynthCore.Plugin.RynthAi.IltHub;
+
+internal sealed class IltQuests : IIltFeature
+{
+ /// Optional user quest-name file (UB-style or simple key/name XML).
+ public static readonly string QuestsXmlPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"quests.xml");
+
+ private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))",
+ RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ private static readonly Regex QbFlagLine = new(@"^[a-zA-Z0-9_\-!@\(\)?]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
+
+ private const long QuestRefreshCooldownMs = 60_000;
+ private const long QbCooldownMs = 60_000;
+
+ private readonly IltHubContext _ctx;
+ private readonly Func _tracker;
+ private Dictionary _friendlyNames = new(StringComparer.OrdinalIgnoreCase);
+ private long _lastQuestRefreshAt = -QuestRefreshCooldownMs;
+ private long _lastQbAt = -QbCooldownMs;
+
+ // QB results (replaced wholesale; read by the render thread).
+ private volatile string[] _qbCompleted = Array.Empty();
+ private volatile string[] _qbIncomplete = Array.Empty();
+ private volatile string _qbStatus = "not loaded";
+ private long _qbCount = -1;
+ private volatile int _qbGeneration; // bumped per successful "/qb list"; 0 = never loaded this session
+ private bool _questsRescueChecked; // popped-out window's off-screen check done for the current show
+
+ // Render-thread UI state.
+ private int _questView; // 0 timed, 1 kill tasks, 2 once, 3 all
+
+ public IltQuests(IltHubContext ctx, Func tracker)
+ {
+ _ctx = ctx;
+ _tracker = tracker;
+ LoadFriendlyNames();
+ }
+
+ public enum QuestKind { Timed, KillTask, Once }
+
+ public static QuestKind Classify(QuestRecord r)
+ {
+ if (KillTaskRegex.IsMatch(r.Key) && r.MaxSolves >= 0) return QuestKind.KillTask;
+ if (r.MaxSolves == 1 && r.Solves <= 1) return QuestKind.Once;
+ return QuestKind.Timed;
+ }
+
+ public string FriendlyName(QuestRecord r)
+ {
+ if (_friendlyNames.TryGetValue(r.Key, out string? n) && !string.IsNullOrWhiteSpace(n)) return n;
+ if (!string.IsNullOrWhiteSpace(r.Description)) return r.Description;
+ return r.Key;
+ }
+
+ // ── quests.xml (optional) ───────────────────────────────────────────────
+
+ /// Reads any element carrying a key/flag attribute plus a name/description.
+ public void LoadFriendlyNames()
+ {
+ var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ try
+ {
+ if (File.Exists(QuestsXmlPath))
+ {
+ using var reader = XmlReader.Create(QuestsXmlPath, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true });
+ while (reader.Read())
+ {
+ if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes) continue;
+ string? key = null, name = null;
+ while (reader.MoveToNextAttribute())
+ {
+ string a = reader.Name.ToLowerInvariant();
+ if (a is "key" or "flag" or "questflag" or "id") key = reader.Value;
+ else if (a is "name" or "description" or "title" or "friendlyname") name ??= reader.Value;
+ }
+ reader.MoveToElement();
+ if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(name))
+ map[key.Trim().ToLowerInvariant()] = name.Trim();
+ }
+ }
+ }
+ catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "quests.xml load"); }
+ _friendlyNames = map;
+ }
+
+ // ── Commands ────────────────────────────────────────────────────────────
+
+ /// Quiet /myquests refresh with a 60 s client-side cooldown (server throttle).
+ public string RefreshQuests()
+ {
+ RynthLog.Trace(LogCat.IltQuests, $"RefreshQuests()");
+ var t = _tracker();
+ if (t == null) return "Quest tracker not ready.";
+ if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled) return "/myquests is disabled on this server.";
+ long now = IltHubContext.NowMs;
+ if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs)
+ return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute).";
+ _lastQuestRefreshAt = now;
+ t.Refresh(quiet: true);
+ return "Refreshing quests...";
+ }
+
+ /// "/ra quests check <regex>" — lists up to 5 matching flags in chat.
+ public void CheckCommand(string pattern)
+ {
+ var t = _tracker();
+ if (t == null) { _ctx.Chat("[ILT Hub] Quest tracker not ready."); return; }
+ Regex rx;
+ try { rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(200)); }
+ catch (ArgumentException ex) { _ctx.Chat("[ILT Hub] Bad pattern: " + ex.Message); return; }
+
+ var hits = t.Snapshot().Where(r => rx.IsMatch(r.Key) || rx.IsMatch(FriendlyName(r))).OrderBy(r => r.Key).ToList();
+ if (hits.Count == 0) { _ctx.Chat($"[ILT Hub] No quest flags match '{pattern}' ({t.Count} cached)."); return; }
+ foreach (var r in hits.Take(5))
+ _ctx.Chat($"[ILT Hub] {FriendlyName(r)} [{r.Key}] solves {r.Solves}{(r.MaxSolves > 0 ? "/" + r.MaxSolves : "")} - {IltParse.Duration(r.TimeUntilReady())}");
+ if (hits.Count > 5) _ctx.Chat($"[ILT Hub] ...and {hits.Count - 5} more.");
+ }
+
+ /// Captures "/qb list" (quiet).
+ public string RefreshQb()
+ {
+ RynthLog.Trace(LogCat.IltQuests, $"RefreshQb()");
+ if (_ctx.Options.IsOff(IltFeature.Qb)) return "/qb is disabled on this server.";
+ long now = IltHubContext.NowMs;
+ if (now - _lastQbAt < QbCooldownMs)
+ return $"Wait {(QbCooldownMs - (now - _lastQbAt)) / 1000}s (server allows one /qb per minute).";
+ if (_ctx.Capture.IsPending("/qb list")) return "Already loading...";
+ _lastQbAt = now;
+ _qbStatus = "loading...";
+
+ _ctx.Capture.Enqueue(new IltChatRequest
+ {
+ Command = "/qb list",
+ IsResponseLine = IsQbLine,
+ IsTerminator = t => t.Contains("Quest bonus list is empty", StringComparison.OrdinalIgnoreCase)
+ || t.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("[QB] This command may only be run once every", StringComparison.OrdinalIgnoreCase),
+ IdleEndMs = 5000,
+ FirstLineTimeoutMs = 30000,
+ Eat = true,
+ OnComplete = OnQbResult,
+ });
+ return "Loading quest bonus list...";
+ }
+
+ private static bool IsQbLine(string t)
+ {
+ if (t.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)
+ || t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
+ return true;
+ if (!QbFlagLine.IsMatch(t)) return false;
+ if (t.StartsWith("You ", StringComparison.Ordinal) || t.StartsWith("The ", StringComparison.Ordinal)) return false;
+ return !(t.Contains("You have", StringComparison.OrdinalIgnoreCase) || t.Contains("command", StringComparison.OrdinalIgnoreCase)
+ || t.Contains("enabled", StringComparison.OrdinalIgnoreCase) || t.Contains("list", StringComparison.OrdinalIgnoreCase));
+ }
+
+ private void OnQbResult(IltChatResult r)
+ {
+ if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb not available"; return; }
+ if (r.TerminatorLine != null)
+ {
+ if (r.TerminatorLine.Contains("not currently enabled", StringComparison.OrdinalIgnoreCase))
+ { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb is disabled on this server"; return; }
+ if (r.TerminatorLine.Contains("only be run once", StringComparison.OrdinalIgnoreCase))
+ { _qbStatus = "rate limited by the server"; return; }
+ }
+ if (r.TimedOut) { _qbStatus = "no reply from server"; return; }
+ _ctx.Options.Set(IltFeature.Qb, IltTri.On);
+
+ var done = new List();
+ var todo = new List();
+ List? current = null;
+ foreach (string line in r.Lines)
+ {
+ if (line.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = done; continue; }
+ if (line.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = todo; continue; }
+ if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
+ {
+ int colon = line.IndexOf(':');
+ if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
+ continue;
+ }
+ if (line.Contains("is empty", StringComparison.OrdinalIgnoreCase)) continue;
+ (current ?? done).Add(line.Trim());
+ }
+ done.Sort(StringComparer.OrdinalIgnoreCase);
+ todo.Sort(StringComparer.OrdinalIgnoreCase);
+ _qbCompleted = done.ToArray();
+ _qbIncomplete = todo.ToArray();
+ _qbStatus = $"{done.Count} completed, {todo.Count} incomplete";
+ _qbGeneration++;
+ }
+
+ /// Increments each time a "/qb list" reply is parsed (0 = not loaded this session).
+ public int QbGeneration => _qbGeneration;
+
+ /// True when the last "/qb list" (completed or incomplete) contains the flag.
+ public bool QbHasFlag(string flag)
+ {
+ if (string.IsNullOrWhiteSpace(flag)) return false;
+ foreach (string f in _qbCompleted)
+ if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
+ foreach (string f in _qbIncomplete)
+ if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
+ return false;
+ }
+
+ /// Login probe tap: "/qb" (no args) prints the count line.
+ public void ApplyQbProbe(List lines)
+ {
+ RynthLog.Trace(LogCat.IltQuests, $"ApplyQbProbe(lines={lines.Count})");
+ foreach (string line in lines)
+ if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
+ {
+ int colon = line.IndexOf(':');
+ if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
+ }
+ }
+
+ // ── IIltFeature ─────────────────────────────────────────────────────────
+
+ public void Tick(long nowMs) { }
+ public bool OnChat(string text) => false;
+ public void OnLogout()
+ {
+ _qbCompleted = Array.Empty();
+ _qbIncomplete = Array.Empty();
+ _qbCount = -1;
+ _qbStatus = "not loaded";
+ _qbGeneration = 0;
+ }
+
+ // ── UI (render thread) ──────────────────────────────────────────────────
+
+ /// Quest tracker body, filling the "Quests" window (the table uses the remaining height).
+ public void RenderQuestTracker()
+ {
+ var t = _tracker();
+ if (t == null) { ImGui.TextDisabled("Quest tracker not ready."); return; }
+ if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled)
+ {
+ ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/myquests is disabled on this server.");
+ return;
+ }
+ var cs = _ctx.State.Character;
+
+ if (ImGui.SmallButton("Refresh##quests")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQuests()));
+ ImGui.SameLine();
+ if (ImGui.SmallButton("Reload quests.xml")) _ctx.Post(LoadFriendlyNames);
+ ImGui.SameLine();
+ ImGui.TextDisabled(t.IsRefreshing ? "refreshing..." : t.LastStatus
+ + (t.LastRefreshUtc == DateTime.MinValue ? "" : " @ " + t.LastRefreshUtc.ToLocalTime().ToString("t")));
+
+ string filter = cs.QuestFilter;
+ ImGui.SetNextItemWidth(220);
+ if (ImGui.InputTextWithHint("##qfilter", "filter by name or key", ref filter, 64u))
+ cs.QuestFilter = filter;
+ ImGui.SameLine();
+ ImGui.RadioButton("Timed", ref _questView, 0); ImGui.SameLine();
+ ImGui.RadioButton("Kill tasks", ref _questView, 1); ImGui.SameLine();
+ ImGui.RadioButton("Once", ref _questView, 2); ImGui.SameLine();
+ ImGui.RadioButton("All", ref _questView, 3);
+
+ bool favOnly = cs.QuestFavoritesOnly;
+ if (ImGui.Checkbox("Favorites only", ref favOnly)) cs.QuestFavoritesOnly = favOnly;
+ ImGui.SameLine();
+ bool favHud = cs.ShowQuestFavoritesHud;
+ if (ImGui.Checkbox("Show floating favorites HUD", ref favHud)) cs.ShowQuestFavoritesHud = favHud;
+ ImGui.SameLine();
+ ImGui.TextDisabled("(click * to star a quest)");
+
+ var favorites = FavoriteSet();
+ var rows = t.Snapshot()
+ .Where(r => favOnly ? favorites.Contains(r.Key) : _questView == 3 || (int)Classify(r) == ViewToKind(_questView))
+ .Where(r => filter.Length == 0 || r.Key.Contains(filter, StringComparison.OrdinalIgnoreCase)
+ || FriendlyName(r).Contains(filter, StringComparison.OrdinalIgnoreCase))
+ .OrderBy(r => r.TimeUntilReady())
+ .ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase)
+ .ToArray();
+
+ if (ImGui.BeginTable("##iltquests", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
+ new Vector2(0, -1)))
+ {
+ ImGui.TableSetupScrollFreeze(0, 1);
+ ImGui.TableSetupColumn("*", ImGuiTableColumnFlags.WidthFixed, 18);
+ ImGui.TableSetupColumn("Quest");
+ ImGui.TableSetupColumn("Solves", ImGuiTableColumnFlags.WidthFixed, 70);
+ ImGui.TableSetupColumn("Ready", ImGuiTableColumnFlags.WidthFixed, 110);
+ ImGui.TableSetupColumn("Key");
+ ImGui.TableHeadersRow();
+ foreach (var r in rows)
+ {
+ ImGui.TableNextRow();
+ ImGui.TableNextColumn();
+ bool starred = favorites.Contains(r.Key);
+ ImGui.PushStyleColor(ImGuiCol.Text, starred ? FavStarOn : FavStarOff);
+ if (ImGui.Selectable($"*##fav{r.Key}", false))
+ {
+ string key = r.Key;
+ _ctx.Post(() => ToggleFavorite(key));
+ }
+ ImGui.PopStyleColor();
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip(starred ? "Remove from favorites" : "Add to favorites");
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r));
+ ImGui.TableNextColumn(); ImGui.TextUnformatted(r.MaxSolves > 0 ? $"{r.Solves}/{r.MaxSolves}" : r.Solves.ToString());
+ ImGui.TableNextColumn();
+ var left = r.TimeUntilReady();
+ if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done");
+ else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready");
+ else ImGui.TextUnformatted(IltParse.Duration(left));
+ ImGui.TableNextColumn(); ImGui.TextDisabled(r.Key);
+ }
+ ImGui.EndTable();
+ }
+ }
+
+ private static int ViewToKind(int view) => view switch { 0 => (int)QuestKind.Timed, 1 => (int)QuestKind.KillTask, _ => (int)QuestKind.Once };
+
+ // ── Favorites / floating windows ────────────────────────────────────────
+
+ private static readonly Vector4 FavStarOn = new(1.00f, 0.82f, 0.25f, 1f);
+ private static readonly Vector4 FavStarOff = new(0.45f, 0.48f, 0.52f, 1f);
+ private const string FavHudPopup = "##questfavhudopts";
+
+ /// Starred keys as a set (render thread; the list itself is only edited on the pump thread).
+ private HashSet FavoriteSet()
+ => new(_ctx.State.Character.QuestFavorites.ToArray(), StringComparer.OrdinalIgnoreCase);
+
+ ///