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); + + /// Stars / unstars a quest flag (pump thread). + private void ToggleFavorite(string key) + { + var list = _ctx.State.Character.QuestFavorites; + if (list.RemoveAll(k => k.Equals(key, StringComparison.OrdinalIgnoreCase)) == 0) + list.Add(key.ToLowerInvariant()); + } + + /// + /// The "Quests" window (opened from the Mini Remote's Options or "/ra hub open quests"; drawn + /// only while the Hub is available, matching IltHubController.SectionAvailable) and the + /// floating favorites HUD. Called every frame. + /// + public void RenderFloatingWindows() + { + var cs = _ctx.State.Character; + bool hubAvailable = _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn; + if (cs.QuestTrackerPoppedOut && hubAvailable) RenderPoppedOutTracker(cs); + else _questsRescueChecked = false; + if (cs.ShowQuestFavoritesHud) RenderFavoritesHud(cs); + } + + private void RenderPoppedOutTracker(IltCharacterState cs) + { + // Offset from the Pets window's first spot so the two don't open exactly stacked. + UiPlacement.CenterFirstUse(new Vector2(40, 40)); + ImGui.SetNextWindowSize(new Vector2(700, 520), ImGuiCond.FirstUseEver); + bool open = true; + if (ImGui.Begin("Quests##iltquestswin", ref open)) + { + UiPlacement.RescueOncePerShow(ref _questsRescueChecked); + // Quest bonus first (collapsed by default) so the tracker table can fill the rest. + if (ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb(); + RenderQuestTracker(); + } + ImGui.End(); + if (!open) cs.QuestTrackerPoppedOut = false; + } + + /// Compact always-on list of starred quests and when each is ready. + private void RenderFavoritesHud(IltCharacterState cs) + { + var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav; + if (cs.QuestFavoritesHudLocked) flags |= ImGuiWindowFlags.NoMove; + ImGui.SetNextWindowPos(new Vector2(260, 120), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowBgAlpha(0.55f); + if (!ImGui.Begin("Quest favorites##iltquestfavhud", flags)) { ImGui.End(); return; } + + ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Quest favorites"); + var t = _tracker(); + var favorites = FavoriteSet(); + if (t == null || favorites.Count == 0) + { + ImGui.TextDisabled(t == null ? "Quest tracker not ready." : "No favorites yet - star quests in the tracker."); + } + else + { + var rows = t.Snapshot().Where(r => favorites.Contains(r.Key)) + .OrderBy(r => r.TimeUntilReady()).ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase).ToArray(); + if (rows.Length == 0) ImGui.TextDisabled("Starred quests not in /myquests yet."); + if (ImGui.BeginTable("##questfavrows", 2, ImGuiTableFlags.SizingFixedFit)) + { + foreach (var r in rows) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r)); + 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.EndTable(); + } + } + + if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(FavHudPopup); + if (ImGui.BeginPopup(FavHudPopup)) + { + bool locked = cs.QuestFavoritesHudLocked; + if (ImGui.Checkbox("Lock position", ref locked)) cs.QuestFavoritesHudLocked = locked; + if (ImGui.MenuItem("Open quest tracker")) cs.QuestTrackerPoppedOut = true; + if (ImGui.MenuItem("Refresh /myquests")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQuests())); + if (ImGui.MenuItem("Hide favorites HUD")) cs.ShowQuestFavoritesHud = false; + ImGui.EndPopup(); + } + ImGui.End(); + } + + public void RenderQb() + { + if (_ctx.Options.IsOff(IltFeature.Qb)) + { + ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/qb is disabled on this server."); + return; + } + if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQb())); + ImGui.SameLine(); + long count = _qbCount; + ImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus); + + string filter = _ctx.State.Character.QbFilter; + ImGui.SetNextItemWidth(220); + if (ImGui.InputTextWithHint("##qbfilter", "filter flags", ref filter, 64u)) + _ctx.State.Character.QbFilter = filter; + + RenderQbList("Incomplete", _qbIncomplete, filter, LegacyDashboardRenderer.ColAmber); + RenderQbList("Completed", _qbCompleted, filter, LegacyDashboardRenderer.ColGreen); + } + + private static void RenderQbList(string label, string[] items, string filter, Vector4 color) + { + var shown = filter.Length == 0 ? items : items.Where(i => i.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}")) + { + if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown)); + foreach (string s in shown) ImGui.TextColored(color, s); + ImGui.TreePop(); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSections.cs new file mode 100644 index 0000000..573d587 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSections.cs @@ -0,0 +1,97 @@ +// IltSections.cs - The ILT Hub's sections, each its own window, opened from the Mini Remote's +// Options or "/ra hub open
". Open flags live in IltCharacterState (per character). +using System; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +/// Section windows. Values index per-section arrays, so new sections go at the end. +internal enum IltSection +{ + Character, + Quests, + Pet, + Banking, + Gear, + Games, + Guardian, +} + +internal static class IltSections +{ + /// Menu order (the old Hub's tab order, then the Guardian window). + public static readonly IltSection[] All = + { + IltSection.Character, IltSection.Quests, IltSection.Pet, + IltSection.Banking, IltSection.Gear, IltSection.Games, IltSection.Guardian, + }; + + public static string Label(IltSection s) => s switch + { + IltSection.Character => "Character", + IltSection.Quests => "Quests", + IltSection.Pet => "Pets", + IltSection.Banking => "Banking", + IltSection.Gear => "Gear", + IltSection.Games => "Games", + IltSection.Guardian => "Guardian", + _ => s.ToString(), + }; + + /// Parses a "/ra hub open" section name (a few aliases accepted). + public static bool TryParse(string text, out IltSection section) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "character": case "char": case "rates": section = IltSection.Character; return true; + case "quests": case "quest": section = IltSection.Quests; return true; + case "pets": case "pet": section = IltSection.Pet; return true; + case "banking": case "bank": section = IltSection.Banking; return true; + case "gear": section = IltSection.Gear; return true; + case "games": case "game": section = IltSection.Games; return true; + case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true; + default: section = IltSection.Character; return false; + } + } + + public static bool IsOpen(IltCharacterState cs, IltSection s) => s switch + { + IltSection.Character => cs.CharacterWindowOpen, + IltSection.Quests => cs.QuestTrackerPoppedOut, + IltSection.Pet => cs.PetsWindowOpen, + IltSection.Banking => cs.BankingWindowOpen, + IltSection.Gear => cs.GearWindowOpen, + IltSection.Games => cs.GamesWindowOpen, + IltSection.Guardian => cs.GuardianWindowOpen, + _ => false, + }; + + public static void SetOpen(IltCharacterState cs, IltSection s, bool open) + { + switch (s) + { + case IltSection.Character: cs.CharacterWindowOpen = open; break; + case IltSection.Quests: cs.QuestTrackerPoppedOut = open; break; + case IltSection.Pet: cs.PetsWindowOpen = open; break; + case IltSection.Banking: cs.BankingWindowOpen = open; break; + case IltSection.Gear: cs.GearWindowOpen = open; break; + case IltSection.Games: cs.GamesWindowOpen = open; break; + case IltSection.Guardian: cs.GuardianWindowOpen = open; break; + } + } + + /// True when any section window is open. + public static bool AnyOpen(IltCharacterState cs) + { + foreach (IltSection s in All) + if (IsOpen(cs, s)) return true; + return false; + } + + /// "show" / "hide" / "toggle" (anything else toggles) applied to the current state. + public static bool Resolve(string mode, bool current) => (mode ?? string.Empty).ToLowerInvariant() switch + { + "show" or "on" or "open" => true, + "hide" or "off" or "close" => false, + _ => !current, + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltServerOptions.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltServerOptions.cs new file mode 100644 index 0000000..7c0597b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltServerOptions.cs @@ -0,0 +1,401 @@ +// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server. +// +// UB gated every Leaftide tool on a single test (WorldName == "InfiniteLeaftide" or a +// Force checkbox). That lies on shards where the operator turned Powerball, /myquests or +// a charm off. This module instead keeps one tri-state bit per feature: +// * World identity: Host.TryGetWorldName (or ForceLeaftideFeatures) decides whether we +// even ASK — it never switches a feature on by itself. +// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once +// ACECustom ships it. Today the server prints "Coming Soon", so: +// * Fallback: a one-shot login probe of read-only commands (/bank, /aug, /qb, /pets, +// /shinies, /xp, /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten. +// /enl is NEVER probed — it opens the enlightenment confirmation dialog. +// * Passive: explicit server refusals seen in chat at any time flip a bit to Off +// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...). +// Unknown bits are treated as OFF by anything that spends currency or runs automation. +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +/// Feature keys used by the gate table. +internal static class IltFeature +{ + public const string Bank = "bank"; + public const string Aug = "aug"; + public const string Enl = "enl"; + public const string Qb = "qb"; + public const string Pets = "pets"; + public const string Shinies = "shinies"; + public const string Xp = "xp"; + public const string Blackjack = "blackjack"; + public const string FBlackjack = "fblackjack"; + public const string Powerball = "powerball"; + public const string Quests = "quests"; + public const string Clap = "clap"; + public const string PetRefill = "pet_refill"; + public const string UniversalMastery = "universal_mastery"; + public const string RequireComps = "require_spell_comps"; + public const string PetBond = "pet_bond"; + public const string PetPotency = "pet_potency"; + + /// Key for a per-charm "enabled" bit, e.g. Charm("Guardian Hand") → "charm:guardianhand". + public static string Charm(string charmName) + { + var chars = (charmName ?? string.Empty).Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray(); + return "charm:" + new string(chars); + } +} + +/// Tri-state feature value. +internal enum IltTri { Unknown = -1, Off = 0, On = 1 } + +internal sealed class IltServerOptions +{ + private readonly RynthCoreHost _host; + private readonly IltChatCapture _capture; + private readonly IltHubState _state; + private readonly Action _chat; + + /// Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances). + public Action? ProbeReplyTap; + + private bool _refreshInFlight; + private int _probesOutstanding; + private long _loginAt; + private bool _loginRefreshDone; + + /// Wait this long after login before the one-shot refresh so chat/world are settled. + private const long LoginRefreshDelayMs = 6000; + + /// + /// Upper bound on waiting for the world name. The engine hook / launch-context file can report + /// it well after the 6 s delay (late inject, Decal coexistence); deciding "not ILT" on an empty + /// name would leave every feature bit Unknown and the Hub hidden for the whole session. + /// + private const long WorldNameWaitMs = 60000; + + public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action chat) + { + _host = host; + _capture = capture; + _state = state; + _chat = chat; + } + + // ── Identity ──────────────────────────────────────────────────────────── + + /// World name as reported by the engine login hook (empty if unknown). + public string WorldName + { + get + { + if (_host.HasGetWorldName && _host.TryGetWorldName(out string n) && !string.IsNullOrWhiteSpace(n)) + return n.Trim(); + return _state.ServerOptions.WorldName ?? string.Empty; + } + } + + /// True when the world is (or is declared to be) an ACECustom/ILT shard. + public bool IsIltLikeWorld + { + get + { + if (_state.ForceLeaftideFeatures) return true; + string w = WorldName; + return w.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase) + || w.Contains("leaftide", StringComparison.OrdinalIgnoreCase); + } + } + + /// True while a refresh (dump or probe) is running. + public bool IsRefreshing => _refreshInFlight; + + public string Source => _state.ServerOptions.Source; + public DateTime LastRefreshUtc => _state.ServerOptions.LastRefreshUtc; + + // ── Bit access ────────────────────────────────────────────────────────── + + public IltTri Get(string key) + => _state.ServerOptions.Bits.TryGetValue(key, out int v) ? (IltTri)Math.Clamp(v, -1, 1) : IltTri.Unknown; + + /// True only when the server positively reported the feature as available. + public bool IsOn(string key) => Get(key) == IltTri.On; + + /// True when the server positively reported the feature as unavailable. + public bool IsOff(string key) => Get(key) == IltTri.Off; + + public void Set(string key, IltTri value) + { + // Every feature gate reads these bits, so each transition is traced (IltOptions). + IltTri old = Get(key); + _state.ServerOptions.Bits[key] = (int)value; + if (old != value) RynthLog.Trace(LogCat.IltOptions, $"feature '{key}': {old} -> {value}"); + } + + /// At least one feature bit is On (Hub window shows only then, unless Force is on). + public bool AnyFeatureOn => _state.ServerOptions.Bits.Values.Any(v => v == 1); + + /// All known bits for the status display. + public IReadOnlyList> SnapshotBits() + => _state.ServerOptions.Bits.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).ToList(); + + // ── Lifecycle ─────────────────────────────────────────────────────────── + + /// Called at login: schedules the one-shot refresh (never a recurring timer). + public void OnLoginComplete() + { + _loginAt = Environment.TickCount64; + _loginRefreshDone = false; + } + + /// + /// Pump-thread tick: fires the delayed login refresh once. While the world name is still + /// unknown it keeps checking (a cheap string compare per tick) until the name arrives or + /// WorldNameWaitMs expires; only a known non-ILT world, or the timeout, ends the wait. + /// + public void Tick() + { + if (_loginRefreshDone || _loginAt == 0) return; + long sinceLogin = Environment.TickCount64 - _loginAt; + if (sinceLogin < LoginRefreshDelayMs) return; + + if (IsIltLikeWorld) + { + _loginRefreshDone = true; + RynthLog.Event(LogEvents.IltWorldCheck, + $"world check: '{WorldName}' is ILT-like (force={_state.ForceLeaftideFeatures}) - refreshing server options"); + Refresh(manual: false); + return; + } + + // World not reported yet: try again next tick rather than concluding "not ILT". + if (string.IsNullOrEmpty(WorldName) && sinceLogin < WorldNameWaitMs) + return; + + _loginRefreshDone = true; + RynthLog.Event(LogEvents.IltWorldCheck, + $"world check: '{WorldName}' is not ILT-like - login refresh skipped (waited {sinceLogin / 1000}s)"); + } + + /// + /// Runs the dump-then-probe refresh. Manual refreshes report progress in chat; the + /// login refresh is silent. + /// + public void Refresh(bool manual) + { + if (_refreshInFlight) + { + if (manual) _chat("[ILT Hub] Server options refresh already running."); + return; + } + if (!IsIltLikeWorld) + { + if (manual) _chat("[ILT Hub] This world is not an ILT/ACECustom shard (enable Force in the Hub to override)."); + return; + } + + _refreshInFlight = true; + _state.ServerOptions.WorldName = WorldName; + RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')"); + if (manual) _chat("[ILT Hub] Refreshing server options..."); + + // Step 1: structured dump. Lines start with "=== ILT Custom Features ===". + _capture.Enqueue(new IltChatRequest + { + Command = "/ilt features", + IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase) + || t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase) + || t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 1200, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = r => OnFeatureDump(r, manual), + }); + } + + private void OnFeatureDump(IltChatResult r, bool manual) + { + var fromDump = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string line in r.Lines) + { + if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue; + foreach (var kv in ParseFeatureLine(line)) + { + Set(kv.Key, kv.Value); + fromDump.Add(kv.Key); + } + } + + _state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe"; + RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}"); + RunProbes(fromDump, manual); + } + + /// + /// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0". + /// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys. + /// + internal static IEnumerable> ParseFeatureLine(string line) + { + string body = line.Substring("ILTFEATURE".Length).Trim(); + foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + int eq = token.IndexOf('='); + if (eq <= 0) continue; + string key = token.Substring(0, eq).Trim(); + string val = token.Substring(eq + 1).Trim(); + + if (key.Equals("charms", StringComparison.OrdinalIgnoreCase)) + { + foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + int c = pair.IndexOf(':'); + if (c <= 0) continue; + yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1))); + } + continue; + } + yield return new(MapServerKey(key), ParseTri(val)); + } + } + + private static IltTri ParseTri(string v) + { + v = v.Trim().ToLowerInvariant(); + return v is "1" or "on" or "true" or "yes" ? IltTri.On + : v is "0" or "off" or "false" or "no" ? IltTri.Off + : IltTri.Unknown; + } + + private static string MapServerKey(string key) + { + string k = key.Trim().ToLowerInvariant(); + return k switch + { + "powerball_enabled" => IltFeature.Powerball, + "quest_info_enabled" => IltFeature.Quests, + "pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill, + "pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery, + "pet_bond_enabled" => IltFeature.PetBond, + "pet_potency_enabled" => IltFeature.PetPotency, + _ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k, + }; + } + + // ── Probe ─────────────────────────────────────────────────────────────── + + /// One read-only probe: command, reply recogniser, feature key. + private readonly record struct Probe(string Key, string Command, Func IsReply); + + private static readonly Probe[] Probes = + { + new(IltFeature.Bank, "/bank", t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase) + || t.Contains("not permitted to use bank", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Aug, "/aug", t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) + || IltParse.AugLine.IsMatch(t)), + new(IltFeature.Qb, "/qb", t => t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("[QB]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Pets, "/pets", t => t.Contains("Your Pet Log", StringComparison.OrdinalIgnoreCase) + || IltParse.RosterLine.IsMatch(t) || t.Contains("Professor Ruggan", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Shinies, "/shinies", t => t.Contains("Your Shiny Log", StringComparison.OrdinalIgnoreCase) + || IltParse.RosterLine.IsMatch(t) || t.Contains("Shiny creatures", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Xp, "/xp", t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Powerball, "/pb", t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Blackjack, "/blackjack", IsParamErrorOr("blackjack", "bet amount")), + new(IltFeature.FBlackjack,"/fblackjack", IsParamErrorOr("blackjack", "bet amount")), + new(IltFeature.Clap, "/clap", IsParamErrorOr("clap", "AutoCraftingEnabled")), + }; + + /// Recognises ACE's wrong-parameter-count reply (command exists) or a keyword reply. + private static Func IsParamErrorOr(string keyword, string keyword2) => t => + t.StartsWith("Invalid parameter count", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Usage:", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("@" + keyword, StringComparison.OrdinalIgnoreCase) + || t.Contains(keyword2, StringComparison.OrdinalIgnoreCase) + || (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith(" alreadyKnown, bool manual) + { + var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).ToList(); + + // /enl is never probed (it pops the enlightenment confirmation). On an ILT-like + // world the command is part of ACECustom, so it is assumed present unless the + // dump said otherwise. + if (!alreadyKnown.Contains(IltFeature.Enl)) + Set(IltFeature.Enl, IltTri.On); + + _probesOutstanding = todo.Count; + if (_probesOutstanding == 0) { CompleteRefresh(manual); return; } + + foreach (var p in todo) + { + var probe = p; + _capture.Enqueue(new IltChatRequest + { + Command = probe.Command, + IsResponseLine = probe.IsReply, + IdleEndMs = 1500, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = r => + { + // Unknown command → Off. Any recognised reply → On. Silence → leave Unknown. + if (r.UnknownCommand) Set(probe.Key, IltTri.Off); + else if (r.Lines.Count > 0) Set(probe.Key, IltTri.On); + RynthLog.Trace(LogCat.IltOptions, $"probe {probe.Command}: lines={r.Lines.Count} unknown={r.UnknownCommand} timedOut={r.TimedOut}"); + try { ProbeReplyTap?.Invoke(probe.Key, r); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltOptions, ex, $"probe tap {probe.Key}"); } + if (--_probesOutstanding <= 0) CompleteRefresh(manual); + }, + }); + } + } + + private void CompleteRefresh(bool manual) + { + _refreshInFlight = false; + _state.ServerOptions.LastRefreshUtc = DateTime.UtcNow; + int on = _state.ServerOptions.Bits.Values.Count(v => v == 1); + int off = _state.ServerOptions.Bits.Values.Count(v => v == 0); + // Building the per-bit list is skipped unless the event is actually going to be recorded. + if (RynthLog.IsEventEnabled(LogEvents.IltOptionsRefreshed)) + RynthLog.Event(LogEvents.IltOptionsRefreshed, $"options refreshed via {Source} (manual={manual}): {on} on, {off} off - " + + string.Join(" ", _state.ServerOptions.Bits.Select(b => $"{b.Key}={b.Value}"))); + if (manual) + _chat($"[ILT Hub] Server options refreshed via {Source}: {on} on, {off} off."); + } + + // ── Passive refusals ──────────────────────────────────────────────────── + + /// + /// Watches every chat line for explicit server refusals and flips the matching bit Off. + /// Cheap substring checks; runs on the pump thread. + /// + public void OnChatLine(string text) + { + if (text.Contains("Powerball lottery is not currently active", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Powerball, IltTri.Off); + else if (text.Contains("\"myquests\" is not currently enabled", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Quests, IltTri.Off); + else if (text.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Qb, IltTri.Off); + else if (text.Contains("must have received the AutoCraftingEnabled quest stamp", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Clap, IltTri.Off); + else if (text.Contains("Universal Summoning Mastery is not enabled on this server", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.UniversalMastery, IltTri.Off); + else if (text.Contains("Auto-Rebuff Charm is currently disabled globally", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off); + else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Bank, IltTri.Off); + } + + /// Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes). + public void NoteQuestTrackerOutcome(bool disabled, int recordCount) + { + if (disabled) Set(IltFeature.Quests, IltTri.Off); + else if (recordCount > 0) Set(IltFeature.Quests, IltTri.On); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSessionRates.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSessionRates.cs new file mode 100644 index 0000000..9b19ef6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSessionRates.cs @@ -0,0 +1,240 @@ +// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab. +// +// Sources (all passive — nothing is sent to the server except the optional bank refresh +// the Banking tab already does): +// XP player quad 1 (TotalExperience) delta since session start. +// Luminance "You've banked N Luminance" chat lines (ILT overflow-to-bank message). +// Coins positive bank Enlightened Coins deltas + carried coin (WCID 300004) gains. +// Pyreals positive bank pyreal deltas + carried pyreal (WCID 273) gains; MMD = 250k. +// Items gains of each item in the item→coin conversion table (carried count), +// converted to potential coins with ItemsPerConversion / CoinsPerConversion. +// Kills RynthAiPlugin.OnKillNotification. +using System; +using System.Collections.Generic; +using System.Linq; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +internal sealed class IltSessionRates : IIltFeature +{ + private const long PyrealsPerMmd = 250_000; + private const long SampleIntervalMs = 5000; + + private readonly IltHubContext _ctx; + private DateTime _start = DateTime.UtcNow; + + private long _startXp = -1; + private long _xp; + private long _lum; + private long _coins; + private long _pyreals; + private int _kills; + + // Carried-item baselines (last seen counts) for gain tracking. + private long _lastInvCoins = -1; + private long _lastInvPyreals = -1; + private readonly Dictionary _lastItemCounts = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _itemGains = new(StringComparer.OrdinalIgnoreCase); + private long _lastSampleAt; + + // Render snapshot. + private volatile RateRow[] _rows = Array.Empty(); + private sealed record RateRow(string Label, string Total, string PerHour); + + /// Per-hour figures for the Mini Remote HUD (rebuilt every sample). + public sealed record RateSummary(double XpPerHour, double LumPerHour, double KillsPerHour, + double CoinsPerHour, double PyrealsPerHour, long Xp, int Kills); + private static readonly RateSummary EmptySummary = new(0, 0, 0, 0, 0, 0, 0); + private volatile RateSummary _summary = EmptySummary; + + /// Latest per-hour summary (safe from the render thread). + public RateSummary Summary => _summary; + /// When the current session (or the last Reset) started. + public DateTime SessionStartUtc => _start; + + public IltSessionRates(IltHubContext ctx) => _ctx = ctx; + + /// Banking hook: bank balance changed (pump thread). + public void OnBankBalanceChanged(string key, long oldValue, long newValue) + { + RynthLog.Trace(LogCat.IltRates, $"balance {key}: {oldValue} -> {newValue}"); + // The first read after login only establishes the baseline (old value is the stale cache). + if (_lastSampleAt == 0) return; + long delta = newValue - oldValue; + if (delta <= 0) return; // spending / sending isn't income + if (key == "EnlightenedCoins") _coins += delta; + else if (key == "Pyreals") _pyreals += delta; + } + + public void RecordKill() => _kills++; + + public void Reset() + { + RynthLog.Trace(LogCat.IltRates, $"Reset()"); + _start = DateTime.UtcNow; + _startXp = -1; + _xp = _lum = _coins = _pyreals = 0; + _kills = 0; + _lastInvCoins = _lastInvPyreals = -1; + _lastItemCounts.Clear(); + _itemGains.Clear(); + _lastSampleAt = 0; + _summary = EmptySummary; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastSampleAt < SampleIntervalMs) return; + _lastSampleAt = nowMs; + var inv = _ctx.Inventory; + + long totalXp = inv.PlayerQuad(IltInventory.QuadTotalXp); + if (totalXp > 0) + { + if (_startXp < 0) _startXp = totalXp; + _xp = Math.Max(0, totalXp - _startXp); + } + + _coins += Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin)); + _pyreals += Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal)); + + // ToArray: the render thread edits this table. + foreach (var conv in _ctx.State.Character.ItemConversions.ToArray()) + { + if (string.IsNullOrWhiteSpace(conv.ItemName)) continue; + long count = inv.CountByName(conv.ItemName); + long last = _lastItemCounts.TryGetValue(conv.ItemName, out long l) ? l : -1; + long gain = Gain(ref last, count); + _lastItemCounts[conv.ItemName] = last; + if (gain > 0) _itemGains[conv.ItemName] = (_itemGains.TryGetValue(conv.ItemName, out long g) ? g : 0) + gain; + } + + BuildRows(); + } + + /// Positive change since the last sample; the first sample only sets the baseline. + private static long Gain(ref long last, long current) + { + if (last < 0) { last = current; return 0; } + long d = current - last; + last = current; + return d > 0 ? d : 0; + } + + public bool OnChat(string text) + { + var m = IltParse.LumBanked.Match(text); + if (m.Success) _lum += IltParse.ParseLeadingLong(m.Groups["amt"].Value); + return false; + } + + public void OnLogout() => Reset(); + + // ── Rows ──────────────────────────────────────────────────────────────── + + private void BuildRows() + { + double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600); + _summary = new RateSummary(_xp / hours, _lum / hours, _kills / hours, _coins / hours, _pyreals / hours, _xp, _kills); + var rows = new List + { + Row("XP", _xp, hours), + Row("Luminance banked", _lum, hours), + Row("Enlightened Coins", _coins, hours), + Row("Pyreals", _pyreals, hours), + new(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.0")), + new("Kills", _kills.ToString(), (_kills / hours).ToString("0")), + }; + + double potentialCoins = 0; + foreach (var conv in _ctx.State.Character.ItemConversions.ToArray()) + { + if (!_itemGains.TryGetValue(conv.ItemName, out long gained) || gained == 0) continue; + double coins = conv.ItemsPerConversion > 0 ? gained / (double)conv.ItemsPerConversion * conv.CoinsPerConversion : 0; + potentialCoins += coins; + rows.Add(new RateRow(" " + conv.ItemName, IltParse.N0(gained), IltParse.Compact(gained / hours))); + } + if (potentialCoins > 0) + rows.Add(new RateRow("Potential coins (items)", potentialCoins.ToString("0"), (potentialCoins / hours).ToString("0.0"))); + _rows = rows.ToArray(); + } + + private static RateRow Row(string label, long total, double hours) + => new(label, IltParse.Compact(total), IltParse.Compact(total / hours)); + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + var elapsed = DateTime.UtcNow - _start; + ImGui.TextDisabled($"Session {IltParse.Duration(elapsed)}"); + ImGui.SameLine(); + if (ImGui.SmallButton("Reset##rates")) _ctx.Post(Reset); + + if (ImGui.BeginTable("##iltrates", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV)) + { + ImGui.TableSetupColumn("Metric"); + ImGui.TableSetupColumn("Session"); + ImGui.TableSetupColumn("Per hour"); + ImGui.TableHeadersRow(); + foreach (var r in _rows) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total); + ImGui.TableNextColumn(); ImGui.TextColored(LegacyDashboardRenderer.ColTeal, r.PerHour); + } + ImGui.EndTable(); + } + + if (ImGui.TreeNode("Item -> coin conversions")) + { + RenderConversionEditor(); + ImGui.TreePop(); + } + } + + private string _newItemName = string.Empty; + + private void RenderConversionEditor() + { + var list = _ctx.State.Character.ItemConversions; + int remove = -1; + for (int i = 0; i < list.Count; i++) + { + var c = list[i]; + ImGui.PushID(i); + ImGui.TextUnformatted(c.ItemName); + ImGui.SameLine(220); + int items = c.ItemsPerConversion, coins = c.CoinsPerConversion; + ImGui.SetNextItemWidth(70); + if (ImGui.InputInt("items", ref items, 0)) c.ItemsPerConversion = Math.Max(1, items); + ImGui.SameLine(); + ImGui.SetNextItemWidth(70); + if (ImGui.InputInt("coins", ref coins, 0)) c.CoinsPerConversion = Math.Max(0, coins); + ImGui.SameLine(); + if (ImGui.SmallButton("x")) remove = i; + ImGui.PopID(); + } + if (remove >= 0) + { + var victim = list[remove]; + _ctx.Post(() => list.Remove(victim)); + } + + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint("##newconv", "exact item name", ref _newItemName, 96u); + ImGui.SameLine(); + if (ImGui.SmallButton("Add") && _newItemName.Trim().Length > 0 + && !list.Any(c => c.ItemName.Equals(_newItemName.Trim(), StringComparison.OrdinalIgnoreCase))) + { + var added = new IltItemConversion { ItemName = _newItemName.Trim(), ItemsPerConversion = 100, CoinsPerConversion = 0 }; + _ctx.Post(() => list.Add(added)); + _newItemName = string.Empty; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSplitArrows.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSplitArrows.cs new file mode 100644 index 0000000..0c56885 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSplitArrows.cs @@ -0,0 +1,205 @@ +// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2). +// +// ILT missile weapons carry a split-arrow count (int 9031). Each White Quartz salvage +// application adds one split and uses one tink. Per weapon: +// needed = min(target - current, 10 - tinks, 10 - current) +// The imbuer applies full (100-unit) White Quartz bags, lowest workmanship first, with +// UseObjectOn(salvage, weapon). AC then shows its own craft confirmation — the player +// clicks it; the imbuer waits (20 s) for the "successfully applies" / "fails to apply" +// line before the next step. Nothing is ever applied without the Hub confirm first. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +internal sealed class IltSplitArrows : IIltFeature +{ + private const int MaterialWhiteQuartz = 46; + private const uint IntNumItemsInMaterial = 170; + private const uint IntItemWorkmanship = 105; + private const long StepTimeoutMs = 20_000; + + private static readonly Regex Applied = new( + @"^(?[\w\s]+) successfully applies the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Failed = new( + @"^(?[\w\s]+) fails to apply the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private readonly IltHubContext _ctx; + + // Job state (pump thread) + private int _weaponId; + private int _remaining; + private bool _waiting; + private long _stepStartedAt; + private volatile string _status = "idle"; + + // Render snapshot of eligible weapons + private volatile WeaponRow[] _weapons = Array.Empty(); + private long _lastScan; + private sealed record WeaponRow(int Id, string Name, int Splits, int Tinks, bool Imbued, int Needed); + + public IltSplitArrows(IltHubContext ctx) => _ctx = ctx; + + private IltGearState G => _ctx.State.Gear; + public bool Running => _weaponId != 0; + + private int Needed(WorldObject w) + { + var inv = _ctx.Inventory; + int cur = inv.Int(w, IltInventory.IntSplitArrowCount); + int tinks = inv.Int(w, IltInventory.IntNumTimesTinkered); + int target = Math.Clamp(G.SplitArrowTarget, 0, 10); + return Math.Max(0, Math.Min(target - cur, Math.Min(10 - tinks, 10 - cur))); + } + + /// Full White Quartz bags, lowest workmanship first. + private List QuartzBags() + { + var inv = _ctx.Inventory; + return inv.Items() + .Where(wo => wo.ObjectClass == AcObjectClass.Salvage + && (inv.Int(wo, IltInventory.IntMaterialType) == MaterialWhiteQuartz || wo.Name.Contains("White Quartz", StringComparison.OrdinalIgnoreCase)) + && inv.Uses(wo) >= 100) + .OrderBy(Workmanship) + .ToList(); + } + + private double Workmanship(WorldObject bag) + { + int total = _ctx.Inventory.Int(bag, IntItemWorkmanship); + int items = Math.Max(1, _ctx.Inventory.Int(bag, IntNumItemsInMaterial, 1)); + return total / (double)items; + } + + /// Starts imbuing one weapon (pump thread, after the UI confirm). + public void Start(int weaponId) + { + var w = _ctx.Inventory.Cache?[weaponId]; + if (w == null) { _status = "weapon not found"; return; } + if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; } + int need = Needed(w); + if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; } + _weaponId = weaponId; + _remaining = need; + _waiting = false; + _status = $"imbuing {w.Name}: {need} application(s)"; + } + + public void Stop(string why) + { + _weaponId = 0; + _waiting = false; + _status = why; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastScan >= 3000 && _ctx.WindowOpen) + { + _lastScan = nowMs; + ScanWeapons(); + } + if (_weaponId == 0) return; + + if (_waiting) + { + if (nowMs - _stepStartedAt > StepTimeoutMs) Stop("no result within 20 s (craft dialog not confirmed?) - stopped"); + return; + } + if (_remaining <= 0) { Stop("done"); return; } + if (_ctx.Inventory.IsBusy) return; + + var bag = QuartzBags().FirstOrDefault(); + if (bag == null) { Stop("out of full White Quartz bags"); return; } + if (_ctx.Inventory.UseOn(bag, unchecked((uint)_weaponId))) + { + _waiting = true; + _stepStartedAt = nowMs; + _status = $"applying {bag.Name} - confirm the craft dialog in AC ({_remaining} left)"; + } + } + + public bool OnChat(string text) + { + if (!_waiting) return false; + if (Applied.IsMatch(text)) + { + _waiting = false; + _remaining--; + _status = $"applied ({_remaining} left)"; + } + else if (Failed.IsMatch(text)) + { + // A failed tink still consumes a tink slot — recompute from the weapon. + _waiting = false; + var w = _ctx.Inventory.Cache?[_weaponId]; + _remaining = w != null ? Math.Min(_remaining, Needed(w)) : 0; + _status = $"application failed ({_remaining} left)"; + } + return false; + } + + public void OnLogout() => Stop("idle"); + + private void ScanWeapons() + { + var inv = _ctx.Inventory; + var rows = new List(); + foreach (var wo in inv.Items()) + { + if (wo.ObjectClass != AcObjectClass.MissileWeapon) continue; + bool imbued = inv.Int(wo, IltInventory.IntImbuedEffect) != 0; + if (imbued && G.SplitIgnoreImbued) continue; + rows.Add(new WeaponRow(wo.Id, wo.Name, inv.Int(wo, IltInventory.IntSplitArrowCount), + inv.Int(wo, IltInventory.IntNumTimesTinkered), imbued, Needed(wo))); + } + _weapons = rows.OrderByDescending(r => r.Needed).ThenBy(r => r.Name).ToArray(); + _bagCount = QuartzBags().Count; + } + + private volatile int _bagCount; + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Split arrows (White Quartz)"); + int tgt = G.SplitArrowTarget; + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Target splits", ref tgt, 0, 10)) G.SplitArrowTarget = tgt; + ImGui.SameLine(); + bool skip = G.SplitIgnoreImbued; + if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip; + ImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}"); + + foreach (var w in _weapons) + { + ImGui.PushID(w.Id); + ImGui.TextUnformatted($"{w.Name} splits {w.Splits}, tinks {w.Tinks}{(w.Imbued ? ", imbued" : "")}"); + ImGui.SameLine(); + ImGui.BeginDisabled(w.Needed <= 0 || Running); + if (ImGui.SmallButton($"Imbue +{w.Needed}")) + { + var row = w; + _ctx.Confirm("Split-arrow imbue", + $"Apply {row.Needed} White Quartz bag(s) to {row.Name}?\n\nEach application uses a tink and can fail.\n" + + "AC will ask you to confirm every craft.", + () => Start(row.Id), "Start"); + } + ImGui.EndDisabled(); + ImGui.PopID(); + } + if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried."); + if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player")); + ImGui.TextDisabled("Status: " + _status); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltTempleAttributes.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltTempleAttributes.cs new file mode 100644 index 0000000..c8c4939 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltTempleAttributes.cs @@ -0,0 +1,298 @@ +// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window). +// +// One row per Fiun attribute NPC plus the Guardian of Attribute Enlightenment riddle. Each row +// prefers the timed flag from /myquests (solves + exact cooldown). When /myquests lacks the flag +// it falls back to the "/qb list" wait stamp: a stamp appearing between two lists counts one +// turn-in and starts an estimated cooldown (CooldownHoursAssumed). Fallback counts and timers +// persist in IltGuardianState. +// +// Rows come from "infi attribute.csv" (RynthAi folder, then Documents\Asheron's Call - the UB +// location) when present: npc, attribute, stamp [, myQuestsKey]. Built-in rows missing from the +// file are appended. Pump thread computes; the render thread only reads Snapshot. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Install; +using RynthCore.Plugin.RynthAi.Meta; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +/// One tracked turn-in: the NPC, its attribute, the /qb wait flag and the /myquests keys to try. +internal sealed class IltTempleAttrRow +{ + public IltTempleAttrRow(string npc, string attribute, string stamp, string? myQuestsKey = null) + { + Npc = npc.Trim(); + Attribute = attribute.Trim(); + QbWaitFlag = ExtractQbFlag(stamp); + var keys = new List(); + void Add(string? k) + { + if (string.IsNullOrWhiteSpace(k)) return; + string t = k.Trim().ToLowerInvariant(); + if (!keys.Contains(t)) keys.Add(t); + } + Add(myQuestsKey); + Add(QbWaitFlag); + if (QbWaitFlag.EndsWith("Wait", StringComparison.OrdinalIgnoreCase) && QbWaitFlag.Length > 4) + Add(QbWaitFlag[..^4]); + MyQuestsKeys = keys.ToArray(); + } + + public string Npc { get; } + public string Attribute { get; } + /// /qb flag name (e.g. TempleAttributeStrengthWait). + public string QbWaitFlag { get; } + /// Lowercase /myquests keys in lookup order: CSV override, the wait flag, the flag without "Wait". + public string[] MyQuestsKeys { get; } + + /// "You've stamped X!" → "X"; a bare flag name is returned trimmed. + private static string ExtractQbFlag(string stamp) + { + string s = (stamp ?? string.Empty).Trim(); + const string prefix = "You've stamped "; + if (s.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) s = s[prefix.Length..]; + return s.Trim().TrimEnd('!', ' ', '\t', '\r', '\n'); + } +} + +/// What the Guardian window shows for one row. +internal sealed record IltTempleAttrStatus(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool FromMyQuests); + +internal sealed class IltTempleAttributes +{ + private const long RebuildIntervalMs = 1000; + private const string CsvName = "infi attribute.csv"; + + private static readonly IltTempleAttrRow[] DefaultRows = + { + new("Fiun Luunere", "Strength", "TempleAttributeStrengthWait"), + new("Fiun Bayaas", "Coordination", "TempleAttributeCoordinationWait"), + new("Fiun Ruun", "Endurance", "TempleAttributeEnduranceWait"), + new("Fiun Riish", "Quickness", "TempleAttributeQuicknessWait"), + new("Fiun Vasherr", "Focus", "TempleAttributeFocusWait"), + new("Fiun Noress", "Willpower", "TempleAttributeSelfWait"), + new("Fiun Vaelesh", "Health", "TempleAttributeHealthWait"), + new("Fiun Torrun", "Stamina", "TempleAttributeStamWait"), + new("Fiun Saeluun", "Mana", "TempleAttributeManaWait"), + new("Guardian (Attr)", "Riddle", "TempleAttributeRiddleWait"), + }; + + private readonly IltHubContext _ctx; + private readonly Func _tracker; + private readonly IltQuests _quests; + private readonly IltTempleAttrRow[] _rows; + // Wait-stamp presence per attribute at the previous "/qb list" (session only: a transition + // needs two lists in the same session). + private readonly Dictionary _lastHadWait = new(StringComparer.OrdinalIgnoreCase); + private int _seenQbGeneration; + private long _lastRebuildAt = -RebuildIntervalMs; + + private volatile IltTempleAttrStatus[] _snapshot = Array.Empty(); + private DateTime _syncedUtc = DateTime.MinValue; + + public IltTempleAttributes(IltHubContext ctx, Func tracker, IltQuests quests) + { + _ctx = ctx; + _tracker = tracker; + _quests = quests; + _rows = LoadRows(out string source); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] attribute rows: {_rows.Length} from {source}"); + } + + /// Rows as last computed (render thread reads this). + public IltTempleAttrStatus[] Snapshot => _snapshot; + + /// When the quest data behind the rows last changed (MinValue = never this session). + public DateTime SyncedUtc => _syncedUtc; + + private IltGuardianState S => _ctx.State.Guardian; + + // ── Rows file ─────────────────────────────────────────────────────────── + + /// The CSV in the RynthAi folder, else UB's Documents location; built-in rows otherwise. + private static IltTempleAttrRow[] LoadRows(out string source) + { + string[] candidates = + { + Path.Combine(RynthInstallPaths.RynthAiDir, CsvName), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", CsvName), + }; + foreach (string path in candidates) + { + try + { + if (!File.Exists(path)) continue; + var rows = ParseCsv(File.ReadAllLines(path)); + if (rows.Count == 0) continue; + source = path; + return MergeMissingDefaults(rows); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"read {path}"); } + } + source = "built-in table"; + return DefaultRows; + } + + /// npc, attribute, stamp [, myQuestsKey]; a header row and blank lines are skipped. + private static List ParseCsv(string[] lines) + { + var rows = new List(); + foreach (string raw in lines) + { + string line = raw.Trim().TrimStart('\uFEFF'); + if (line.Length == 0) continue; + if (line.StartsWith("npc", StringComparison.OrdinalIgnoreCase) && line.Contains("attribute", StringComparison.OrdinalIgnoreCase)) + continue; + string[] seg = line.Split(','); + if (seg.Length < 3) continue; + string npc = seg[0].Trim(), attr = seg[1].Trim(); + string stamp; + string? key = null; + if (seg.Length == 4) { stamp = seg[2].Trim(); key = seg[3].Trim(); } + else stamp = string.Join(",", seg.Skip(2)).Trim(); // a full stamp chat line may contain commas + if (npc.Length == 0 || attr.Length == 0 || stamp.Length == 0) continue; + rows.Add(new IltTempleAttrRow(npc, attr, stamp, key)); + } + return rows; + } + + private static IltTempleAttrRow[] MergeMissingDefaults(List loaded) + { + var seen = new HashSet(loaded.Select(r => r.QbWaitFlag), StringComparer.OrdinalIgnoreCase); + foreach (var def in DefaultRows) + if (seen.Add(def.QbWaitFlag)) loaded.Add(def); + return loaded.ToArray(); + } + + // ── Pump thread ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + int gen = _quests.QbGeneration; + if (gen != _seenQbGeneration) + { + _seenQbGeneration = gen; + if (gen > 0) ApplyQbTransitions(); + _syncedUtc = DateTime.UtcNow; + } + if (nowMs - _lastRebuildAt < RebuildIntervalMs) return; + _lastRebuildAt = nowMs; + Rebuild(); + } + + /// Re-asks the server for /myquests and "/qb list" (each limited to once a minute). + public string Refresh() => $"{_quests.RefreshQuests()} {_quests.RefreshQb()}"; + + /// Forgets the counted turn-ins and estimated cooldowns (the /qb fallback only). + public void ResetCounts() + { + S.TurnInCounts.Clear(); + S.CooldownUntilUtc.Clear(); + _lastRebuildAt = long.MinValue / 2; + } + + public void OnLogout() + { + _lastHadWait.Clear(); + _seenQbGeneration = 0; + _syncedUtc = DateTime.MinValue; + } + + private bool TryQuest(IltTempleAttrRow row, out QuestRecord rec) + { + rec = null!; + var t = _tracker(); + if (t == null) return false; + foreach (string key in row.MyQuestsKeys) + if (t.TryGetFlag(key, out rec)) return true; + return false; + } + + /// A new "/qb list" arrived: count wait stamps that appeared since the previous list. + private void ApplyQbTransitions() + { + int hours = Math.Max(1, S.CooldownHoursAssumed); + foreach (var row in _rows) + { + string key = row.Attribute; + bool hasWait = _quests.QbHasFlag(row.QbWaitFlag); + if (!TryQuest(row, out _)) + { + if (_lastHadWait.TryGetValue(key, out bool had) && !had && hasWait) + { + S.TurnInCounts[key] = (S.TurnInCounts.TryGetValue(key, out int n) ? n : 0) + 1; + S.CooldownUntilUtc[key] = DateTime.UtcNow.AddHours(hours); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] {key} turn-in counted from /qb (now {S.TurnInCounts[key]})"); + } + if (!hasWait) S.CooldownUntilUtc.Remove(key); + } + _lastHadWait[key] = hasWait; + } + } + + private void Rebuild() + { + bool qbLoaded = _quests.QbGeneration > 0; + int hours = Math.Max(1, S.CooldownHoursAssumed); + var list = new IltTempleAttrStatus[_rows.Length]; + for (int i = 0; i < _rows.Length; i++) + { + var row = _rows[i]; + if (TryQuest(row, out var rec)) + { + list[i] = FromQuest(row, rec); + continue; + } + + string key = row.Attribute; + int count = S.TurnInCounts.TryGetValue(key, out int c) ? c : 0; + if (!qbLoaded) + { + list[i] = new(key, row.Npc, count, "Unknown", "Refresh", false, false); + continue; + } + if (!_quests.QbHasFlag(row.QbWaitFlag)) + { + list[i] = new(key, row.Npc, count, "Ready", "-", true, false); + continue; + } + + // Wait stamp present: show the estimated cooldown, starting one if none is known. + if (!S.CooldownUntilUtc.TryGetValue(key, out DateTime until)) + S.CooldownUntilUtc[key] = until = DateTime.UtcNow.AddHours(hours); + until = AsUtc(until); + TimeSpan left = until - DateTime.UtcNow; + list[i] = left > TimeSpan.Zero + ? new(key, row.Npc, count, "Wait stamp", $"~{IltParse.Duration(left)} (est.)", false, false) + : new(key, row.Npc, count, "Wait stamp", "ready? (est.)", false, false); + } + _snapshot = list; + } + + /// A row backed by its /myquests flag: exact solves and cooldown. + private static IltTempleAttrStatus FromQuest(IltTempleAttrRow row, QuestRecord rec) + { + switch (IltQuests.Classify(rec)) + { + case IltQuests.QuestKind.KillTask: + return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true); + case IltQuests.QuestKind.Once: + return new(row.Attribute, row.Npc, rec.Solves, "Once", rec.Solves >= 1 ? "done" : "-", false, true); + default: + if (rec.IsReady()) return new(row.Attribute, row.Npc, rec.Solves, "Ready", "now", true, true); + TimeSpan left = rec.TimeUntilReady(); + string at = DateTime.Now.Add(left).ToString("ddd HH:mm"); + return new(row.Attribute, row.Npc, rec.Solves, "Cooldown", $"{IltParse.Duration(left)} ({at})", false, true); + } + } + + /// Stored times may load as Unspecified; they were written as UTC. + private static DateTime AsUtc(DateTime dt) => dt.Kind switch + { + DateTimeKind.Utc => dt, + DateTimeKind.Local => dt.ToUniversalTime(), + _ => DateTime.SpecifyKind(dt, DateTimeKind.Utc), + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltUsdImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltUsdImporter.cs new file mode 100644 index 0000000..2efd80a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/IltHub/IltUsdImporter.cs @@ -0,0 +1,351 @@ +// IltUsdImporter.cs — VirindiTank .usd settings → RynthAi monster / weapon / consumable rules (Gear tab, P2). +// +// .usd is VTank's line-based table dump. Each table is: +// +// +// x count +// x count +// +// per cell: then +// Tables we read: MyMonsters (monster rules), weapons/wands/shields/combatitems (weapon +// rules), pets (pet essences), items/itemlist/buffeditems/AssistItems (consumables). +// Object ids are resolved against the current inventory (id first, then name). The +// import is previewed first and only applied after a confirm; existing rules with the +// same name / id are replaced, everything else is kept. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.IltHub; + +internal sealed class IltUsdImporter +{ + /// Default VTank profile folder when the Decal registry value is unavailable. + public const string DefaultVtProfileDir = @"C:\Games\VirindiPlugins\VirindiTank\"; + + private static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; + private static readonly HashSet WeaponTables = new(StringComparer.OrdinalIgnoreCase) { "weapons", "wands", "shields", "combatitems" }; + private static readonly HashSet ConsumableTables = new(StringComparer.OrdinalIgnoreCase) { "items", "itemlist", "buffeditems", "assistitems" }; + + /// One parsed table: column names and rows of raw cell strings. + private sealed class UsdTable + { + public string Name = string.Empty; + public string[] Columns = Array.Empty(); + public List Rows = new(); + + public string Get(string[] row, params string[] names) + { + foreach (string n in names) + { + int i = Array.FindIndex(Columns, c => c.Equals(n, StringComparison.OrdinalIgnoreCase)); + if (i >= 0 && i < row.Length) return row[i] ?? string.Empty; + } + return string.Empty; + } + } + + /// Result of a preview: the rules that would be written. + private sealed class ImportPlan + { + public string Path = string.Empty; + public List Monsters = new(); + public List Weapons = new(); + public List Consumables = new(); + public List Notes = new(); + } + + private readonly IltHubContext _ctx; + private volatile ImportPlan? _plan; + private volatile string _status = string.Empty; + private string _pathInput = string.Empty; + + public IltUsdImporter(IltHubContext ctx) + { + _ctx = ctx; + _pathInput = ctx.State.Gear.LastUsdPath; + } + + /// VTank's profile folder from Decal's registry entry, else the default install path. + public static string VtProfileDir() + { + try + { + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\Decal\Plugins\{642F1F48-16BE-48BF-B1D4-286652C4533E}"); + if (key?.GetValue("ProfilePath") is string p && p.Length > 0 && Directory.Exists(p)) return p; + } + catch { /* registry unavailable: fall back */ } + return DefaultVtProfileDir; + } + + // ── Parsing ───────────────────────────────────────────────────────────── + + private static List Parse(string[] lines) + { + var tables = new List(); + int i = 0; + while (i < lines.Length - 1) + { + string name = lines[i].Trim(); + if (name.Length == 0 || !int.TryParse(lines[i + 1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int cols) + || cols < 1 || cols > 32 || name.Any(char.IsWhiteSpace)) + { + i++; + continue; + } + + int p = i + 2; + if (p + cols * 2 >= lines.Length) { i++; continue; } + var t = new UsdTable { Name = name, Columns = new string[cols] }; + for (int c = 0; c < cols; c++) t.Columns[c] = lines[p++].Trim(); + p += cols; // type tokens + if (p >= lines.Length || !int.TryParse(lines[p].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int rows) || rows < 0 || rows > 100_000) + { + i++; + continue; + } + p++; + bool ok = true; + for (int r = 0; r < rows && ok; r++) + { + var row = new string[cols]; + for (int c = 0; c < cols; c++) + { + if (p + 1 >= lines.Length) { ok = false; break; } + // Every cell is a tag line plus a value line; unknown tags are still two lines. + row[c] = lines[p + 1].Trim(); + p += 2; + } + if (ok) t.Rows.Add(row); + } + tables.Add(t); + i = p; + } + return tables; + } + + private static int ParseId(string s) + { + s = s.Trim(); + if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + && int.TryParse(s.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int hex)) return hex; + if (long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out long l)) return unchecked((int)l); + return 0; + } + + private static bool ValidId(int id) => id != 0 && id != -1 && id != -5; + + private static bool ParseBool(string s) + => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase); + + /// VTank damage value (name or AC damage-type bitmask) → RynthAi element, or null. + private static string? MapElement(string v) + { + v = v.Trim(); + if (v.Length == 0) return null; + foreach (string e in Elements) if (v.Equals(e, StringComparison.OrdinalIgnoreCase)) return e; + if (v.StartsWith("Bludg", StringComparison.OrdinalIgnoreCase)) return "Bludgeon"; + if (v.StartsWith("Pierc", StringComparison.OrdinalIgnoreCase)) return "Pierce"; + if (v.StartsWith("Electric", StringComparison.OrdinalIgnoreCase)) return "Lightning"; + if (v.StartsWith("Void", StringComparison.OrdinalIgnoreCase)) return "Nether"; + if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out int dt) || dt <= 0) return null; + return BitsToElement(dt); + } + + private static string? BitsToElement(int dt) + { + if ((dt & 1024) != 0) return "Nether"; + if ((dt & 16) != 0) return "Fire"; + if ((dt & 8) != 0) return "Cold"; + if ((dt & 64) != 0) return "Lightning"; + if ((dt & 32) != 0) return "Acid"; + if ((dt & 4) != 0) return "Bludgeon"; + if ((dt & 2) != 0) return "Pierce"; + if ((dt & 1) != 0) return "Slash"; + return null; + } + + /// Resolves a USD object (id, name) to a carried item. + private WorldObject? Resolve(int id, string name) + { + var cache = _ctx.Inventory.Cache; + if (cache == null) return null; + if (ValidId(id)) + { + var byId = cache[id]; + if (byId != null) return byId; + } + if (string.IsNullOrWhiteSpace(name)) return null; + return _ctx.Inventory.Items().FirstOrDefault(w => w.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)); + } + + private static string ConsumableType(string name) + { + string n = name.ToLowerInvariant(); + if (n.Contains("essence")) return "Pet"; + if (n.Contains("kit")) return "HealthKit"; + if (n.Contains("mana stone") || n.Contains("mana charge")) return "ManaStone"; + if (n.Contains("stamina")) return "Stamina"; + if (n.Contains("lockpick")) return "Lockpick"; + return "General"; + } + + // ── Preview / apply (pump thread) ─────────────────────────────────────── + + public void Preview(string path) + { + path = (path ?? string.Empty).Trim().Trim('"'); + if (path.Length > 0 && !Path.IsPathRooted(path)) path = Path.Combine(VtProfileDir(), path); + if (!File.Exists(path)) { _status = "File not found: " + path; _plan = null; return; } + + string[] lines; + try { lines = File.ReadAllLines(path); } + catch (Exception ex) { _status = "Read failed: " + ex.Message; _plan = null; return; } + + var plan = new ImportPlan { Path = path }; + foreach (var t in Parse(lines)) + { + if (t.Name.Equals("MyMonsters", StringComparison.OrdinalIgnoreCase)) PlanMonsters(t, plan); + else if (WeaponTables.Contains(t.Name)) PlanWeapons(t, plan); + else if (t.Name.Equals("pets", StringComparison.OrdinalIgnoreCase)) PlanConsumables(t, plan, forceType: "Pet"); + else if (ConsumableTables.Contains(t.Name)) PlanConsumables(t, plan, forceType: null); + } + _ctx.State.Gear.LastUsdPath = path; + _plan = plan; + _status = $"Preview: {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables."; + } + + private void PlanMonsters(UsdTable t, ImportPlan plan) + { + foreach (var row in t.Rows) + { + string name = t.Get(row, "MonsterName", "Name").Trim(); + if (name.Length == 0) continue; + var rule = new MonsterRule + { + Name = name, + Priority = int.TryParse(t.Get(row, "AttackPriority", "Priority"), out int pri) ? Math.Max(0, pri) : 1, + DamageType = MapElement(t.Get(row, "DamageType")) ?? "Auto", + ExVuln = MapElement(t.Get(row, "SecondaryVuln", "ExtraVuln")) ?? "None", + PetDamage = MapElement(t.Get(row, "PetDamage")) ?? "PAuto", + UseRing = ParseBool(t.Get(row, "Ring")), + UseStreak = ParseBool(t.Get(row, "Streak")), + UseArc = ParseBool(t.Get(row, "Arc")), + Fester = ParseBool(t.Get(row, "Fester")), + Broadside = ParseBool(t.Get(row, "Broadside")), + GravityWell = ParseBool(t.Get(row, "GravityW", "GravityWell")), + Imperil = ParseBool(t.Get(row, "Imperil")), + Yield = ParseBool(t.Get(row, "Yield")), + Vuln = ParseBool(t.Get(row, "Vuln")), + }; + var weapon = Resolve(ParseId(t.Get(row, "WeaponToUse", "Weapon")), t.Get(row, "WeaponName")); + if (weapon != null) rule.WeaponId = weapon.Id; + else if (t.Get(row, "WeaponName").Length > 0) plan.Notes.Add($"{name}: weapon '{t.Get(row, "WeaponName")}' not carried"); + var off = Resolve(ParseId(t.Get(row, "SecondaryEquip", "Offhand")), t.Get(row, "OffhandName")); + if (off != null) rule.OffhandId = off.Id; + plan.Monsters.Add(rule); + } + } + + private void PlanWeapons(UsdTable t, ImportPlan plan) + { + // The VT "shields" table (or any row whose item wields into the shield slot) + // becomes an off-hand Shield entry, never a main-hand weapon. + bool shieldTable = t.Name.Equals("shields", StringComparison.OrdinalIgnoreCase); + foreach (var row in t.Rows) + { + int id = ParseId(t.Get(row, "Object", "ObjectId", "Id")); + string name = t.Get(row, "Name").Trim(); + var wo = Resolve(id, name); + if (wo == null) { if (name.Length > 0) plan.Notes.Add($"weapon '{name}' not carried"); continue; } + if (plan.Weapons.Any(w => w.Id == wo.Id)) continue; + bool isShield = shieldTable || RynthCore.Plugin.RynthAi.CombatManager.IsShieldItem(wo); + string element = BitsToElement(wo.Values(LongValueKey.DamageType, 0)) ?? "Slash"; + plan.Weapons.Add(new ItemRule + { + Id = wo.Id, + Name = wo.Name, + Action = isShield ? ItemRule.ShieldAction : ItemRule.WeaponAction, + Element = element, + }); + } + } + + private void PlanConsumables(UsdTable t, ImportPlan plan, string? forceType) + { + foreach (var row in t.Rows) + { + int id = ParseId(t.Get(row, "Object", "ObjectId", "Id")); + string name = t.Get(row, "Name").Trim(); + var wo = Resolve(id, name); + if (wo == null) { if (name.Length > 0) plan.Notes.Add($"item '{name}' not carried"); continue; } + if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb) continue; + if (plan.Consumables.Any(c => c.Id == wo.Id)) continue; + plan.Consumables.Add(new ConsumableRule { Id = wo.Id, Name = wo.Name, Type = forceType ?? ConsumableType(wo.Name) }); + } + } + + /// Writes the previewed rules into the live settings and saves them. + public void Apply() + { + var plan = _plan; + var s = _ctx.Settings; + if (plan == null || s == null) { _status = "Nothing to apply."; return; } + + foreach (var m in plan.Monsters) + { + s.MonsterRules.RemoveAll(r => r.Name.Equals(m.Name, StringComparison.OrdinalIgnoreCase)); + s.MonsterRules.Add(m); + } + foreach (var w in plan.Weapons) + { + s.ItemRules.RemoveAll(r => r.Id == w.Id); + s.ItemRules.Add(w); + } + foreach (var c in plan.Consumables) + { + s.ConsumableRules.RemoveAll(r => r.Id == c.Id); + s.ConsumableRules.Add(c); + } + _ctx.SaveCombatSettings?.Invoke(); + _status = $"Imported {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables."; + _ctx.Chat("[ILT Hub] " + _status); + _plan = null; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Import VirindiTank settings (.usd)"); + ImGui.SetNextItemWidth(320); + ImGui.InputTextWithHint("##usdpath", @"full path or file name in C:\Games\VirindiPlugins\VirindiTank", ref _pathInput, 260u); + ImGui.SameLine(); + string p = _pathInput; + if (ImGui.SmallButton("Preview")) _ctx.Post(() => Preview(p)); + + var plan = _plan; + if (plan != null) + { + ImGui.TextUnformatted($"{plan.Monsters.Count} monster rules, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables"); + if (ImGui.TreeNode("Preview details")) + { + foreach (var m in plan.Monsters.Take(50)) ImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}"); + foreach (var w in plan.Weapons) ImGui.BulletText($"Weapon {w.Name} [{w.Element}]"); + foreach (var c in plan.Consumables) ImGui.BulletText($"{c.Type}: {c.Name}"); + foreach (var n in plan.Notes.Take(30)) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, n); + ImGui.TreePop(); + } + if (ImGui.Button("Apply import...")) + _ctx.Confirm("Import VTank settings", + $"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced.", + Apply, "Import"); + } + if (_status.Length > 0) ImGui.TextWrapped(_status); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ImGuiNativeBinding.cs b/Plugins/RynthCore.Plugin.RynthAi/ImGuiNativeBinding.cs new file mode 100644 index 0000000..9d75b96 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ImGuiNativeBinding.cs @@ -0,0 +1,69 @@ +// ImGuiNativeBinding.cs - Binds ImGui.NET's "cimgui" P/Invokes to the cimgui module the +// engine already loaded. +// +// The engine ships its own build as RynthCore.cimgui.dll. Without this resolver, Windows +// resolves "cimgui" to a separate cimgui.dll: a second ImGui instance whose windows (ILT Hub, +// Pets, Quests, Mini Remote, Item HUD) are built but never reach the engine's draw data. +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthAi; + +internal static class ImGuiNativeBinding +{ + private const string EngineModule = "RynthCore.cimgui.dll"; + private const string LegacyModule = "cimgui.dll"; + + private static int _configured; // 1 once the resolver is registered (survives DLL-copy reuse) + private static int _resolvedLogged; + + /// + /// Registers the resolver. Call before the first ImGui call (Initialize). The resolver can be + /// set only once per assembly, so later calls (a reused plugin DLL copy) are no-ops. + /// + public static void Ensure() + { + if (Interlocked.Exchange(ref _configured, 1) != 0) return; + try + { + NativeLibrary.SetDllImportResolver(typeof(ImGui).Assembly, Resolve); + RynthLog.Write(LogCat.UI, "[ImGui] native resolver registered (prefers the engine's " + EngineModule + ")."); + } + catch (InvalidOperationException) + { + // Already registered by an earlier instance in this process. + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.UI, ex, "ImGuiNativeBinding.Ensure"); + } + } + + /// Runs on the first cimgui P/Invoke: the engine's module, else whatever cimgui.dll is loaded. + private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + { + if (!string.Equals(libraryName, "cimgui", StringComparison.OrdinalIgnoreCase) && + !string.Equals(libraryName, LegacyModule, StringComparison.OrdinalIgnoreCase)) + return IntPtr.Zero; + + string bound = EngineModule; + IntPtr module = GetModuleHandleA(EngineModule); + if (module == IntPtr.Zero) + { + bound = LegacyModule; + module = GetModuleHandleA(LegacyModule); + } + + if (Interlocked.Exchange(ref _resolvedLogged, 1) == 0) + RynthLog.Write(LogCat.UI, module != IntPtr.Zero + ? $"[ImGui] cimgui bound to loaded {bound} (0x{module.ToInt64():X})." + : "[ImGui] no loaded cimgui module found; falling back to the default DLL search."); + return module; // IntPtr.Zero = default resolution + } + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] + private static extern IntPtr GetModuleHandleA(string lpModuleName); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs new file mode 100644 index 0000000..dab4088 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemDescriber.cs @@ -0,0 +1,673 @@ +// MagItemDescriber.cs — one-line "Mag-style" item info (Mag-Tools ItemInfo / UtilityBelt ub-IT ItemInfo). +// +// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, CS, Undead Slayer, Tinks 4, +// Applied: Steel x2, 152.48-236, 0.35v, +18%a, 12%md, Legendary Blood Thirst, Wield Lvl 180, +// Heavy Weapons 375, Diff 270, Craft 8, [D 3, CD 2] +// +// The same fields can also print as the pet-roster layout (IltPetStats: identity line, stats +// line, ratings/requirements line), plus a spells line: +// +// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8 +// CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md +// [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270 +// Spells: Legendary Blood Thirst +// +// Field order and per-class gating follow ub-IT (Tools/ItemInfo.cs ItemDescriptions.ToString, +// Lib/ItemDescribeMagShorthand.cs, Lib/ItemInfoHelper/ItemIdentifyFieldSet.cs); labels and the +// spell filter follow Mag-Tools. All ids are raw ACE properties (RynthCore reads CBaseQualities by +// STypeInt/STypeFloat/STypeString id — not Decal's remapped LongValueKey/DoubleValueKey numbers). +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using RynthCore.Loot; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +/// Property reads for one item. Implemented over the live object cache (see +/// ); a missing property returns false / empty. +internal interface IItemPropertySource +{ + string Name { get; } + AcObjectClass ObjectClass { get; } + bool TryGetInt(uint stype, out int value); + bool TryGetDouble(uint stype, out double value); + string GetString(uint stype); + /// Spell ids on the item (inscribed + cantrips), unsorted. + IReadOnlyList SpellIds { get; } +} + +/// Per-call output options, snapshotted from . +internal readonly record struct MagItemInfoOptions( + MagItemInfoField Hidden, int HiddenRatings, bool ShowValueAndBurden, bool AllSpells, int MaxListedSpells) +{ + /// Everything shown, Mag spell filter — used when no settings are loaded yet. + public static readonly MagItemInfoOptions Default = new(MagItemInfoField.None, 0, false, false, 26); + + public static MagItemInfoOptions From(MagItemInfoSettings? s) => s == null + ? Default + : new((MagItemInfoField)s.HiddenFields, s.HiddenRatings, s.ShowValueAndBurden, + s.SpellMode == MagItemInfoSettings.SpellModeAll, s.MaxListedSpells); + + public bool Shows(MagItemInfoField f) => (Hidden & f) == 0; +} + +/// Which pet-style line a field lands on (). +internal enum MagItemSection +{ + /// Line 1 after the name: set, AL, tinks, applied, craft, keyring. + Identity, + /// Line 2: imbues, slayer, damage, attack/defense/mana-conversion, protections. + Combat, + /// Line 3 lead: the "[D 3, CD 2]" cluster. + Ratings, + /// Line 3 tail: wield / activation / difficulty, value and burden. + Requirements, + /// Line 4: spell names. + Spells, +} + +/// +/// One described item: the title plus fields tagged with their section, kept in Mag print order +/// so reproduces the classic line exactly. +/// +internal sealed class MagItemDescription +{ + /// "[Material ]Name[ (DamageType Mastery)]". + public string Title = string.Empty; + public readonly List<(MagItemSection Section, string Text)> Segments = new(); + + public void Add(MagItemSection section, string text) + { + if (!string.IsNullOrEmpty(text)) Segments.Add((section, text)); + } + + /// Classic Mag one-liner: title, then every field comma-separated. + public string ToOneLine() + { + var sb = new StringBuilder(Title, 256); + foreach (var (_, text) in Segments) sb.Append(", ").Append(text); + return sb.ToString(); + } + + /// + /// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are + /// dropped so plain armor stays short. + /// + public List ToPetLines() + { + var lines = new List(4); + + var identity = new StringBuilder(Title); + foreach (string t in Section(MagItemSection.Identity)) identity.Append(", ").Append(t); + lines.Add(identity.ToString()); + + string combat = string.Join(", ", Section(MagItemSection.Combat)); + if (combat.Length > 0) lines.Add(combat); + + // Like the pet roster's third line: ratings first, then the rest two-space separated. + var tail = new List(2); + string ratings = string.Join(", ", Section(MagItemSection.Ratings)); + if (ratings.Length > 0) tail.Add(ratings); + string reqs = string.Join(", ", Section(MagItemSection.Requirements)); + if (reqs.Length > 0) tail.Add(reqs); + if (tail.Count > 0) lines.Add(string.Join(" ", tail)); + + var spells = Section(MagItemSection.Spells); + if (spells.Count > 0) + { + // The verbose list is a single pre-labelled "Spells: a; b" segment. + lines.Add(spells.Count == 1 && spells[0].StartsWith("Spells:", StringComparison.Ordinal) + ? spells[0] + : "Spells: " + string.Join(", ", spells)); + } + return lines; + } + + private List Section(MagItemSection section) + { + var list = new List(); + foreach (var (s, text) in Segments) + if (s == section) list.Add(text); + return list; + } +} + +/// Builds the Mag-style item info line. +internal static class MagItemDescriber +{ + // ── ACE PropertyInt ids ────────────────────────────────────────────────── + private const uint IntBurden = 5; // EncumbranceVal + private const uint IntValue = 19; + private const uint IntArmorLevel = 28; + private const uint IntResistMagic = 36; // >= 9999 = unenchantable + private const uint IntMaxDamage = 44; // Damage + private const uint IntDamageType = 45; + private const uint IntAttackType = 47; + private const uint IntStructure = 92; // keyring uses remaining + private const uint IntWorkmanship = 105; + private const uint IntItemDifficulty = 109; // arcane lore requirement ("Diff") + private const uint IntActivationLevel = 115; // ItemSkillLevelLimit + private const uint IntMaterial = 131; + private const uint IntWieldReq = 158; + private const uint IntWieldSkill = 159; + private const uint IntWieldValue = 160; + private const uint IntSlayerCreature = 166; + private const uint IntNumItemsInMaterial = 170; // salvage: workmanship = 105 / 170 + private const uint IntTinks = 171; + private const uint IntActivationSkill = 176; // AppraisalItemSkill + private const uint IntImbued = 179; // ImbuedEffect (+ 303..306 for 2..5) + private const uint IntNumKeys = 193; + private const uint IntElementalBonus = 204; + private const uint IntEquipmentSet = 265; + private const uint IntWieldReq2 = 270; + private const uint IntWieldSkill2 = 271; + private const uint IntWieldValue2 = 272; + private const uint IntWeaponType = 353; // mastery + private const uint IntUseRequiresSkill = 366; + private const uint IntUseRequiresSkillLvl = 367; + private const uint IntUseRequiresSpec = 368; + private const uint IntUseRequiresLevel = 369; + private const uint IntSplitArrows = 9031; // ACECustom SplitArrowCount + + // ── ACE PropertyFloat ids ──────────────────────────────────────────────── + private const uint FloatArmorVsSlash = 13; // 13..19 = Slash/Pierce/Bludgeon/Cold/Fire/Acid/Electric + private const uint FloatVariance = 22; + private const uint FloatMaxVelocity = 26; + private const uint FloatMeleeDefense = 29; // WeaponDefense + private const uint FloatAttack = 62; // WeaponOffense + private const uint FloatDamageMod = 63; + private const uint FloatCritMultiplier = 136; + private const uint FloatManaConversion = 144; + private const uint FloatCritFrequency = 147; + private const uint FloatMissileDefense = 149; + private const uint FloatMagicDefense = 150; + private const uint FloatVsMonsters = 152; // ElementalDamageMod + private const uint FloatIgnoreArmor = 155; // armor cleaving + + // ── ACE PropertyString ids ─────────────────────────────────────────────── + private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids + + /// Gear ratings are small (1..~50). Anything above is a wrong key leaking through. + private const int MaxPlausibleRating = 200; + + /// Class-specific fields (ub-IT ItemIdentifyFieldSet). Generic fields print for every class. + [Flags] + private enum Field + { + None = 0, + DamageType = 1 << 0, + CritStats = 1 << 1, + Splits = 1 << 2, + Cleaves = 1 << 3, + Slayer = 1 << 4, + Range = 1 << 5, + Damage = 1 << 6, + AttackBonus = 1 << 7, + MeleeDefense = 1 << 8, + MissileDefense = 1 << 9, + MagicDefense = 1 << 10, + ManaConversion = 1 << 11, + ArmorCleave = 1 << 12, + WeaponDefenses = MeleeDefense | MissileDefense | MagicDefense, + } + + private static Field FieldsFor(AcObjectClass cls) => cls switch + { + AcObjectClass.MissileWeapon => Field.DamageType | Field.CritStats | Field.Splits | Field.Cleaves + | Field.Slayer | Field.Range | Field.Damage | Field.WeaponDefenses + | Field.ArmorCleave, + AcObjectClass.MeleeWeapon => Field.DamageType | Field.CritStats | Field.Cleaves | Field.Slayer + | Field.Damage | Field.AttackBonus | Field.WeaponDefenses + | Field.ArmorCleave, + AcObjectClass.WandStaffOrb => Field.DamageType | Field.CritStats | Field.Slayer | Field.Damage + | Field.WeaponDefenses | Field.ManaConversion, + AcObjectClass.Jewelry => Field.None, + // Armor / clothing / misc: keep Mag's generic bonus lines (shields roll %md etc.). + _ => Field.AttackBonus | Field.WeaponDefenses | Field.ManaConversion, + }; + + /// Full Mag-style line for one item (name first, comma-separated fields). + public static string Describe(IItemPropertySource item, MagItemInfoOptions options) + => Build(item, options).ToOneLine(); + + /// Reads every enabled field once, tagged by section (one-line or pet-style output). + public static MagItemDescription Build(IItemPropertySource item, MagItemInfoOptions options) + { + var d = new MagItemDescription(); + var sb = new StringBuilder(128); // title only + AcObjectClass cls = item.ObjectClass; + Field fields = FieldsFor(cls); + bool Has(Field f) => (fields & f) == f; + bool Show(MagItemInfoField f) => options.Shows(f); + + int Int(uint id) => item.TryGetInt(id, out int v) ? v : 0; + double Dbl(uint id, double fallback) => item.TryGetDouble(id, out double v) ? v : fallback; + + // ── Name: "[Material ]Name (DamageType Mastery)" ──────────────────────── + int material = Int(IntMaterial); + if (material > 0 && Show(MagItemInfoField.Material)) + { + string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}"; + // Loot names usually omit the material; don't double it when the name already starts with it. + if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase)) + sb.Append(matName).Append(' '); + } + sb.Append(item.Name); + + if (Has(Field.DamageType) && Show(MagItemInfoField.TypeMastery)) + { + string dmgType = MagItemInfoTables.DamageTypeName(Int(IntDamageType)); + int mastery = Int(IntWeaponType); + string masteryName = mastery > 0 + ? (MagItemInfoTables.Masteries.TryGetValue(mastery, out string? mn) ? mn : $"Unknown mastery {mastery}") + : string.Empty; + string inner = $"{dmgType} {masteryName}".Trim(); + if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')'); + } + d.Title = sb.ToString(); + + const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements; + string I(int v) => v.ToString(CultureInfo.InvariantCulture); + + // ── Set ───────────────────────────────────────────────────────────────── + int set = Int(IntEquipmentSet); + if (set > 0 && Show(MagItemInfoField.Set)) + d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}"); + + // ── Armor level ───────────────────────────────────────────────────────── + int al = Int(IntArmorLevel); + if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al)); + + // ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ───────── + if (Show(MagItemInfoField.Imbues)) + d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306))); + + if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0) + d.Add(Cbt, "AC"); + + if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats)) + { + double critMult = Dbl(FloatCritMultiplier, 0); + if (critMult > 0) d.Add(Cbt, $"CritMult ({Fmt(critMult)})"); + double critFreq = Dbl(FloatCritFrequency, 0); + if (critFreq > 0) d.Add(Cbt, $"CritFreq ({Fmt(critFreq)})"); + } + + if (Has(Field.Splits) && Show(MagItemInfoField.Splits)) + { + int splits = Int(IntSplitArrows); + if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})"); + } + + if (Has(Field.Range) && Show(MagItemInfoField.Range)) + { + int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0)); + if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd"); + } + + if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike)) + { + int attackType = Int(IntAttackType); + int mastery = Int(IntWeaponType); + bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0); + if (cleaving) d.Add(Cbt, "Cleaving"); + else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike"); + else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)"); + } + + // ── Slayer ────────────────────────────────────────────────────────────── + if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer)) + { + string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature)); + if (slayer != null) d.Add(Cbt, slayer + " Slayer"); + } + + // ── Tinks + applied materials (TinkerLog) ────────────────────────────── + int tinks = Int(IntTinks); + if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks)); + if (Show(MagItemInfoField.Applied)) + { + string applied = FormatTinkerLog(item.GetString(StringTinkerLog)); + if (applied.Length > 0) d.Add(Id, "Applied: " + applied); + } + + // ── Damage ────────────────────────────────────────────────────────────── + if (Has(Field.Damage) && Show(MagItemInfoField.Damage)) + AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus), + Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1)); + + // ── Attack / defense / mana conversion percents ─────────────────────── + bool defenses = Show(MagItemInfoField.Defenses); + if (Has(Field.AttackBonus) && Show(MagItemInfoField.Attack)) AddPercent(d, Dbl(FloatAttack, 1), "%a", 0); + if (Has(Field.MeleeDefense) && defenses) AddPercent(d, Dbl(FloatMeleeDefense, 1), "%md", 0); + if (Has(Field.MagicDefense) && defenses) AddPercent(d, Dbl(FloatMagicDefense, 1), "%mgc.d", 1); + if (Has(Field.MissileDefense) && defenses) AddPercent(d, Dbl(FloatMissileDefense, 1), "%msl.d", 1); + if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion)) + { + double mc = Dbl(FloatManaConversion, 0); + if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc"); + } + + // ── Spells ────────────────────────────────────────────────────────────── + bool unenchantable = Int(IntResistMagic) >= 9999; + if (Show(MagItemInfoField.Spells)) + AddSpells(d, item.SpellIds, unenchantable, options.AllSpells, options.MaxListedSpells); + + // ── Requirements ──────────────────────────────────────────────────────── + if (Show(MagItemInfoField.Wield)) + { + AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue)); + AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2)); + } + + if (Show(MagItemInfoField.Activation)) + { + int useLevel = Int(IntUseRequiresLevel); + if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel)); + + // "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it. + int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel); + if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel)) + d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate"); + + // Summoning essences / gems. + int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec); + if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}"); + if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}"); + } + + int diff = Int(IntItemDifficulty); + if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff)); + + // ── Workmanship ───────────────────────────────────────────────────────── + int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0; + if (cls == AcObjectClass.Salvage) + { + int items = Int(IntNumItemsInMaterial); + if (work > 0) + { + double avg = items > 0 ? (double)work / items : work; + d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture)); + } + } + else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked + { + d.Add(Id, "Craft " + I(work)); + } + + // ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ───────────── + if (cls == AcObjectClass.Armor && unenchantable && Show(MagItemInfoField.Protections)) + { + var prot = new StringBuilder("["); + for (uint i = 0; i < 7; i++) + { + if (i > 0) prot.Append('/'); + prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture)); + } + d.Add(Cbt, prot.Append(']').ToString()); + } + + if (options.ShowValueAndBurden) + { + int value = Int(IntValue); + if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture)); + int burden = Int(IntBurden); + if (burden > 0) d.Add(Req, "BU " + I(burden)); + } + + // ── Ratings ───────────────────────────────────────────────────────────── + if (Show(MagItemInfoField.Ratings)) + d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings)); + + if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring) + && item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase)) + { + d.Add(Id, "Keys: " + I(Int(IntNumKeys))); + d.Add(Id, "Uses: " + I(Int(IntStructure))); + } + + return d; + } + + /// Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether + /// rend); empty when no known bit is set. + private static string ImbueLabels(int mask) + { + if (mask == 0) return string.Empty; + var sb = new StringBuilder(); + void Flag(int bit, string label) + { + if ((mask & bit) == 0) return; + if (sb.Length > 0) sb.Append(' '); + sb.Append(label); + } + Flag(0x0001, "CS"); + Flag(0x0002, "CB"); + Flag(0x0004, "AR"); + Flag(0x0008, "SlashRend"); + Flag(0x0010, "PierceRend"); + Flag(0x0020, "BludgeRend"); + Flag(0x0040, "AcidRend"); + Flag(0x0080, "FrostRend"); + Flag(0x0100, "LightRend"); + Flag(0x0200, "FireRend"); + Flag(0x4000, "NetherRend"); + Flag(0x0400, "MeleeImbue"); + Flag(0x0800, "MissileImbue"); + Flag(0x1000, "MagicImbue"); + Flag(0x2000, "Hematited"); + Flag(0x20000000, "MagicAbsorb"); + return sb.ToString(); // only unknown bits → empty → field skipped + } + + /// Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line). + private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance, + int elemBonus, double dmgMod, double vsMonsters) + { + const MagItemSection Cbt = MagItemSection.Combat; + if (cls != AcObjectClass.MissileWeapon && maxDmg > 0) + { + string max = maxDmg.ToString(CultureInfo.InvariantCulture); + d.Add(Cbt, variance > 0 + ? (maxDmg - maxDmg * variance).ToString("N2", CultureInfo.InvariantCulture) + "-" + max + : max); + } + if (variance > 0) + d.Add(Cbt, Math.Round(variance, 2).ToString(CultureInfo.InvariantCulture) + "v"); + if (elemBonus != 0) + d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture)); + // A missing/zero multiplier means "no bonus" (0 would print as -100%). + if (dmgMod > 0 && dmgMod != 1) + d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%"); + if (vsMonsters > 0 && vsMonsters != 1) + d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters"); + } + + /// Mag "18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0. + private static void AddPercent(MagItemDescription d, double multiplier, string suffix, int decimals) + { + if (multiplier <= 0 || multiplier == 1) return; + double pct = Math.Round((multiplier - 1) * 100, decimals); + d.Add(MagItemSection.Combat, pct.ToString(CultureInfo.InvariantCulture) + suffix); + } + + /// "Wield Lvl 180" for a level requirement, else "Heavy Weapons 375". + private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value) + { + if (value <= 0) return; + string v = value.ToString(CultureInfo.InvariantCulture); + d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level + ? "Wield Lvl " + v + : SkillName(skillOrAttr) + " " + v); + } + + private static string SkillName(int skill) => + MagItemInfoTables.Skills.TryGetValue(skill, out string? name) ? name : $"Skill {skill}"; + + /// + /// Mag-Tools spell filter (ub-IT applies it to every item): keep cantrip Impen, Augmented + /// (trinket) spells, banes/Impen only on unenchantable gear, level 7+ weapon auras, and + /// named high-tier spells (cantrips); drop I–VI, level-7 lore buffs and Incantations. + /// Verbose lists every spell (capped) for troubleshooting. + /// + private static void AddSpells(MagItemDescription d, IReadOnlyList spellIds, bool unenchantable, + bool verbose, int maxVerbose) + { + if (spellIds.Count == 0) return; + var ids = new List(spellIds); + ids.Sort(); + ids.Reverse(); // Mag lists highest spell id first + + var seen = new HashSet(); + var verboseList = verbose ? new StringBuilder() : null; + int shown = 0, skippedVerbose = 0; + foreach (int id in ids) + { + if (!seen.Add(id)) continue; + bool known = SpellDatabase.HasSpell(id); + if (verboseList != null) + { + // Verbose is the troubleshooting view: list ids SpellData.txt doesn't know too. + if (shown >= maxVerbose) { skippedVerbose++; continue; } + verboseList.Append(shown == 0 ? "Spells: " : "; ") + .Append(known ? SpellDatabase.GetSpellName(id) : $"Spell {id}"); + shown++; + continue; + } + if (!known) continue; + string name = SpellDatabase.GetSpellName(id); + SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty); + if (ShouldShowSpell(name, family, difficulty, unenchantable)) + d.Add(MagItemSection.Spells, name); + } + if (verboseList == null || verboseList.Length == 0) return; + if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)"); + d.Add(MagItemSection.Spells, verboseList.ToString()); + } + + private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable) + { + if (name.Contains("Minor Impenetrability") || name.Contains("Major Impenetrability") + || name.Contains("Epic Impenetrability") || name.Contains("Legendary Impenetrability")) + return true; + if (name.Contains("Augmented")) + return true; + + // Banes / Impen / Brogard's: only meaningful on unenchantable gear (loot armor + // already reflects them in AL and protections). + bool baneLike = name.Contains(" Bane") || name.Contains("Impen") || name.StartsWith("Brogard", StringComparison.Ordinal); + if (baneLike) return unenchantable; + + // Weapon auras (Elysa's Sight .. Swift Killer, Hermetic Link, Vision of the Hunter): + // level 7 (300) and 8+ (400+) only. + if ((family >= 152 && family <= 158) || family == 195 || family == 325) + return difficulty == 300 || difficulty >= 400; + + if (name.EndsWith(" I") || name.EndsWith(" II") || name.EndsWith(" III") + || name.EndsWith(" IV") || name.EndsWith(" V") || name.EndsWith(" VI")) + return false; + if (difficulty == 300) return false; // level-7 lore buffs (Might of the Lugians …) + if (name.Contains("Incantation")) return false; + return true; // cantrips: Legendary Strength, Epic Defender … + } + + /// Rating cluster "[D 11, C 8, CD 4]" from ACE Gear* ratings 370–389 + /// (); bit i of skips rating i. + private static string RatingsCluster(IItemPropertySource item, int hiddenMask) + { + var sb = new StringBuilder(); + var ratings = MagItemInfoCatalog.Ratings; + for (int i = 0; i < ratings.Length; i++) + { + if ((hiddenMask & (1 << i)) != 0) continue; + if (!item.TryGetInt(ratings[i].StatId, out int v) || v <= 0 || v > MaxPlausibleRating) continue; + sb.Append(sb.Length == 0 ? "[" : ", ").Append(ratings[i].Tag).Append(' ') + .Append(v.ToString(CultureInfo.InvariantCulture)); + } + return sb.Length > 0 ? sb.Append(']').ToString() : string.Empty; + } + + /// ACECustom TinkerLog CSV ("64,64,46") → "Steel x2, White Quartz". + private static string FormatTinkerLog(string csv) + { + if (string.IsNullOrWhiteSpace(csv)) return string.Empty; + var order = new List(); + var counts = new Dictionary(); + foreach (string raw in csv.Split(',')) + { + if (!int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) || id <= 0) + continue; + if (counts.TryGetValue(id, out int c)) counts[id] = c + 1; + else { counts[id] = 1; order.Add(id); } + } + var sb = new StringBuilder(); + foreach (int id in order) + { + if (sb.Length > 0) sb.Append(", "); + sb.Append(MagItemInfoTables.Materials.TryGetValue(id, out string? name) ? name : $"material {id}"); + if (counts[id] > 1) sb.Append(" x").Append(counts[id]); + } + return sb.ToString(); + } + + /// Max ballistic range (45° arc, v²/g) in yards; 0 when velocity is missing. + private static int MissileRangeYards(double velocity) + { + if (double.IsNaN(velocity) || velocity <= 0) return 0; + double meters = velocity * velocity / 9.8; + return (int)Math.Round(meters * 1.0936133); + } + + private static string Fmt(double v) => Math.Round(v, 2).ToString(CultureInfo.InvariantCulture); +} + +/// over the live client object (RynthCore host reads). +internal sealed class CacheItemPropertySource : IItemPropertySource +{ + private readonly RynthCore.PluginSdk.RynthCoreHost _host; + private readonly uint _id; + private IReadOnlyList? _spells; + + public CacheItemPropertySource(RynthCore.PluginSdk.RynthCoreHost host, WorldObject wo) + { + _host = host; + _id = unchecked((uint)wo.Id); + Name = wo.Name; + ObjectClass = wo.ObjectClass; + } + + public string Name { get; } + public AcObjectClass ObjectClass { get; } + + public bool TryGetInt(uint stype, out int value) + { + value = 0; + return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, stype, out value); + } + + public bool TryGetDouble(uint stype, out double value) + { + value = 0; + return _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(_id, stype, out value); + } + + public string GetString(uint stype) => + _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(_id, stype, out string? v) && v != null + ? v + : string.Empty; + + public IReadOnlyList SpellIds => _spells ??= ReadSpells(); + + private IReadOnlyList ReadSpells() + { + if (!_host.HasGetObjectSpellIds) return Array.Empty(); + uint[] buf = new uint[128]; + int n = _host.GetObjectSpellIds(_id, buf, buf.Length); + if (n <= 0) return Array.Empty(); + int take = Math.Min(n, buf.Length); + var list = new List(take); + for (int i = 0; i < take; i++) list.Add(unchecked((int)buf[i])); + return list; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs new file mode 100644 index 0000000..dc2aae7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoSettings.cs @@ -0,0 +1,251 @@ +// MagItemInfoSettings.cs — user options for the Mag-style item info line (/ra iteminfo). +// +// Stored per character inside LegacyUiSettings.ItemInfoSettings. Field visibility is kept as a +// *hidden* bitmask so any field added in a later release shows by default for existing profiles. +using System; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +/// Toggleable sections of the item info line (bit set in HiddenFields = not printed). +[Flags] +public enum MagItemInfoField +{ + None = 0, + Material = 1 << 0, + TypeMastery = 1 << 1, + Set = 1 << 2, + ArmorLevel = 1 << 3, + Imbues = 1 << 4, + ArmorCleave = 1 << 5, + CritStats = 1 << 6, + Splits = 1 << 7, + Range = 1 << 8, + CleaveMultiStrike = 1 << 9, + Slayer = 1 << 10, + Tinks = 1 << 11, + Applied = 1 << 12, + Damage = 1 << 13, + Attack = 1 << 14, + Defenses = 1 << 15, + ManaConversion = 1 << 16, + Spells = 1 << 17, + Wield = 1 << 18, + Activation = 1 << 19, + Difficulty = 1 << 20, + Craft = 1 << 21, + Protections = 1 << 22, + Ratings = 1 << 23, + Keyring = 1 << 24, +} + +/// Persisted item-info options (JSON fields; see RynthAiJsonContext IncludeFields). +public sealed class MagItemInfoSettings +{ + /// Spell list modes for . + public const int SpellModeMag = 0, SpellModeAll = 1; + /// Mouse triggers for . + public const int ClickOff = 0, ClickLeft = 1, ClickRight = 2; + /// Output layouts for . + public const int LayoutOneLine = 0, LayoutPetLines = 1; + /// value meaning "use ". + public const int SameAsHeader = -1; + + // ── When to print ──────────────────────────────────────────────────────── + /// Print automatically when an item is selected. + public bool OnSelect; + /// + /// Print the selected item after a left () or right () + /// click in the game world / inventory — also re-prints an item that was already selected. + /// + public int ClickTrigger = ClickOff; + /// On-select class filters (manual /ra iteminfo ignores them). + public bool OnSelectWeapons = true; + public bool OnSelectArmor = true; + public bool OnSelectJewelry = true; + public bool OnSelectOther = true; + /// Seconds to wait for an ID before printing partial data. + public float IdTimeoutSec = 3f; + + // ── What to print ──────────────────────────────────────────────────────── + /// bits that are NOT printed. + public int HiddenFields; + /// Bit i set = [i] not printed. + public int HiddenRatings; + /// Append ", Value N, BU N". + public bool ShowValueAndBurden; + /// (Mag filter) or . + public int SpellMode = SpellModeMag; + /// Cap for the "all spells" list. + public int MaxListedSpells = 26; + + // ── How to print ───────────────────────────────────────────────────────── + /// (pet-roster style lines) or (Mag one-liner). + public int Layout = LayoutPetLines; + /// AC chat type passed to WriteToChat (selects the chat colour / window). + public int ChatType = 1; + /// Chat type for pet-style lines 2+, or . + public int DetailChatType = SameAsHeader; + /// Text put in front of every line. + public string Prefix = "[RynthAi] "; + + /// Item Info settings window open. + public bool ShowWindow; + + public bool IsHidden(MagItemInfoField f) => (HiddenFields & (int)f) != 0; + + public void SetHidden(MagItemInfoField f, bool hidden) => + HiddenFields = hidden ? HiddenFields | (int)f : HiddenFields & ~(int)f; + + public bool IsRatingHidden(int index) => (HiddenRatings & (1 << index)) != 0; + + public void SetRatingHidden(int index, bool hidden) => + HiddenRatings = hidden ? HiddenRatings | (1 << index) : HiddenRatings & ~(1 << index); + + /// Clamp values a hand-edited or older profile could carry out of range. + public void Sanitize() + { + if (float.IsNaN(IdTimeoutSec) || IdTimeoutSec < 0.5f) IdTimeoutSec = 0.5f; + if (IdTimeoutSec > 15f) IdTimeoutSec = 15f; + if (SpellMode is not (SpellModeMag or SpellModeAll)) SpellMode = SpellModeMag; + MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64); + if (ChatType < 0 || ChatType > 31) ChatType = 1; + if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader; + if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff; + if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines; + Prefix ??= string.Empty; + if (Prefix.Length > 32) Prefix = Prefix[..32]; + } + + /// Back to first-run defaults (window stays open). + public void ResetToDefaults() + { + var d = new MagItemInfoSettings(); + OnSelect = d.OnSelect; + ClickTrigger = d.ClickTrigger; + Layout = d.Layout; + DetailChatType = d.DetailChatType; + OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor; + OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther; + IdTimeoutSec = d.IdTimeoutSec; + HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings; + ShowValueAndBurden = d.ShowValueAndBurden; + SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells; + ChatType = d.ChatType; Prefix = d.Prefix; + } +} + +/// Labels for the settings window and the /ra iteminfo field|rating commands. +public static class MagItemInfoCatalog +{ + public readonly record struct FieldInfo(MagItemInfoField Field, string Label, string Example); + public readonly record struct RatingInfo(uint StatId, string Tag, string Name); + + /// In print order. + public static readonly FieldInfo[] Fields = + { + new(MagItemInfoField.Material, "Material", "Gold Ornate Long Sword"), + new(MagItemInfoField.TypeMastery, "Damage type / mastery","(Slash Sword)"), + new(MagItemInfoField.Set, "Equipment set", "Noble Relic Set"), + new(MagItemInfoField.ArmorLevel, "Armor level", "AL 650"), + new(MagItemInfoField.Imbues, "Imbues", "CS, AR, FireRend"), + new(MagItemInfoField.ArmorCleave, "Armor cleaving", "AC"), + new(MagItemInfoField.CritStats, "Crit mult / freq", "CritMult (1.5), CritFreq (0.15)"), + new(MagItemInfoField.Splits, "Split arrows", "Splits (2)"), + new(MagItemInfoField.Range, "Missile range", "Range 120yd"), + new(MagItemInfoField.CleaveMultiStrike, "Cleaving / Multi-Strike", "Cleaving"), + new(MagItemInfoField.Slayer, "Slayer", "Undead Slayer"), + new(MagItemInfoField.Tinks, "Tinks", "Tinks 4"), + new(MagItemInfoField.Applied, "Applied materials", "Applied: Steel x2"), + new(MagItemInfoField.Damage, "Damage", "152.48-236, 0.35v, +18, +10%"), + new(MagItemInfoField.Attack, "Attack bonus", "+18%a"), + new(MagItemInfoField.Defenses, "Defense bonuses", "12%md, 1.5%mgc.d, 1%msl.d"), + new(MagItemInfoField.ManaConversion, "Mana conversion", "6%mc"), + new(MagItemInfoField.Spells, "Spells", "Legendary Blood Thirst"), + new(MagItemInfoField.Wield, "Wield requirements", "Wield Lvl 180, Heavy Weapons 375"), + new(MagItemInfoField.Activation, "Activation / use reqs","Lvl 50, Melee Defense 300 to Activate"), + new(MagItemInfoField.Difficulty, "Arcane difficulty", "Diff 270"), + new(MagItemInfoField.Craft, "Craft / salvage work", "Craft 8"), + new(MagItemInfoField.Protections, "Protections (unenchantable armor)", "[1.0/0.8/1.2/...]"), + new(MagItemInfoField.Ratings, "Ratings", "[D 3, CD 2]"), + new(MagItemInfoField.Keyring, "Keyring keys / uses", "Keys: 3, Uses: 25"), + }; + + /// ACE gear ratings (PropertyInt 370–389) in Mag print order. + public static readonly RatingInfo[] Ratings = + { + new(370, "D", "Damage"), + new(371, "DR", "Damage Resist"), + new(372, "C", "Crit"), + new(374, "CD", "Crit Damage"), + new(373, "CR", "Crit Resist"), + new(375, "CDR", "Crit Damage Resist"), + new(376, "HB", "Healing Boost"), + new(379, "V", "Vitality"), + new(377, "NR", "Nether Resist"), + new(378, "LR", "Life Resist"), + new(383, "PKD", "PK Damage"), + new(384, "PKDR", "PK Damage Resist"), + new(388, "OP", "Overpower"), + new(389, "OPR", "Overpower Resist"), + }; + + /// Labels for , indexed by value. + public static readonly string[] ClickTriggers = { "Off", "Left mouse click", "Right mouse click" }; + + /// Labels for , indexed by value. + public static readonly string[] Layouts = { "One line (Mag-Tools)", "Pet-style lines" }; + + /// Common AC chat types for the colour picker (value passed to WriteToChat). + public static readonly (int Type, string Label)[] ChatTypes = + { + (0, "0 - Broadcast"), + (1, "1 - RynthAi default"), + (2, "2 - Speech"), + (3, "3 - Tell"), + (4, "4 - Outgoing tell"), + (5, "5 - System"), + (6, "6 - Combat"), + (7, "7 - Magic"), + (8, "8 - Channels"), + (10, "10 - Social"), + (12, "12 - Emote"), + (13, "13 - Advancement"), + (15, "15 - Help"), + (16, "16 - Appraisal"), + (17, "17 - Spellcasting"), + (18, "18 - Allegiance"), + (19, "19 - Fellowship"), + (21, "21 - Combat (enemy)"), + (22, "22 - Combat (self)"), + (24, "24 - Craft"), + (25, "25 - Salvaging"), + }; + + /// Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery"). + public static bool TryFindField(string key, out MagItemInfoField field) + { + foreach (var f in Fields) + { + if (f.Field.ToString().Equals(key, StringComparison.OrdinalIgnoreCase) + || f.Label.Replace(" ", string.Empty).StartsWith(key, StringComparison.OrdinalIgnoreCase)) + { + field = f.Field; + return true; + } + } + field = MagItemInfoField.None; + return false; + } + + /// Rating index by tag ("CD") or name ("critdamage"), case-insensitive. + public static int FindRating(string key) + { + for (int i = 0; i < Ratings.Length; i++) + { + if (Ratings[i].Tag.Equals(key, StringComparison.OrdinalIgnoreCase) + || Ratings[i].Name.Replace(" ", string.Empty).Equals(key, StringComparison.OrdinalIgnoreCase)) + return i; + } + return -1; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoTables.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoTables.cs new file mode 100644 index 0000000..d90564a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemInfo/MagItemInfoTables.cs @@ -0,0 +1,159 @@ +// MagItemInfoTables.cs — name tables for the Mag-style item info line (MagItemDescriber). +// Skill / mastery / set / material names follow UtilityBelt ub-IT (Lib/ItemInfoHelper/Dictionaries.cs, +// itself from Mag-Tools / Alinco / VTank). Slayer names use the full ACE CreatureType enum instead of +// ub-IT's 17-entry subset so every slayer resolves. +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthAi.ItemInfo; + +internal static class MagItemInfoTables +{ + /// Skill id → name (wield / activation / summoning requirements). + public static readonly Dictionary Skills = new() + { + { 0x01, "Axe" }, { 0x02, "Bow" }, { 0x03, "Crossbow" }, { 0x04, "Dagger" }, { 0x05, "Mace" }, + { 0x06, "Melee Defense" }, { 0x07, "Missile Defense" }, { 0x08, "Sling" }, { 0x09, "Spear" }, + { 0x0A, "Staff" }, { 0x0B, "Sword" }, { 0x0C, "Thrown Weapons" }, { 0x0D, "Unarmed Combat" }, + { 0x0E, "Arcane Lore" }, { 0x0F, "Magic Defense" }, { 0x10, "Mana Conversion" }, + { 0x12, "Item Tinkering" }, { 0x13, "Assess Person" }, { 0x14, "Deception" }, { 0x15, "Healing" }, + { 0x16, "Jump" }, { 0x17, "Lockpick" }, { 0x18, "Run" }, { 0x1B, "Assess Creature" }, + { 0x1C, "Weapon Tinkering" }, { 0x1D, "Armor Tinkering" }, { 0x1E, "Magic Item Tinkering" }, + { 0x1F, "Creature Enchantment" }, { 0x20, "Item Enchantment" }, { 0x21, "Life Magic" }, + { 0x22, "War Magic" }, { 0x23, "Leadership" }, { 0x24, "Loyalty" }, { 0x25, "Fletching" }, + { 0x26, "Alchemy" }, { 0x27, "Cooking" }, { 0x28, "Salvaging" }, { 0x29, "Two Handed Combat" }, + { 0x2A, "Gearcraft" }, { 0x2B, "Void" }, { 0x2C, "Heavy Weapons" }, { 0x2D, "Light Weapons" }, + { 0x2E, "Finesse Weapons" }, { 0x2F, "Missile Weapons" }, { 0x30, "Shield" }, { 0x31, "Dual Wield" }, + { 0x32, "Recklessness" }, { 0x33, "Sneak Attack" }, { 0x34, "Dirty Fighting" }, { 0x35, "Challenge" }, + { 0x36, "Summoning" }, + }; + + /// ACE PropertyInt.WeaponType (353) → mastery name. + public static readonly Dictionary Masteries = new() + { + { 1, "Unarmed Weapon" }, { 2, "Sword" }, { 3, "Axe" }, { 4, "Mace" }, { 5, "Spear" }, { 6, "Dagger" }, + { 7, "Staff" }, { 8, "Bow" }, { 9, "Crossbow" }, { 10, "Thrown" }, { 11, "Two Handed Combat" }, { 12, "Wand" }, + }; + + /// ACE PropertyInt.MaterialType (131) → material name. + public static readonly Dictionary Materials = new() + { + { 1, "Ceramic" }, { 2, "Porcelain" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" }, { 7, "Velvet" }, + { 8, "Wool" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" }, { 13, "Aquamarine" }, + { 14, "Azurite" }, { 15, "Bag of Abyssal-Touched" }, { 16, "Black Opal" }, { 17, "Bloodstone" }, + { 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" }, + { 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" }, + { 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" }, + { 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" }, + { 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smokey Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" }, + { 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" }, + { 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" }, + { 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" }, + { 55, "Reed Shark Hide" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" }, + { 61, "Iron" }, { 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 66, "Alabaster" }, + { 67, "Granite" }, { 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" }, + { 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" }, + }; + + /// ACE PropertyInt.EquipmentSetId (265) → set name. + public static readonly Dictionary EquipmentSets = BuildSets(); + + /// ACE CreatureType enum, index = value (0..101). Used for SlayerCreatureType (166). + private static readonly string[] CreatureTypes = + { + "Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker", + "Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo", + "Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus", + "Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman", + "Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny", + "Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion", + "Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun", + "Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental", + "Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken", + "Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", "Target", + "Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", "Remoran", "Swarm", + "Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", "Paradox Olthoi", "Harvest", + "Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", "Gear Knight", "Gurog", "A'nekshay", + }; + + /// Slayer creature name, or null for 0 / unknown values. + public static string? CreatureTypeName(int value) => + value > 0 && value < CreatureTypes.Length ? CreatureTypes[value] : null; + + /// + /// ACE DamageType flags (45) → "Slash", "Slash/Pierce", "Lightning" … Empty when no known bit is set. + /// + public static string DamageTypeName(int flags) + { + if (flags <= 0) return string.Empty; + var sb = new StringBuilder(); + void Add(int bit, string name) + { + if ((flags & bit) == 0) return; + if (sb.Length > 0) sb.Append('/'); + sb.Append(name); + } + Add(0x001, "Slash"); + Add(0x002, "Pierce"); + Add(0x004, "Bludgeon"); + Add(0x008, "Cold"); + Add(0x010, "Fire"); + Add(0x020, "Acid"); + Add(0x040, "Lightning"); + Add(0x400, "Nether"); + return sb.ToString(); + } + + private static Dictionary BuildSets() + { + var d = new Dictionary + { + { 2, "Test" }, { 4, "Carraida's Benediction" }, { 5, "Noble Relic Set" }, { 6, "Ancient Relic Set" }, + { 7, "Relic Alduressa Set" }, { 8, "Shou-jen Set" }, { 9, "Empyrean Rings Set" }, + { 10, "Arm, Mind, Heart Set" }, { 11, "Coat of the Perfect Light Set" }, + { 12, "Leggings of Perfect Light Set" }, { 13, "Soldier's Set" }, { 14, "Adept's Set" }, + { 15, "Archer's Set" }, { 16, "Defender's Set" }, { 17, "Tinker's Set" }, { 18, "Crafter's Set" }, + { 19, "Hearty Set" }, { 20, "Dexterous Set" }, { 21, "Wise Set" }, { 22, "Swift Set" }, + { 23, "Hardened Set" }, { 24, "Reinforced Set" }, { 25, "Interlocking Set" }, + { 26, "Flame Proof Set" }, { 27, "Acid Proof Set" }, { 28, "Cold Proof Set" }, + { 29, "Lightning Proof Set" }, { 30, "Dedication Set" }, { 31, "Gladiatorial Clothing Set" }, + { 32, "Ceremonial Clothing" }, { 33, "Protective Clothing" }, { 34, "Noobie Armor" }, + { 35, "Sigil of Defense" }, { 36, "Sigil of Destruction" }, { 37, "Sigil of Fury" }, + { 38, "Sigil of Growth" }, { 39, "Sigil of Vigor" }, { 40, "Heroic Protector Set" }, + { 41, "Heroic Destroyer Set" }, { 42, "Olthoi Armor D Red" }, { 43, "Olthoi Armor C Rat" }, + { 44, "Olthoi Armor C Red" }, { 45, "Olthoi Armor D Rat" }, { 46, "Upgraded Relic Alduressa Set" }, + { 47, "Upgraded Ancient Relic Set" }, { 48, "Upgraded Noble Relic Set" }, + { 49, "Weave of Alchemy" }, { 50, "Weave of Arcane Lore" }, { 51, "Weave of Armor Tinkering" }, + { 52, "Weave of Assess Person" }, { 53, "Weave of Light Weapons" }, { 54, "Weave of Missile Weapons" }, + { 55, "Weave of Cooking" }, { 56, "Weave of Creature Enchantment" }, { 57, "Weave of Missile Weapons" }, + { 58, "Weave of Finesse" }, { 59, "Weave of Deception" }, { 60, "Weave of Fletching" }, + { 61, "Weave of Healing" }, { 62, "Weave of Item Enchantment" }, { 63, "Weave of Item Tinkering" }, + { 64, "Weave of Leadership" }, { 65, "Weave of Life Magic" }, { 66, "Weave of Loyalty" }, + { 67, "Weave of Light Weapons" }, { 68, "Weave of Magic Defense" }, + { 69, "Weave of Magic Item Tinkering" }, { 70, "Weave of Mana Conversion" }, + { 71, "Weave of Melee Defense" }, { 72, "Weave of Missile Defense" }, { 73, "Weave of Salvaging" }, + { 74, "Weave of Light Weapons" }, { 75, "Weave of Light Weapons" }, { 76, "Weave of Heavy Weapons" }, + { 77, "Weave of Missile Weapons" }, { 78, "Weave of Two Handed Combat" }, { 79, "Weave of Light Weapons" }, + { 80, "Weave of Void Magic" }, { 81, "Weave of War Magic" }, { 82, "Weave of Weapon Tinkering" }, + { 83, "Weave of Assess Creature" }, { 84, "Weave of Dirty Fighting" }, { 85, "Weave of Dual Wield" }, + { 86, "Weave of Recklessness" }, { 87, "Weave of Shield" }, { 88, "Weave of Sneak Attack" }, + { 89, "Ninja_New" }, { 90, "Weave of Summoning" }, { 91, "Shrouded Soul" }, { 92, "Darkened Mind" }, + { 93, "Clouded Spirit" }, { 130, "Shimmering Shadows" }, { 131, "Brown Society Locket" }, + { 132, "Yellow Society Locket" }, { 133, "Red Society Band" }, { 134, "Green Society Band" }, + { 135, "Purple Society Band" }, { 136, "Blue Society Band" }, { 137, "Gauntlet Garb" }, + { 138, "Paragon" }, { 139, "Paragon" }, { 140, "Paragon" }, + }; + + // 94..129: Minor / Major / Blackfire × Stinging / Sparking / Smoldering / Shivering × + // Shrouded Soul / Darkened Mind / Clouded Spirit (same order as the VTank set list). + string[] tiers = { "Minor", "Major", "Blackfire" }; + string[] souls = { "Shrouded Soul", "Darkened Mind", "Clouded Spirit" }; + string[] elements = { "Stinging", "Sparking", "Smoldering", "Shivering" }; + int id = 94; + foreach (string tier in tiers) + foreach (string soul in souls) + foreach (string element in elements) + d[id++] = $"{tier} {element} {soul}"; + return d; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs index 22ece09..3e6a1e8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs @@ -89,11 +89,11 @@ internal sealed class Jumper _turningStartedAt = DateTime.UtcNow; if (_host.HasTurnToHeading) _host.TurnToHeadingBy("Jump", _targetHeading); - _host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms"); + RynthLog.Write(LogCat.Jumper, $"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms"); } else { - _host.Log($"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms"); + RynthLog.Write(LogCat.Jumper, $"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms"); } return true; } @@ -118,7 +118,7 @@ internal sealed class Jumper { _isTurning = false; if (_host.TryGetPlayerHeading(out float current)) - _host.Log($"[Jumper] Turn done heading={current:F1}"); + RynthLog.Write(LogCat.Jumper, $"[Jumper] Turn done heading={current:F1}"); } if (_needToJump && !_isTurning) @@ -141,12 +141,12 @@ internal sealed class Jumper RestoreNav(); _waitingForJump = false; _addW = _addX = _addZ = _addC = _addShift = false; - _host.Log("[Jumper] Settle complete -> idle"); + RynthLog.Write(LogCat.Jumper, "[Jumper] Settle complete -> idle"); } } catch (Exception ex) { - _host.Log($"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}"); + RynthLog.Write(LogCat.Jumper, $"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}"); Cancel(); } } @@ -166,7 +166,7 @@ internal sealed class Jumper started = _host.CommenceJump(); _charging = started; _chargeStartedAt = DateTime.UtcNow; - _host.Log($"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " + + RynthLog.Write(LogCat.Jumper, $"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " + $"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}"); } else @@ -174,7 +174,7 @@ internal sealed class Jumper started = _host.HasTapJump && _host.TapJump(); _waitingForJump = started; _jumpStartedAt = DateTime.UtcNow; - _host.Log($"[Jumper] TapJump fallback ok={started} " + + RynthLog.Write(LogCat.Jumper, $"[Jumper] TapJump fallback ok={started} " + $"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}"); } @@ -200,13 +200,13 @@ internal sealed class Jumper if (_host.HasLaunchJumpWithMotion) { released = _host.LaunchJumpWithMotion(_addShift, _addW, _addX, _addZ, _addC); - _host.Log($"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " + + RynthLog.Write(LogCat.Jumper, $"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " + $"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}"); } else { released = _host.HasDoJump && _host.DoJump(true); - _host.Log($"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms"); + RynthLog.Write(LogCat.Jumper, $"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms"); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.LocalFeatures.cs new file mode 100644 index 0000000..54bd732 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.LocalFeatures.cs @@ -0,0 +1,27 @@ +// LegacyDashboardRenderer.LocalFeatures.cs — style shared with the plugin's own ImGui windows +// (ILT Hub, floating HUDs, chat translator). +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +internal sealed partial class LegacyDashboardRenderer +{ + /// Pushes RynthAi's window colours; returns the count for PopStyleColor. + internal static int PushDashboardStyle() + { + // Muted slate-blue accents. TitleBgActive replaces ImGui's default yellow on detached windows. + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.18f, 0.22f, 0.28f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.24f, 0.30f, 0.38f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.30f, 0.38f, 0.48f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.85f, 0.90f, 1.00f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.PopupBg, new Vector4(0.10f, 0.14f, 0.20f, 0.98f)); + ImGui.PushStyleColor(ImGuiCol.Header, new Vector4(0.20f, 0.28f, 0.36f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderHovered, new Vector4(0.26f, 0.36f, 0.46f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderActive, new Vector4(0.32f, 0.44f, 0.58f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBg, new Vector4(0.14f, 0.18f, 0.24f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.22f, 0.30f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgCollapsed, new Vector4(0.10f, 0.14f, 0.20f, 0.85f)); + return 11; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs new file mode 100644 index 0000000..be4ea07 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs @@ -0,0 +1,224 @@ +// LegacyDashboardRenderer.NavEdit.cs — route editor commands from the engine Nav panel: +// multi-select move / duplicate / delete, set active, move a step to the player, nearest, +// reverse, snap to path, pause / portal / point-at-selection steps, simplify, recording and +// trail -> route. +// +// Commands arrive with indices into the route the panel last saw. Structural edits go +// through NavRouteEditing.Apply (copy-on-write) so the nav engine never sees a half-edited list. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +internal sealed partial class LegacyDashboardRenderer +{ + /// How long an edit's result stays in the Nav panel's status line. + private const long NavEditStatusMs = 8_000; + + /// Spot closer than this to an existing waypoint is refused by "Snap to path", yards. + private const double SnapMinGapYards = 0.5; + + /// Decal ObjectClass.Portal, as VTank writes it in Portal steps. + private const int PortalObjectClass = 14; + + private string _navEditStatus = string.Empty; + private long _navEditStatusAt; + + /// Breadcrumb trail (set by the plugin once the nav overlay exists; null before login). + internal NavBreadcrumbTracker? NavBreadcrumbs { get; set; } + + private List RoutePoints => _settings.CurrentRoute.Points; + + /// The last edit's result while it is fresh, else empty. + private string CurrentNavEditStatus() => + _navEditStatus.Length > 0 && Environment.TickCount64 - _navEditStatusAt < NavEditStatusMs ? _navEditStatus : string.Empty; + + private void SetNavEditStatus(string text) + { + _navEditStatus = text; + _navEditStatusAt = Environment.TickCount64; + RynthLog.Trace(LogCat.Navigation, "[NavEdit] " + text); + } + + private void HandleNavEditCommand(NavCommand cmd) + { + switch (cmd.Cmd) + { + case "movePoints": + { + var sel = PointsAt(cmd.Indices); + if (sel.Count == 0 || cmd.Delta == 0) return; + EditRoute(l => NavRouteEditing.Move(l, sel, Math.Sign(cmd.Delta))); + break; + } + case "duplicatePoints": + { + var sel = PointsAt(cmd.Indices); + if (sel.Count == 0) return; + var copies = new List(); + EditRoute(l => NavRouteEditing.Duplicate(l, sel, copies)); + SetNavEditStatus($"Duplicated {copies.Count} step(s)."); + break; + } + case "deletePoints": + { + var sel = PointsAt(cmd.Indices); + if (sel.Count == 0) return; + EditRoute(l => NavRouteEditing.Remove(l, sel)); + SetNavEditStatus($"Deleted {sel.Count} step(s)."); + break; + } + case "setActive": + if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count) return; + _settings.ActiveNavIndex = cmd.Index; + SaveSettings(); + SetNavEditStatus($"Active waypoint: {cmd.Index}."); + break; + + case "movePointHere": + { + if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count || !TryNavHere(out NavPoint here)) return; + NavPoint p = RoutePoints[cmd.Index]; + p.NS = here.NS; p.EW = here.EW; p.Z = here.Z; + _navigationUi.TryAutoSaveNav(); + SetNavEditStatus($"Step {cmd.Index} moved to your position."); + break; + } + case "nearestActive": + { + int i = FindNearestWaypoint(_settings.CurrentRoute); + if (RoutePoints.Count == 0) return; + _settings.ActiveNavIndex = i; + SaveSettings(); + SetNavEditStatus($"Active waypoint: {i} (nearest)."); + break; + } + case "reverseRoute": + if (RoutePoints.Count < 2) return; + EditRoute(NavRouteEditing.Reverse); + SetNavEditStatus("Route reversed."); + break; + + case "snapToPath": + { + if (!TryNavHere(out NavPoint here)) return; + NavPoint? inserted = null; + string error = string.Empty; + EditRoute(l => { NavRouteEditing.TrySnapInsert(l, here.NS, here.EW, SnapMinGapYards, out inserted, out error); return l; }); + SetNavEditStatus(inserted != null ? $"Inserted a point on the path at step {RoutePoints.IndexOf(inserted)}." : error); + break; + } + case "addPause": + { + if (!TryNavHere(out NavPoint p)) return; + p.Type = NavPointType.Pause; + p.PauseTimeMs = (int)(Math.Clamp(cmd.Seconds, 0.1, 600.0) * 1000); + InsertNavPoint(p, cmd.AddMode, cmd.InsertAt); + SetNavEditStatus($"Added a {p.PauseTimeMs / 1000.0:0.#} s pause."); + break; + } + case "addPortal": + { + if (!TryDescribeNavSelection(out string name, out double ons, out double oew, out double oz) || !TryNavHere(out NavPoint p)) return; + p.Type = NavPointType.PortalNPC; + p.TargetName = name; + p.ObjectClass = PortalObjectClass; + p.PortalExitNS = ons; p.PortalExitEW = oew; p.PortalExitZ = oz; + InsertNavPoint(p, cmd.AddMode, cmd.InsertAt); + SetNavEditStatus($"Added Portal step '{name}'."); + break; + } + case "addPointAtSelected": + { + if (!TryDescribeNavSelection(out string name, out double ns, out double ew, out double z)) return; + InsertNavPoint(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z }, cmd.AddMode, cmd.InsertAt); + SetNavEditStatus($"Added a point at '{name}'."); + break; + } + case "simplifyRoute": + { + double tol = Math.Clamp(cmd.Yards, 0.2, 10.0); + int ai = _settings.ActiveNavIndex; + NavPoint? keep = ai >= 0 && ai < RoutePoints.Count ? RoutePoints[ai] : null; + int removed = 0; + EditRoute(l => { removed = NavRouteEditing.Simplify(l, tol, keep); return l; }); + SetNavEditStatus($"Simplify ({tol:0.#} yd) removed {removed} point(s)."); + break; + } + case "setRecording": + _settings.IsRecordingNav = cmd.On; + SetNavEditStatus(cmd.On ? "Recording: walk the route; points are added for you." : "Recording stopped."); + break; + + case "trailToRoute": + { + NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty(); + List pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, cmd.Reverse); + if (pts.Count < 2) { SetNavEditStatus("The trail is too short to make a route."); return; } + _settings.IsRecordingNav = false; + // A new unsaved route: the loaded file on disk is not changed (Save As keeps it). + _settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts }; + _settings.CurrentNavPath = string.Empty; + _settings.ActiveNavIndex = 0; + RefreshNavFiles(); + SaveSettings(); + SetNavEditStatus($"{(cmd.Reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points (unsaved)."); + break; + } + } + } + + /// Copy-on-write route edit, then the route file autosave. + private void EditRoute(Func, List> edit) + { + NavRouteEditing.Apply(_settings, edit); + _navigationUi.TryAutoSaveNav(); + } + + /// The route's points at ; out-of-range indices are skipped. + private HashSet PointsAt(List? indices) + { + var sel = new HashSet(); + if (indices == null) return sel; + var pts = RoutePoints; + foreach (int i in indices) + if (i >= 0 && i < pts.Count) sel.Add(pts[i]); + return sel; + } + + /// A Point at the player's position (Z in nav units), or false when the position is unknown. + private bool TryNavHere(out NavPoint p) + { + p = new NavPoint(); + if (!NavCoordinateHelper.TryGetNavPosition(_host, out double ns, out double ew, out double z)) + { + SetNavEditStatus("Position unavailable."); + return false; + } + p.NS = ns; p.EW = ew; p.Z = z; + return true; + } + + /// Name and nav position of the selected world object. + private bool TryDescribeNavSelection(out string name, out double ns, out double ew, out double navZ) + { + name = string.Empty; ns = ew = navZ = 0; + if (!_host.HasGetSelectedItemId) { SetNavEditStatus("Selection unavailable."); return false; } + uint sel = _host.GetSelectedItemId(); + if (sel == 0) { SetNavEditStatus("Select an object first."); return false; } + if (!_host.HasGetObjectName || !_host.TryGetObjectName(sel, out name) || string.IsNullOrWhiteSpace(name)) + { + SetNavEditStatus("The selected object has no name yet."); + return false; + } + if (_host.HasGetObjectPosition + && _host.TryGetObjectPosition(sel, out uint cell, out float x, out float y, out float z) + && NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out ns, out ew)) + { + navZ = z / NavCoordinateHelper.NavZScale; + return true; + } + SetNavEditStatus($"Could not read the position of '{name}'."); + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 38dddac..89aa75c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -12,7 +12,7 @@ using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthAi.LegacyUi; -internal sealed class LegacyDashboardRenderer +internal sealed partial class LegacyDashboardRenderer { internal static readonly Vector4 ColTeal = new(0.15f, 0.85f, 0.90f, 1.00f); internal static readonly Vector4 ColAmber = new(0.91f, 0.70f, 0.20f, 1.00f); @@ -1087,6 +1087,13 @@ internal sealed class LegacyDashboardRenderer AutoVendorTriesTime = s.AutoVendorTriesTime, OffhandDefault = s.OffhandDefault, PreferDualWield = s.PreferDualWield, + EnableGroundLoot = s.EnableGroundLoot, + ItemInfoOnSelect = s.ItemInfoSettings.OnSelect, + // Diagnostics (per PC, RynthLog) + DiagDebugToChat = RynthLog.DebugToChat, + DiagFileLogAll = RynthLog.FileLogAll, + DiagCategories = RynthLog.FormatCategoryLevels(), + DiagFolder = RynthLog.Directory, }; return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload); } @@ -1288,6 +1295,12 @@ internal sealed class LegacyDashboardRenderer // Off hand: only fields the sender actually included (the engine face doesn't draw them yet) if (p.OffhandDefault is string od && OffhandRules.TryParse(od, out var odMode)) s.OffhandDefault = OffhandRules.SettingValue(odMode); if (p.PreferDualWield is bool pdw) s.PreferDualWield = pdw; + s.EnableGroundLoot = p.EnableGroundLoot; + s.ItemInfoSettings.OnSelect = p.ItemInfoOnSelect; + // Diagnostics: each setter rewrites diagnostics.json, so only touch what changed. + if (p.DiagDebugToChat != RynthLog.DebugToChat) RynthLog.DebugToChat = p.DiagDebugToChat; + if (p.DiagFileLogAll != RynthLog.FileLogAll) RynthLog.FileLogAll = p.DiagFileLogAll; + RynthLog.ApplyCategoryLevels(p.DiagCategories); SaveSettings(); } catch { } @@ -2300,6 +2313,12 @@ internal sealed class LegacyDashboardRenderer ActiveNavIndex = _settings.ActiveNavIndex, NavFiles = new List(_navFiles), Points = points, + TrackBreadcrumbs = _settings.NavOverlay.TrackBreadcrumbs, + ShowRouteOverlay = _settings.NavOverlay.ShowRouteMarkers, + IsRecording = _settings.IsRecordingNav, + TrailPoints = NavBreadcrumbs?.Trail.Length ?? 0, + TrailYards = NavBreadcrumbs?.TrailYards ?? 0, + EditStatus = CurrentNavEditStatus(), }; return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload); } @@ -2329,6 +2348,18 @@ internal sealed class LegacyDashboardRenderer SaveSettings(); break; + case "setBreadcrumbs": + // Nav panel "Breadcrumbs": record (and draw) the walked trail. + _settings.NavOverlay.TrackBreadcrumbs = cmd.On; + SaveSettings(); + break; + + case "setRouteOverlay": + // Nav panel "Route overlay": route rings / lines, waypoint labels, guide line. + _settings.NavOverlay.ShowRouteMarkers = cmd.On; + SaveSettings(); + break; + case "addWaypoint": _host.SetMotionBy("UI", 0x6500000D, false); // stop TurnRight _host.SetMotionBy("UI", 0x6500000E, false); // stop TurnLeft @@ -2405,6 +2436,11 @@ internal sealed class LegacyDashboardRenderer int ni = _navFiles.IndexOf(cmd.NavName); if (ni >= 0) { _selectedNavIdx = ni; LoadSelectedNav(); SaveSettings(); } break; + + default: + // Route editor commands (multi-select edits, pause / portal steps, trail -> route). + HandleNavEditCommand(cmd); + break; } } catch { } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs new file mode 100644 index 0000000..374c4d4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyItemInfoUi.cs @@ -0,0 +1,295 @@ +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.ItemInfo; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// +/// "RynthAi Item Info" window: every option of the Mag-style item info line (/ra iteminfo) with +/// a live preview of the selected item. Edits go straight into +/// and are saved by the dashboard autosave. +/// Opened from Advanced Settings → Display or with /ra iteminfo settings. +/// +internal sealed class LegacyItemInfoUi +{ + private readonly LegacyUiSettings _settings; + + // Supplied by RynthAiPlugin (it owns the host + object cache). + private Func? _describeSelected; // selected item's line (no prefix) or null when nothing is selected + private Action? _printSelected; // same path as /ra iteminfo (requests an ID when needed) + private Action? _testChatType; // prints a sample line with the given chat type + + // Preview is rebuilt on a timer or when an output option changes, not every frame. + private const long PreviewRefreshMs = 500; + private string? _previewText; + private long _previewAt; + private MagItemInfoOptions _previewOptions; + + private static readonly Vector4 ExampleColor = new(0.60f, 0.66f, 0.74f, 1f); + + public LegacyItemInfoUi(LegacyUiSettings settings) => _settings = settings; + + public void SetHooks(Func describeSelected, Action printSelected, Action testChatType) + { + _describeSelected = describeSelected; + _printSelected = printSelected; + _testChatType = testChatType; + } + + public void Render() + { + // Re-read every frame: loading a character profile replaces the settings object. + MagItemInfoSettings s = _settings.ItemInfoSettings; + if (!s.ShowWindow) return; + + ImGui.SetNextWindowSize(new Vector2(560, 600), ImGuiCond.FirstUseEver); + if (ImGui.Begin("RynthAi Item Info##ItemInfoSettings", ref s.ShowWindow)) + { + RenderPreview(s); + RenderWhen(s); + RenderFields(s); + RenderSpellsAndRatings(s); + RenderChat(s); + + ImGui.Spacing(); + ImGui.Separator(); + if (ImGui.Button("Reset all to defaults##ii")) + { + s.ResetToDefaults(); + _previewAt = 0; + } + ImGui.SameLine(); + if (ImGui.Button("Close##ii")) s.ShowWindow = false; + } + ImGui.End(); + } + + // ── Preview ────────────────────────────────────────────────────────────── + + private void RenderPreview(MagItemInfoSettings s) + { + if (!ImGui.CollapsingHeader("Preview (selected item)##ii", ImGuiTreeNodeFlags.DefaultOpen)) return; + + var options = MagItemInfoOptions.From(s); + long now = Environment.TickCount64; + if (_describeSelected != null && (now - _previewAt >= PreviewRefreshMs || options != _previewOptions)) + { + try { _previewText = _describeSelected(); } + catch (Exception ex) { _previewText = "Preview failed: " + ex.Message; } + _previewAt = now; + _previewOptions = options; + } + + // Pet-style output is up to four lines plus wrapping. + float previewHeight = s.Layout == MagItemInfoSettings.LayoutPetLines ? 110 : 70; + ImGui.BeginChild("iiPreview", new Vector2(0, previewHeight), ImGuiChildFlags.Borders); + if (string.IsNullOrEmpty(_previewText)) + ImGui.TextDisabled("Select an item to preview its info line."); + else + ImGui.TextWrapped(s.Prefix + _previewText); + ImGui.EndChild(); + + if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Same as /ra iteminfo: IDs the selected item first when needed."); + ImGui.SameLine(); + if (ImGui.Button("Refresh##iiRefresh")) _previewAt = 0; + } + + // ── When to print ──────────────────────────────────────────────────────── + + private static void RenderWhen(MagItemInfoSettings s) + { + if (!ImGui.CollapsingHeader("When to print##ii", ImGuiTreeNodeFlags.DefaultOpen)) return; + + ImGui.Checkbox("Describe items when selected##iiOnSel", ref s.OnSelect); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Print the info every time the selection changes to an item.\n/ra iteminfo always works, whatever is set here."); + + RenderClickTrigger(s, "##iiClick"); + + ImGui.Text("Item types:"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Which items the select / click triggers describe.\n/ra iteminfo and Print to chat ignore these."); + ImGui.Indent(); + ImGui.BeginDisabled(!s.OnSelect && s.ClickTrigger == MagItemInfoSettings.ClickOff); + ImGui.Checkbox("Weapons##iiSelW", ref s.OnSelectWeapons); ImGui.SameLine(); + ImGui.Checkbox("Armor & clothing##iiSelA", ref s.OnSelectArmor); ImGui.SameLine(); + ImGui.Checkbox("Jewelry##iiSelJ", ref s.OnSelectJewelry); ImGui.SameLine(); + ImGui.Checkbox("Other items##iiSelO", ref s.OnSelectOther); + ImGui.EndDisabled(); + ImGui.Unindent(); + + ImGui.SetNextItemWidth(200); + if (ImGui.SliderFloat("ID wait (seconds)##iiTimeout", ref s.IdTimeoutSec, 0.5f, 15f, "%.1f s")) + s.Sanitize(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("How long to wait for an unidentified item's appraisal\nbefore printing what is already known."); + } + + /// + /// "ID on click" combo (Off / Left / Right). Shared with Advanced Settings → Display, so + /// keeps the ImGui ids unique per window. + /// + public static void RenderClickTrigger(MagItemInfoSettings s, string idSuffix) + { + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("ID + print on click" + idSuffix, ref s.ClickTrigger, + MagItemInfoCatalog.ClickTriggers, MagItemInfoCatalog.ClickTriggers.Length)) + s.Sanitize(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Clicking an item in the world or your packs IDs it and prints its info,\n" + + "even when it was already selected. Clicks on RynthCore windows, drags and\n" + + "held-button camera turns are ignored.\n" + + "Right click prints whatever item is selected after the click: if your client\n" + + "doesn't select on right click, left-click to select, then right-click to print.\n" + + "Needs the ImGui overlay enabled."); + } + + /// Layout combo (pet-style lines / one line). Shared with Advanced Settings → Display. + public static void RenderLayout(MagItemInfoSettings s, string idSuffix) + { + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Layout" + idSuffix, ref s.Layout, MagItemInfoCatalog.Layouts, MagItemInfoCatalog.Layouts.Length)) + s.Sanitize(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip( + "Pet-style lines (like the ILT Hub pet roster):\n" + + " 1 Name (type mastery), set, AL, tinks, applied, craft\n" + + " 2 imbues, slayer, damage, variance, %a / %md / %mc\n" + + " 3 [ratings] wield / activation / diff, value\n" + + " 4 Spells: …\n" + + "One line: the classic Mag-Tools single line."); + } + + // ── Field toggles ──────────────────────────────────────────────────────── + + private void RenderFields(MagItemInfoSettings s) + { + if (!ImGui.CollapsingHeader("Fields##ii", ImGuiTreeNodeFlags.DefaultOpen)) return; + + if (ImGui.SmallButton("All on##iiFields")) s.HiddenFields = 0; + ImGui.SameLine(); + if (ImGui.SmallButton("All off##iiFields")) + { + foreach (var f in MagItemInfoCatalog.Fields) s.SetHidden(f.Field, true); + } + ImGui.SameLine(); + ImGui.TextDisabled("(the item name is always printed)"); + + if (ImGui.BeginTable("iiFieldTable", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Field", ImGuiTableColumnFlags.WidthStretch, 0.45f); + ImGui.TableSetupColumn("Example", ImGuiTableColumnFlags.WidthStretch, 0.55f); + foreach (var f in MagItemInfoCatalog.Fields) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + bool shown = !s.IsHidden(f.Field); + if (ImGui.Checkbox($"{f.Label}##iiF{(int)f.Field}", ref shown)) + s.SetHidden(f.Field, !shown); + ImGui.TableNextColumn(); + ImGui.TextColored(ExampleColor, f.Example); + } + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.Checkbox("Value & burden##iiValBu", ref s.ShowValueAndBurden); + ImGui.TableNextColumn(); + ImGui.TextColored(ExampleColor, "Value 12,500, BU 220"); + ImGui.EndTable(); + } + } + + // ── Spells + per-rating toggles ────────────────────────────────────────── + + private static void RenderSpellsAndRatings(MagItemInfoSettings s) + { + if (!ImGui.CollapsingHeader("Spells & ratings##ii")) return; + + ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Spells)); + ImGui.Text("Spell list:"); + ImGui.SameLine(); + ImGui.RadioButton("Mag filter##iiSpMag", ref s.SpellMode, MagItemInfoSettings.SpellModeMag); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Cantrips, level 7+ weapon auras, Augmented spells,\nand Impen/banes only on unenchantable gear."); + ImGui.SameLine(); + ImGui.RadioButton("All spells##iiSpAll", ref s.SpellMode, MagItemInfoSettings.SpellModeAll); + if (s.SpellMode == MagItemInfoSettings.SpellModeAll) + { + ImGui.SetNextItemWidth(200); + if (ImGui.SliderInt("Max spells listed##iiSpMax", ref s.MaxListedSpells, 1, 64)) + s.Sanitize(); + } + ImGui.EndDisabled(); + + ImGui.Spacing(); + ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Ratings)); + ImGui.Text("Ratings shown:"); + ImGui.SameLine(); + if (ImGui.SmallButton("All##iiRat")) s.HiddenRatings = 0; + ImGui.SameLine(); + if (ImGui.SmallButton("None##iiRat")) s.HiddenRatings = (1 << MagItemInfoCatalog.Ratings.Length) - 1; + if (ImGui.BeginTable("iiRatingTable", 3)) + { + var ratings = MagItemInfoCatalog.Ratings; + for (int i = 0; i < ratings.Length; i++) + { + ImGui.TableNextColumn(); + bool shown = !s.IsRatingHidden(i); + if (ImGui.Checkbox($"{ratings[i].Tag} - {ratings[i].Name}##iiR{i}", ref shown)) + s.SetRatingHidden(i, !shown); + } + ImGui.EndTable(); + } + ImGui.EndDisabled(); + } + + // ── Chat output ────────────────────────────────────────────────────────── + + private void RenderChat(MagItemInfoSettings s) + { + if (!ImGui.CollapsingHeader("Chat output##ii", ImGuiTreeNodeFlags.DefaultOpen)) return; + + RenderLayout(s, "##iiLayout"); + + ChatTypeCombo("Chat type / colour##iiChat", ref s.ChatType, allowSameAsHeader: false); + ImGui.SameLine(); + if (ImGui.Button("Test##iiChatTest")) _testChatType?.Invoke(s.ChatType); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Print a sample line with this chat type to see its colour."); + + // Pet-style only: the roster draws its detail lines in a second colour. + ImGui.BeginDisabled(s.Layout != MagItemInfoSettings.LayoutPetLines); + ChatTypeCombo("Detail lines colour##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true); + ImGui.SameLine(); + if (ImGui.Button("Test##iiChatDetailTest")) + _testChatType?.Invoke(s.DetailChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.DetailChatType); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above)."); + + ImGui.SetNextItemWidth(220); + ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Text put in front of every item info line (may be empty)."); + } + + /// Chat type picker; adds the "same as name line" entry (-1). + private static void ChatTypeCombo(string label, ref int chatType, bool allowSameAsHeader) + { + const string SameLabel = "Same as name line"; + string current = chatType == MagItemInfoSettings.SameAsHeader ? SameLabel : $"{chatType}"; + foreach (var (type, name) in MagItemInfoCatalog.ChatTypes) + if (type == chatType) { current = name; break; } + + ImGui.SetNextItemWidth(220); + if (!ImGui.BeginCombo(label, current)) return; + if (allowSameAsHeader && ImGui.Selectable(SameLabel, chatType == MagItemInfoSettings.SameAsHeader)) + chatType = MagItemInfoSettings.SameAsHeader; + foreach (var (type, name) in MagItemInfoCatalog.ChatTypes) + if (ImGui.Selectable(name, type == chatType)) chatType = type; + ImGui.EndCombo(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs index 8360a03..444d32a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.Install; namespace RynthCore.Plugin.RynthAi.LegacyUi; @@ -46,7 +47,7 @@ internal sealed class LegacyMetaUi private string _statusMessage = ""; private DateTime _statusTime = DateTime.MinValue; - private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + private static readonly string MetaFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles"); /// Warnings from the most recent LoadMacroFile, so the Avalonia /// bridge can surface them too (it doesn't see the LoadedMeta). diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 46da731..2368a7f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -13,6 +13,8 @@ public static class DashWindows public static bool ShowWeapons; public static bool ShowLua; public static bool ShowDungeonMap; + /// ILT Hub window (persisted in ilt-hub.json, not in the combat profile). + public static bool ShowIltHub; } public sealed class LegacyUiSettings @@ -80,6 +82,10 @@ public sealed class LegacyUiSettings public bool ShowTargetStaminaMana; + /// Mag-style item info (/ra iteminfo): on-select, per-field visibility, chat type, prefix. + /// Edited in the "RynthAi Item Info" window. + public RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoSettings ItemInfoSettings = new(); + public bool EnableMissileCrafting = true; public int MissileCraftAmmoThreshold = 1000; @@ -162,6 +168,8 @@ public sealed class LegacyUiSettings public const float FollowNavMinLowest = 0.5f, FollowNavMinHighest = 20f; public static float ClampFollowNavMin(float yards) => float.IsNaN(yards) ? 1.5f : Math.Clamp(yards, FollowNavMinLowest, FollowNavMinHighest); + /// Marker colours, waypoint HUD / labels, breadcrumb trail and recording options. + public NavOverlaySettings NavOverlay = new(); public float NavRingThickness = 6.0f; public float NavLineThickness = 6.0f; public float NavHeightOffset = 0.05f; @@ -197,6 +205,8 @@ public sealed class LegacyUiSettings /// public bool TravelToOwnCorpse; public bool LootOnlyRareCorpses; + /// Also pick up loose ground items that match the loot profile, within the corpse max range. + public bool EnableGroundLoot; public bool PeaceModeWhenIdle = true; public bool RebuffWhenIdle; /// @@ -411,6 +421,8 @@ public sealed class LegacyUiSettings public List MonsterRules { get; set; } = new(); public List ItemRules { get; set; } = new(); + /// Loose ammo the monster rules can prefer. Edited by the local monsters window. + public List AmmoRules { get; set; } = new(); public List ConsumableRules { get; set; } = new(); public List BuffRules { get; set; } = new(); public List MetaRules { get; set; } = new(); @@ -614,6 +626,8 @@ public sealed class MonsterRule /// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed /// item to wield there (the old per-rule picker). public int OffhandId { get; set; } + /// Optional loose ammo stack id for missile combat while this rule matches (0 = auto). + public int PreferredAmmoItemId { get; set; } public string PetDamage { get; set; } = "PAuto"; /// Debuffs the player typed in (Damage panel), comma separated: a spell's base /// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is. @@ -629,6 +643,11 @@ public sealed class BuffRule public sealed class ItemRule { + /// Action string for a listed weapon (VirindiTank import and the ILT gear importer). + public const string WeaponAction = "Weapon"; + /// Action string for a listed shield. + public const string ShieldAction = "Shield"; + public int Id { get; set; } public string Name { get; set; } = string.Empty; public string Action { get; set; } = "Loot"; @@ -638,6 +657,18 @@ public sealed class ItemRule /// (not known, or an entry from before sources were kept). public string ElementSource { get; set; } = ""; public bool KeepBuffed { get; set; } = true; + + /// True when this row is a shield (off hand), not a main-hand weapon. + public bool IsShield() => string.Equals(Action, ShieldAction, StringComparison.OrdinalIgnoreCase); +} + +/// Loose ammo the monster rules can prefer (bow, crossbow, atlatl, or Auto). +public sealed class AmmoRule +{ + public int Id { get; set; } + public string Name { get; set; } = string.Empty; + /// Bow, Crossbow, Atlatl, or Auto (match any launcher). + public string Category { get; set; } = "Auto"; } /// JSON wire-format types used by the engine-side Avalonia MonstersPanel. @@ -707,6 +738,17 @@ public sealed class NavBridgePayload public int ActiveNavIndex { get; set; } public List NavFiles { get; set; } = new(); public List Points { get; set; } = new(); + /// NavOverlaySettings.TrackBreadcrumbs (Nav panel "Breadcrumbs" toggle). + public bool TrackBreadcrumbs { get; set; } + /// NavOverlaySettings.ShowRouteMarkers (Nav panel "Route overlay" toggle). + public bool ShowRouteOverlay { get; set; } + /// Route recording is on (/ra navrec). + public bool IsRecording { get; set; } + /// Breadcrumb trail since the last teleport: point count and walked yards. + public int TrailPoints { get; set; } + public double TrailYards { get; set; } + /// Result of the last route edit ("Route reversed."), empty once it is a few seconds old. + public string EditStatus { get; set; } = string.Empty; } /// One-shot command sent from the Avalonia NavPanel to the plugin. @@ -720,6 +762,12 @@ public sealed class NavCommand public int InsertAt { get; set; } = -1; public string NavName { get; set; } = string.Empty; public string Text { get; set; } = string.Empty; // addChat: the command or text + public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording + public List Indices { get; set; } = new(); // movePoints / duplicatePoints / deletePoints + public int Delta { get; set; } // movePoints: -1 up, +1 down + public double Seconds { get; set; } // addPause + public double Yards { get; set; } // simplifyRoute tolerance + public bool Reverse { get; set; } // trailToRoute: backtrack (walk the trail in reverse) } /// Bridge payload for the engine-side Avalonia SettingsPanel. @@ -915,6 +963,21 @@ public sealed class SettingsBridgePayload // The off hand (only when the sender includes them; today's engine Settings face doesn't). public string? OffhandDefault { get; set; } public bool? PreferDualWield { get; set; } + + // Ground loot (GroundLootController; also /ra groundloot on|off). + public bool EnableGroundLoot { get; set; } + // Item info: describe an item in chat when it is selected (/ra iteminfo onselect). + public bool ItemInfoOnSelect { get; set; } + + // Diagnostics. Stored per PC in Logs\Diagnostics\diagnostics.json (RynthLog), not in + // the character profile; applied only when a value differs, so a save of other + // settings doesn't rewrite that file. + public bool DiagDebugToChat { get; set; } + public bool DiagFileLogAll { get; set; } = true; + /// Every trace category as "Name=Level" joined by ','; Level 0 = Off, 1 = Trace, 2 = Info. + public string DiagCategories { get; set; } = string.Empty; + /// Read-only: the diagnostics folder, shown under the switches. + public string DiagFolder { get; set; } = string.Empty; } public enum MetaConditionType diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs index de89dc3..6c3f27f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavCoordinateHelper.cs @@ -5,6 +5,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi; internal static class NavCoordinateHelper { + /// World Z from the player pose is divided by this to match nav-file height. + public const double NavZScale = 240.0; + public static bool TryGetNavCoords(RynthCoreHost host, out double northSouth, out double eastWest) { northSouth = 0; @@ -19,6 +22,17 @@ internal static class NavCoordinateHelper return false; } + /// Current position as a waypoint would store it (NS/EW map coords + Z in nav units). + public static bool TryGetNavPosition(RynthCoreHost host, out double northSouth, out double eastWest, out double navZ) + { + navZ = 0; + if (!TryGetNavCoords(host, out northSouth, out eastWest)) + return false; + if (host.HasGetPlayerPose && host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _)) + navZ = z / NavZScale; + return true; + } + internal static bool TryConvertPoseToCoords(uint objCellId, float x, float y, out double northSouth, out double eastWest) { northSouth = 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavOverlaySettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavOverlaySettings.cs new file mode 100644 index 0000000..84c3e8d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavOverlaySettings.cs @@ -0,0 +1,109 @@ +// NavOverlaySettings.cs — display + recording options for the Navigation window: +// route marker colours, the on-screen waypoint HUD / labels, the guide line to the +// active waypoint, the breadcrumb trail and route recording. +// +// Stored per character inside LegacyUiSettings.NavOverlay (public fields, serialized via +// RynthAiJsonContext IncludeFields). Colours are D3D9 ARGB (0xAARRGGBB). +using System; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +/// Persisted Navigation display / breadcrumb / recording options. +public sealed class NavOverlaySettings +{ + // ── Route markers (3D rings + lines) ───────────────────────────────────── + /// + /// Route overlay master switch (Nav panel "Route overlay"): the route's rings and connecting + /// lines, the waypoint labels and the guide line. The waypoint HUD window has its own switch. + /// + public bool ShowRouteMarkers = true; + /// Upper bound on route points drawn around the active waypoint. + public int MaxRouteMarkers = 128; + public uint ColorRing = 0xFF00FFFF; // cyan + public uint ColorActiveRing = 0xFFFF4444; // red + public uint ColorLine = 0xFF0088FF; // blue + + // ── Waypoint HUD + on-screen labels ────────────────────────────────────── + /// Small movable window: active waypoint, distance, direction arrow, next step. + public bool ShowHud = true; + /// Only show the HUD while navigation is enabled (otherwise whenever a route is loaded). + public bool HudOnlyWhileNavigating; + /// "#12 · 34yd" text drawn over the upcoming waypoints in the 3D view. + public bool ShowWaypointLabels = true; + /// How many upcoming waypoints get a label (active included). + public int LabelsAhead = 3; + /// Line from the player to the active waypoint (UB "breadcrumb" line). + public bool ShowGuideLine = true; + public uint ColorGuide = 0xFFFFDC28; // yellow + + // ── Breadcrumb trail ───────────────────────────────────────────────────── + /// + /// Record where the character walks, independent of any route (Nav panel "Breadcrumbs"). + /// While off, the trail is neither extended nor drawn. + /// + public bool TrackBreadcrumbs = true; + /// Draw the recorded trail on the ground. + public bool ShowBreadcrumbs = true; + /// Minimum distance between trail samples, yards. + public float BreadcrumbSpacingYards = 3f; + /// Trail length cap (oldest samples drop off). + public int BreadcrumbMaxPoints = 400; + /// Trail segments farther than this from the player are not drawn, yards. + public float BreadcrumbDrawRangeYards = 150f; + /// Older trail segments fade out. + public bool BreadcrumbFade = true; + public uint ColorBreadcrumb = 0xFFFF9A2E; // orange + + // ── Route recording ────────────────────────────────────────────────────── + /// Distance between auto-added Point waypoints while recording, yards. + public float RecordSpacingYards = 5f; + /// On a teleport while recording, add a Portal step for the portal used just before it. + public bool RecordPortals = true; + /// Pause added after an auto-recorded portal step, ms (0 = none). + public int RecordPauseAfterPortalMs = 1500; + + // Effective visibility (methods, not properties, so the settings JSON doesn't gain fields). + + /// Breadcrumb trail is drawn: tracking on and the trail display on. + public bool TrailVisible() => TrackBreadcrumbs && ShowBreadcrumbs; + + /// Guide line to the active waypoint is drawn (part of the route overlay). + public bool GuideLineVisible() => ShowRouteMarkers && ShowGuideLine; + + /// Waypoint labels are drawn (part of the route overlay). + public bool LabelsVisible() => ShowRouteMarkers && ShowWaypointLabels; + + /// Clamp values a hand-edited or older profile could carry out of range. + public void Sanitize() + { + MaxRouteMarkers = Math.Clamp(MaxRouteMarkers, 8, 128); + LabelsAhead = Math.Clamp(LabelsAhead, 1, 10); + BreadcrumbSpacingYards = Clamp(BreadcrumbSpacingYards, 0.5f, 50f, 3f); + BreadcrumbMaxPoints = Math.Clamp(BreadcrumbMaxPoints, 20, 2000); + BreadcrumbDrawRangeYards = Clamp(BreadcrumbDrawRangeYards, 20f, 500f, 150f); + RecordSpacingYards = Clamp(RecordSpacingYards, 1f, 50f, 5f); + RecordPauseAfterPortalMs = Math.Clamp(RecordPauseAfterPortalMs, 0, 30000); + } + + /// Display defaults (recording / trail options keep their values). + public void ResetColors() + { + var d = new NavOverlaySettings(); + ColorRing = d.ColorRing; ColorActiveRing = d.ColorActiveRing; ColorLine = d.ColorLine; + ColorGuide = d.ColorGuide; ColorBreadcrumb = d.ColorBreadcrumb; + } + + private static float Clamp(float v, float min, float max, float fallback) + => float.IsNaN(v) ? fallback : Math.Clamp(v, min, max); + + /// D3D9 ARGB → ImGui ABGR (swap red and blue). + public static uint ArgbToImGui(uint argb) + => (argb & 0xFF00FF00) | ((argb & 0x00FF0000) >> 16) | ((argb & 0x000000FF) << 16); + + /// Same colour with its alpha scaled by (0..1). + public static uint ScaleAlpha(uint argb, float factor) + { + uint a = (uint)Math.Clamp((argb >> 24) * factor, 0f, 255f); + return (a << 24) | (argb & 0x00FFFFFF); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteEditing.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteEditing.cs new file mode 100644 index 0000000..8e37f83 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteEditing.cs @@ -0,0 +1,229 @@ +// NavRouteEditing.cs — route edit operations for the Navigation window (UB-IT nav builder +// parity plus a few extras): remove / duplicate / move selected, reverse, snap-insert on the +// path, simplify, nearest waypoint, trail → route. +// +// The nav engine reads CurrentRoute.Points on the plugin tick thread while the window edits +// on the render thread, so structural edits never mutate the live list: they build a new +// list and swap the reference (atomic), keeping the active waypoint on the same NavPoint. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.LegacyUi; + +internal static class NavRouteEditing +{ + /// Nav map units → yards (the engine's distance scale). + public const double NavToYards = 240.0; + + public static double DistanceYards(double ns1, double ew1, double ns2, double ew2) + { + double dn = ns2 - ns1, de = ew2 - ew1; + return Math.Sqrt(dn * dn + de * de) * NavToYards; + } + + /// + /// Copy-on-write edit of the current route. receives a private copy + /// and returns the new list; the active waypoint follows its NavPoint (or is clamped when + /// that point was removed). + /// + public static void Apply(LegacyUiSettings s, Func, List> edit) + { + var route = s.CurrentRoute; + var old = route.Points; + int oldActive = s.ActiveNavIndex; + NavPoint? active = oldActive >= 0 && oldActive < old.Count ? old[oldActive] : null; + + var next = edit(new List(old)); + route.Points = next; + + int ai = active != null ? next.IndexOf(active) : -1; + s.ActiveNavIndex = ai >= 0 ? ai : Math.Clamp(oldActive, 0, Math.Max(0, next.Count - 1)); + } + + /// Field-for-field copy (NavPoint is a plain DTO). + public static NavPoint Clone(NavPoint p) => new() + { + Type = p.Type, NS = p.NS, EW = p.EW, Z = p.Z, + SpellId = p.SpellId, PauseTimeMs = p.PauseTimeMs, ChatCommand = p.ChatCommand, + TargetName = p.TargetName, ObjectClass = p.ObjectClass, IsTie = p.IsTie, VendorId = p.VendorId, + PortalExitNS = p.PortalExitNS, PortalExitEW = p.PortalExitEW, PortalExitZ = p.PortalExitZ, + }; + + public static List Remove(List list, HashSet sel) + { + list.RemoveAll(sel.Contains); + return list; + } + + /// Each selected point gets a copy right after it; returns the copies via . + public static List Duplicate(List list, HashSet sel, List copies) + { + var result = new List(list.Count + sel.Count); + foreach (var p in list) + { + result.Add(p); + if (!sel.Contains(p)) continue; + var c = Clone(p); + result.Add(c); + copies.Add(c); + } + return result; + } + + /// Moves every selected point one slot up (delta -1) or down (+1), keeping their order; + /// a selected point already at the edge (or blocked by another selected one there) stays put. + public static List Move(List list, HashSet sel, int delta) + { + if (delta < 0) + { + for (int i = 1; i < list.Count; i++) + if (sel.Contains(list[i]) && !sel.Contains(list[i - 1])) + (list[i - 1], list[i]) = (list[i], list[i - 1]); + } + else + { + for (int i = list.Count - 2; i >= 0; i--) + if (sel.Contains(list[i]) && !sel.Contains(list[i + 1])) + (list[i + 1], list[i]) = (list[i], list[i + 1]); + } + return list; + } + + public static List Reverse(List list) + { + list.Reverse(); + return list; + } + + /// Nearest travel Point to the given position, or -1 when the route has none. + public static int NearestPointIndex(IReadOnlyList list, double ns, double ew) + { + int best = -1; + double bestD = double.MaxValue; + for (int i = 0; i < list.Count; i++) + { + var p = list[i]; + if (p.Type != NavPointType.Point) continue; + double d = DistanceYards(ns, ew, p.NS, p.EW); + if (d < bestD) { bestD = d; best = i; } + } + return best; + } + + /// + /// UB-IT "snap to path": projects the position onto every Point→Point leg (NS/EW plane), + /// and inserts a Point at the closest spot (Z interpolated) before the leg's far end. + /// Refuses when the spot lands within of an existing point. + /// + public static bool TrySnapInsert(List list, double ns, double ew, double minGapYards, + out NavPoint? inserted, out string error) + { + inserted = null; + error = string.Empty; + int bestLeg = -1; + double bestDist = double.MaxValue, bestT = 0; + for (int i = 0; i + 1 < list.Count; i++) + { + NavPoint a = list[i], b = list[i + 1]; + if (a.Type != NavPointType.Point || b.Type != NavPointType.Point) continue; + double vn = b.NS - a.NS, ve = b.EW - a.EW; + double len2 = vn * vn + ve * ve; + double t = len2 < 1e-12 ? 0 : Math.Clamp(((ns - a.NS) * vn + (ew - a.EW) * ve) / len2, 0, 1); + double d = DistanceYards(ns, ew, a.NS + vn * t, a.EW + ve * t); + if (d < bestDist) { bestDist = d; bestLeg = i; bestT = t; } + } + if (bestLeg < 0) { error = "The route has no Point→Point leg to snap onto."; return false; } + + NavPoint pa = list[bestLeg], pb = list[bestLeg + 1]; + var p = new NavPoint + { + Type = NavPointType.Point, + NS = pa.NS + (pb.NS - pa.NS) * bestT, + EW = pa.EW + (pb.EW - pa.EW) * bestT, + Z = pa.Z + (pb.Z - pa.Z) * bestT, + }; + if (DistanceYards(p.NS, p.EW, pa.NS, pa.EW) < minGapYards || DistanceYards(p.NS, p.EW, pb.NS, pb.EW) < minGapYards) + { + error = $"Closest path spot is on waypoint {(bestT < 0.5 ? bestLeg : bestLeg + 1)} already."; + return false; + } + list.Insert(bestLeg + 1, p); + inserted = p; + return true; + } + + /// + /// Douglas–Peucker over each run of consecutive Points (action steps split runs and are + /// never touched; run endpoints are kept). Removes Points that deviate less than + /// from the simplified line. Returns the removed count. + /// + public static int Simplify(List list, double toleranceYards, NavPoint? keep) + { + var drop = new HashSet(); + int runStart = -1; + for (int i = 0; i <= list.Count; i++) + { + bool isPoint = i < list.Count && list[i].Type == NavPointType.Point; + if (isPoint && runStart < 0) runStart = i; + if (!isPoint && runStart >= 0) + { + if (i - 1 - runStart >= 2) + DouglasPeucker(list, runStart, i - 1, toleranceYards, drop); + runStart = -1; + } + } + if (keep != null) drop.Remove(keep); // never remove the active waypoint + list.RemoveAll(drop.Contains); + return drop.Count; + } + + private static void DouglasPeucker(List list, int first, int last, double tol, HashSet drop) + { + // Iterative stack so long recorded runs can't overflow the stack. + var stack = new Stack<(int, int)>(); + stack.Push((first, last)); + while (stack.Count > 0) + { + var (a, b) = stack.Pop(); + if (b - a < 2) continue; + double maxD = -1; + int maxI = -1; + for (int i = a + 1; i < b; i++) + { + double d = SegmentDistanceYards(list[i], list[a], list[b]); + if (d > maxD) { maxD = d; maxI = i; } + } + if (maxD > tol) + { + stack.Push((a, maxI)); + stack.Push((maxI, b)); + } + else + { + for (int i = a + 1; i < b; i++) drop.Add(list[i]); + } + } + } + + /// Horizontal distance from to segment a–b, yards. + private static double SegmentDistanceYards(NavPoint p, NavPoint a, NavPoint b) + { + double vn = b.NS - a.NS, ve = b.EW - a.EW; + double len2 = vn * vn + ve * ve; + double t = len2 < 1e-12 ? 0 : Math.Clamp(((p.NS - a.NS) * vn + (p.EW - a.EW) * ve) / len2, 0, 1); + return DistanceYards(p.NS, p.EW, a.NS + vn * t, a.EW + ve * t); + } + + /// Total walking length of the route's Point→Point legs, yards. + public static double PathLengthYards(IReadOnlyList list) + { + double total = 0; + for (int i = 0; i + 1 < list.Count; i++) + { + NavPoint a = list[i], b = list[i + 1]; + if (a.Type == NavPointType.Point && b.Type == NavPointType.Point) + total += DistanceYards(a.NS, a.EW, b.NS, b.EW); + } + return total; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs index d0289ee..eed6cf7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs @@ -17,6 +17,14 @@ namespace RynthCore.Plugin.RynthAi; [JsonSerializable(typeof(MetaRuleDto))] [JsonSerializable(typeof(MetaCommand))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Meta.MetaScheduleConfig))] +// UB seed, translation, diagnostics, ILT Hub, HUD and item info files persist through this +// context (NativeAOT cannot reflect). +[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Translate.TranslateSettings))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.RynthLogConfig))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Huds.HudState))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.IltHub.IltHubState))] +[JsonSerializable(typeof(System.Collections.Generic.List), TypeInfoPropertyName = "IltBankTransactionList")] [JsonSourceGenerationOptions( WriteIndented = true, IncludeFields = true, diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs index ae58016..6275d02 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs @@ -1379,7 +1379,7 @@ public sealed class SalvageManager return name.Contains("Salvage (", StringComparison.OrdinalIgnoreCase); } - private void Log(string message) => _host.Log(message); + private void Log(string message) => RynthLog.Write(LogCat.Salvage, message); private void NoteError(string what) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapTexture.cs b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapTexture.cs new file mode 100644 index 0000000..f7c0b69 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Maps/DungeonMapTexture.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Install; + +namespace RynthCore.Plugin.RynthAi.Maps; + +/// +/// One D3D9 POOL_MANAGED A8R8G8B8 texture baked from a single Z-layer's floor cells. +/// Each texel covers one GridCell (0.5 AC units). Edge cells (cells bordering empty space) +/// use the bright wall colour; interior cells use the semi-transparent fill colour; +/// empty cells are fully transparent (alpha=0). +/// +/// Displayed via dl.AddImageQuad — O(1) vertices per layer vs O(strips + edges) otherwise. +/// Disk-cached to \RynthAi\Maps\{landblock:X8}_{layerIdx}.bin so +/// re-entering a dungeon skips the rasterise step. +/// +internal sealed class DungeonMapTexture : IDisposable +{ + private const float GridCell = 0.5f; + private static readonly string CacheDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"Maps"); + private const uint Magic = 0x524D5458u; // "XTMR" + + // D3D9 vtable indices on IDirect3DDevice9 / IDirect3DTexture9 + 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; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr shared); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr pRect, 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 pBits; } + + // ── D3D9 A8R8G8B8 colour helpers (ARGB uint: A<<24|R<<16|G<<8|B) ───── + private static uint Argb(float r, float g, float b, float a) => + ((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f); + + // Match DungeonMapUi colour definitions + private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f); + private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f); + private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f); + private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f); + private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f); + private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f); + + // World bounds of the baked area + public float WorldX0, WorldY0, WorldX1, WorldY1; + public IntPtr TexId => _tex; + + private IntPtr _tex; + + private DungeonMapTexture() {} + + /// + /// Returns a texture for the given floor-cell grid. Checks the disk cache first; + /// if absent, rasterises, uploads to D3D9, and saves to disk. + /// Returns null if device is invalid or texture upload fails. + /// + public static DungeonMapTexture? GetOrBuild( + IntPtr device, + Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells, + uint landblock, int layerIdx) + { + if (device == IntPtr.Zero || cells.Count == 0) return null; + + // Bounding box + int xMin = int.MaxValue, xMax = int.MinValue; + int yMin = int.MaxValue, yMax = int.MinValue; + foreach (var (gx, gy) in cells.Keys) + { + if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx; + if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy; + } + int w = xMax - xMin + 1, h = yMax - yMin + 1; + if (w <= 0 || h <= 0 || w > 8192 || h > 8192) return null; + + // Try disk cache first (only valid when dimensions match the dat-computed bounds) + var cached = TryLoadFromDisk(device, landblock, layerIdx, xMin, yMin, w, h); + if (cached != null) return cached; + + // Rasterise → upload → cache + var pixels = Rasterise(cells, xMin, yMax, w, h); + IntPtr tex = Upload(device, w, h, pixels); + if (tex == IntPtr.Zero) return null; + + SaveToDisk(landblock, layerIdx, xMin, yMin, w, h, pixels); + + return new DungeonMapTexture + { + _tex = tex, + WorldX0 = xMin * GridCell, + WorldY0 = yMin * GridCell, + WorldX1 = (xMax + 1) * GridCell, + WorldY1 = (yMax + 1) * GridCell, + }; + } + + public void Dispose() + { + if (_tex == IntPtr.Zero) return; + try { GetVtFunc(_tex, VtRelease)(_tex); } catch { } + _tex = IntPtr.Zero; + } + + // ── Rasterisation ───────────────────────────────────────────────────── + + private static uint[] Rasterise( + Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells, + int xMin, int yMax, int w, int h) + { + var pixels = new uint[w * h]; // 0 = transparent + foreach (var ((gx, gy), ctype) in cells) + { + bool isEdge = !cells.ContainsKey((gx + 1, gy)) + || !cells.ContainsKey((gx - 1, gy)) + || !cells.ContainsKey((gx, gy + 1)) + || !cells.ContainsKey((gx, gy - 1)); + uint col = isEdge + ? ctype switch + { + DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp, + DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown, + _ => EdgeFlat, + } + : ctype switch + { + DungeonMapUi.CellType.SlopeUp => FillSlopeUp, + DungeonMapUi.CellType.SlopeDown => FillSlopeDown, + _ => FillFlat, + }; + // Row 0 = northernmost cells (highest gy), so flip Y + pixels[(yMax - gy) * w + (gx - xMin)] = col; + } + return pixels; + } + + // ── D3D9 upload ─────────────────────────────────────────────────────── + + private static unsafe IntPtr Upload(IntPtr device, int w, int h, uint[] pixels) + { + try + { + int hr = GetVtFunc(device, VtCreateTexture)( + device, (uint)w, (uint)h, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero); + if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero; + + var locked = new D3DLockedRect(); + hr = GetVtFunc(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0); + if (hr < 0) { GetVtFunc(tex, VtRelease)(tex); return IntPtr.Zero; } + + // Copy row by row — pitch may be wider than w*4 + for (int row = 0; row < h; row++) + { + IntPtr dst = IntPtr.Add(locked.pBits, row * locked.Pitch); + fixed (uint* src = &pixels[row * w]) + Buffer.MemoryCopy(src, (void*)dst, (nuint)(w * 4), (nuint)(w * 4)); + } + + GetVtFunc(tex, VtUnlockRect)(tex, 0); + return tex; + } + catch { return IntPtr.Zero; } + } + + // ── Disk cache ──────────────────────────────────────────────────────── + + private static DungeonMapTexture? TryLoadFromDisk( + IntPtr device, uint lb, int layerIdx, + int expXMin, int expYMin, int expW, int expH) + { + try + { + string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin"); + if (!File.Exists(path)) return null; + using var br = new BinaryReader(File.OpenRead(path)); + if (br.ReadUInt32() != Magic) return null; + int xMin = br.ReadInt32(), yMin = br.ReadInt32(); + int w = br.ReadInt32(), h = br.ReadInt32(); + // Invalidate if bounds no longer match the dat + if (w != expW || h != expH || xMin != expXMin || yMin != expYMin) return null; + if (br.BaseStream.Length < 20L + (long)w * h * 4) return null; + + var pixels = new uint[w * h]; + for (int i = 0; i < pixels.Length; i++) pixels[i] = br.ReadUInt32(); + + IntPtr tex = Upload(device, w, h, pixels); + if (tex == IntPtr.Zero) return null; + + return new DungeonMapTexture + { + _tex = tex, + WorldX0 = xMin * GridCell, + WorldY0 = yMin * GridCell, + WorldX1 = (xMin + w) * GridCell, + WorldY1 = (yMin + h) * GridCell, + }; + } + catch { return null; } + } + + private static void SaveToDisk(uint lb, int layerIdx, int xMin, int yMin, int w, int h, uint[] pixels) + { + try + { + Directory.CreateDirectory(CacheDir); + string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin"); + using var bw = new BinaryWriter(File.Open(path, FileMode.Create)); + bw.Write(Magic); bw.Write(xMin); bw.Write(yMin); bw.Write(w); bw.Write(h); + foreach (uint px in pixels) bw.Write(px); + } + catch { } + } + + // ── VTable helper ───────────────────────────────────────────────────── + + private static unsafe TDelegate GetVtFunc(IntPtr obj, int idx) where TDelegate : Delegate + { + void** vt = *(void***)obj; + return Marshal.GetDelegateForFunctionPointer((IntPtr)vt[idx]); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 1d1d1a2..1af94ff 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.CreatureData; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; +using RynthCore.Install; namespace RynthCore.Plugin.RynthAi.Meta; @@ -111,7 +112,7 @@ internal sealed class MetaManager // §3.3: surface schema/enum drift once per session instead of letting a // mid-enum insert silently corrupt every saved meta + the JSON bridge. if (MetaSchema.DriftError != null) - _host.Log($"[Meta] SCHEMA DRIFT — fix MetaSchema/enum alignment: {MetaSchema.DriftError}"); + RynthLog.Write(LogCat.Meta, $"[Meta] SCHEMA DRIFT — fix MetaSchema/enum alignment: {MetaSchema.DriftError}"); } public void SetMtCommandHandler(Func handler) => _mtCommandHandler = handler; @@ -389,7 +390,7 @@ internal sealed class MetaManager // A condition/action threw. Localise it to this tick instead of // letting partial state (half-applied SetState, pushed call stack) // persist. ForceStateReset recomputes HasFired cleanly next tick. - _host.Log($"[Meta] Think crashed in '{_settings.CurrentState}': {ex.GetType().Name}: {ex.Message}"); + RynthLog.Write(LogCat.Meta, $"[Meta] Think crashed in '{_settings.CurrentState}': {ex.GetType().Name}: {ex.Message}"); if (_settings.MetaDebug) _host.WriteToChat($"[Meta] Think exception: {ex.Message}", 1); _lastExprError = $"Think: {ex.GetType().Name}: {Truncate(ex.Message, 100)}"; @@ -850,7 +851,7 @@ internal sealed class MetaManager { if (string.IsNullOrWhiteSpace(rule.ActionData)) { - _host.Log("[Meta] EmbedNav: empty ActionData, ignored"); + RynthLog.Write(LogCat.Meta, "[Meta] EmbedNav: empty ActionData, ignored"); break; } string routeName = rule.ActionData.Split(';')[0]; @@ -886,13 +887,13 @@ internal sealed class MetaManager _settings.CurrentRoute = newRoute; _settings.ActiveNavIndex = StartIndexForRoute(newRoute); _settings.EnableNavigation = true; - _host.Log($"[Meta] EmbedNav: loaded '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})"); + RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: loaded '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})"); _host.WriteToChat($"[RynthAi Meta] Route \u2192 {routeName} ({newRoute.Points.Count} pts)", 1); break; } // Fallback: a standalone .nav file in NavProfiles. - string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles"; + string navFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"NavProfiles"); string fullPath = Path.Combine(navFolder, routeName + ".nav"); if (File.Exists(fullPath)) { @@ -901,19 +902,19 @@ internal sealed class MetaManager _settings.CurrentRoute = newRoute; _settings.ActiveNavIndex = StartIndexForRoute(newRoute); _settings.EnableNavigation = true; - _host.Log($"[Meta] EmbedNav: loaded file '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})"); + RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: loaded file '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})"); _host.WriteToChat($"[RynthAi Meta] Route \u2192 {routeName} ({newRoute.Points.Count} pts)", 1); } else { string keys = string.Join(", ", _settings.EmbeddedNavs.Keys); - _host.Log($"[Meta] EmbedNav: route '{routeName}' not found. Embedded keys: [{keys}]"); + RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: route '{routeName}' not found. Embedded keys: [{keys}]"); _host.WriteToChat($"[RynthAi Meta] Route missing: {routeName}", 1); } } catch (Exception ex) { - _host.Log($"[Meta] EmbedNav error: {ex.Message}"); + RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav error: {ex.Message}"); _host.WriteToChat($"[RynthAi Meta] Load Error: {ex.Message}", 1); } break; @@ -1023,7 +1024,7 @@ internal sealed class MetaManager _lastExprError = $"{rule.Action} ignored — VTank Views are not supported in RynthAi"; _lastExprErrorAt = Clock(); _host.WriteToChat("[RynthAi] Meta uses VTank Views (CreateView/DestroyView) — not supported; those actions are ignored.", 1); - _host.Log($"[Meta] {rule.Action} ignored — VTank Views unsupported"); + RynthLog.Write(LogCat.Meta, $"[Meta] {rule.Action} ignored — VTank Views unsupported"); } break; } @@ -1091,7 +1092,7 @@ internal sealed class MetaManager parts[2].Equals("load", StringComparison.OrdinalIgnoreCase)) { string name = string.Join(" ", parts, 3, parts.Length - 3); - string metaDir = @"C:\Games\RynthSuite\RynthAi\MetaFiles"; + string metaDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles"); string afPath = Path.Combine(metaDir, name + ".af"); string metPath = Path.Combine(metaDir, name + ".met"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs index f8189ac..f7abf81 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/QuestTracker.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text.RegularExpressions; using RynthCore.PluginSdk; @@ -8,6 +9,8 @@ namespace RynthCore.Plugin.RynthAi.Meta; internal sealed class QuestRecord { public string Key = ""; + /// Server-supplied description from /myquests (may be empty). + public string Description = ""; public int Solves; public int MaxSolves; public DateTime CompletedOn = DateTime.MinValue; @@ -24,6 +27,13 @@ internal sealed class QuestRecord return false; return !(MaxSolves == 1 && Solves <= 1); } + + /// Time until the flag can be solved again (zero when ready). + public TimeSpan TimeUntilReady() + { + var left = (CompletedOn + RepeatTime) - DateTime.UtcNow; + return left > TimeSpan.Zero ? left : TimeSpan.Zero; + } } /// @@ -44,21 +54,44 @@ internal sealed class QuestTracker private bool _refreshing; private bool _gotFirstQuest; + private bool _quietRefresh; private DateTime _lastLineTime; private DateTime _refreshStarted; public bool IsRefreshing => _refreshing; + /// The server answered that /myquests is not enabled. + public bool Disabled { get; private set; } + + /// UTC time the last refresh finished with data (MinValue = never). + public DateTime LastRefreshUtc { get; private set; } = DateTime.MinValue; + + /// Last refresh outcome text for the ILT Hub ("12 flags", "rate limited", ...). + public string LastStatus { get; private set; } = "not refreshed"; + + /// Number of cached flags. + public int Count => _flags.Count; + + /// Raised on the pump thread when a refresh ends. The ILT Hub reads Disabled and Count. + public event Action? RefreshCompleted; + public QuestTracker(RynthCoreHost host) => _host = host; /// /// Issues /myquests to the server to populate the quest flag cache. /// No-ops if already refreshing or InvokeChatParser is not available. /// - public void Refresh() + public void Refresh() => Refresh(quiet: false); + + /// + /// Issues /myquests. asks to report + /// those lines as eatable so the ILT Hub can hide its own poll. + /// + public void Refresh(bool quiet) { if (_refreshing || !_host.HasInvokeChatParser) return; + _quietRefresh = quiet; ExpectReply(); RefreshSent?.Invoke(); _host.InvokeChatParser("/myquests"); @@ -83,33 +116,43 @@ internal sealed class QuestTracker /// Feed every incoming chat line here. Quest lines are parsed and cached; /// terminal lines (empty list, rate limit, etc.) end the refresh early. /// - public void OnChatLine(string text) + public bool OnChatLine(string text) { if (!_refreshing) - return; + return false; - if (text.Contains("Quest list is empty") || - text.Contains("The command \"myquests\" is not currently enabled")) + if (text.Contains("Quest list is empty")) { - _refreshing = false; - return; + bool quiet = _quietRefresh; + Finish("quest list is empty", gotData: true); + return quiet; + } + + if (text.Contains("The command \"myquests\" is not currently enabled")) + { + Disabled = true; + bool quiet = _quietRefresh; + Finish("/myquests is disabled on this server", gotData: false); + return quiet; } if (text.Contains("This command may only be run once every")) { - _refreshing = false; - return; + bool quiet = _quietRefresh; + Finish("rate limited by the server (try again in a minute)", gotData: false); + return quiet; } var m = QuestLineRegex.Match(text); if (!m.Success) - return; + return false; _gotFirstQuest = true; _lastLineTime = DateTime.UtcNow; var rec = new QuestRecord(); rec.Key = m.Groups["key"].Value.ToLowerInvariant(); + rec.Description = m.Groups["description"].Value.Trim().Trim('"'); int.TryParse(m.Groups["solves"].Value, out rec.Solves); int.TryParse(m.Groups["maxSolves"].Value, out rec.MaxSolves); @@ -126,6 +169,7 @@ internal sealed class QuestTracker rec.RepeatTime = TimeSpan.FromSeconds(rt); _flags[rec.Key] = rec; + return _quietRefresh; } /// @@ -142,15 +186,32 @@ internal sealed class QuestTracker if (_gotFirstQuest) { if ((now - _lastLineTime).TotalSeconds >= 1.0) - _refreshing = false; + Finish($"{Count} flags", gotData: true); } else { if ((now - _refreshStarted).TotalSeconds >= 15.0) - _refreshing = false; + Finish("no reply from server", gotData: false); } } + private void Finish(string status, bool gotData) + { + _refreshing = false; + _quietRefresh = false; + LastStatus = status; + if (gotData) + { + Disabled = false; + LastRefreshUtc = DateTime.UtcNow; + } + try { RefreshCompleted?.Invoke(); } + catch (Exception ex) { _host.Log($"[RynthAi] QuestTracker RefreshCompleted threw: {ex.Message}"); } + } + + /// Copy of every cached record for the ILT Hub quest list. + public QuestRecord[] Snapshot() => _flags.Values.ToArray(); + /// Returns true if the key exists in the cached quest flag list. public bool HasFlag(string key) => _flags.ContainsKey(key.ToLowerInvariant()); diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs new file mode 100644 index 0000000..98cbc26 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs @@ -0,0 +1,286 @@ +// NavBreadcrumbTracker.cs — position sampling for the Navigation window: +// +// * Breadcrumb trail: where the character has walked (spacing / max points / teleport +// breaks), drawn by NavOverlayRenderer and exportable as a route ("backtrack"). +// * Route recording (UB-IT KeyStoreRecorder style): while LegacyUiSettings.IsRecordingNav +// is on, appends Point waypoints every RecordSpacingYards and, on a teleport, a Portal +// step for the portal selected just before it (plus an optional pause). +// +// Runs on the plugin tick thread. The render thread only reads the published trail array +// (copy-on-write), so no locks are needed. +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// One trail sample. Z is the raw world height (marker frame = Z, not Z/240). +internal readonly record struct NavCrumb(double NS, double EW, float Z, bool SegmentStart); + +internal sealed class NavBreadcrumbTracker +{ + /// A position jump larger than this between ticks is a teleport (engine uses the same 50 yd). + private const double TeleportYards = 50.0; + /// A portal selected longer ago than this isn't credited for a recorded teleport. + private const long PortalCreditMs = 20_000; + /// Recording autosaves to the route file every this many added waypoints. + private const int RecordAutosaveEvery = 10; + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + /// Object id → (name, Decal object class) when it is a portal, else null. + private readonly Func _describePortal; + private readonly Action _chat; + + // ── Trail (tick thread owns _crumbs; _snapshot is what the renderer reads) ── + private readonly List _crumbs = new(); + private NavCrumb[] _snapshot = Array.Empty(); + private bool _breakNext = true; + private double _trailYards; + + // ── Teleport detection ── + private double _lastNS = double.NaN, _lastEW, _lastZ; + private bool _wasPortaling; + + // ── Recording ── + private bool _recordingActive; + private double _recNS = double.NaN, _recEW; + private int _recAdded, _recSinceSave; + private (string Name, int Cls, double NS, double EW, double NavZ, long At)? _portalCandidate; + + public NavBreadcrumbTracker(RynthCoreHost host, LegacyUiSettings settings, + Func describePortal, Action chat) + { + _host = host; + _settings = settings; + _describePortal = describePortal; + _chat = chat; + } + + /// Current trail, oldest first (safe to read from the render thread). + public NavCrumb[] Trail => Volatile.Read(ref _snapshot); + /// Walked length of the trail (teleport jumps excluded), yards. + public double TrailYards => Volatile.Read(ref _trailYards); + /// Waypoints added by the current recording session. + public int RecordedCount => Volatile.Read(ref _recAdded); + + /// Clear request from the UI thread; applied on the next tick. + public void RequestClear() => Interlocked.Exchange(ref _clearRequested, 1); + private int _clearRequested; + + public void Tick() + { + var o = _settings.NavOverlay; + if (Interlocked.Exchange(ref _clearRequested, 0) == 1) ClearTrail(); + + // Portal space: no position worth recording, but remember we passed through it. + if (_host.HasIsPortaling && _host.IsPortaling()) + { + _wasPortaling = true; + return; + } + if (!NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) return; + if (!_host.TryGetPlayerPose(out uint cell, out _, out _, out float z, out _, out _, out _, out _)) return; + if ((cell >> 16) == 0) return; + + bool hadLast = !double.IsNaN(_lastNS); + bool teleported = _wasPortaling + || (hadLast && NavRouteEditing.DistanceYards(_lastNS, _lastEW, ns, ew) > TeleportYards); + _wasPortaling = false; + double preNS = _lastNS, preEW = _lastEW, preZ = _lastZ; + _lastNS = ns; _lastEW = ew; _lastZ = z; + + if (teleported) _breakNext = true; + + // While tracking is off, keep a break pending so the trail resumes as a new segment + // instead of joining across the untracked stretch. + if (o.TrackBreadcrumbs) SampleCrumb(ns, ew, z, o); + else _breakNext = true; + TickRecording(ns, ew, z, o, teleported && hadLast, preNS, preEW, preZ); + } + + // ═══════════════════════════════════════════════════════════════════ + // Breadcrumb trail + // ═══════════════════════════════════════════════════════════════════ + + private void SampleCrumb(double ns, double ew, float z, NavOverlaySettings o) + { + if (_crumbs.Count > 0 && !_breakNext) + { + var last = _crumbs[^1]; + double d = NavRouteEditing.DistanceYards(last.NS, last.EW, ns, ew); + if (d < o.BreadcrumbSpacingYards) return; + _trailYards += d; + } + _crumbs.Add(new NavCrumb(ns, ew, z, _breakNext || _crumbs.Count == 0)); + _breakNext = false; + + int over = _crumbs.Count - o.BreadcrumbMaxPoints; + if (over > 0) + { + _crumbs.RemoveRange(0, over); + if (_crumbs.Count > 0 && !_crumbs[0].SegmentStart) + _crumbs[0] = _crumbs[0] with { SegmentStart = true }; + _trailYards = MeasureTrail(_crumbs); + } + Volatile.Write(ref _snapshot, _crumbs.ToArray()); + } + + private void ClearTrail() + { + _crumbs.Clear(); + _trailYards = 0; + _breakNext = true; + Volatile.Write(ref _snapshot, Array.Empty()); + } + + private static double MeasureTrail(List crumbs) + { + double total = 0; + for (int i = 1; i < crumbs.Count; i++) + if (!crumbs[i].SegmentStart) + total += NavRouteEditing.DistanceYards(crumbs[i - 1].NS, crumbs[i - 1].EW, crumbs[i].NS, crumbs[i].EW); + return total; + } + + /// + /// Trail → waypoints (Z converted to nav units), thinned to . + /// builds a backtrack (newest first). Teleport breaks end the + /// export so the route never asks the bot to walk across a portal jump. + /// + public static List TrailToPoints(NavCrumb[] trail, double spacingYards, bool reverse) + { + var pts = new List(); + if (trail.Length == 0) return pts; + + // Newest unbroken segment only: from the last segment start to the end. + int start = 0; + for (int i = trail.Length - 1; i >= 0; i--) + if (trail[i].SegmentStart) { start = i; break; } + + NavCrumb? lastKept = null; + for (int i = start; i < trail.Length; i++) + { + var c = trail[i]; + bool isLast = i == trail.Length - 1; + if (lastKept is NavCrumb k && !isLast + && NavRouteEditing.DistanceYards(k.NS, k.EW, c.NS, c.EW) < spacingYards) + continue; + pts.Add(new NavPoint { Type = NavPointType.Point, NS = c.NS, EW = c.EW, Z = c.Z / NavCoordinateHelper.NavZScale }); + lastKept = c; + } + if (reverse) pts.Reverse(); + return pts; + } + + // ═══════════════════════════════════════════════════════════════════ + // Route recording + // ═══════════════════════════════════════════════════════════════════ + + private void TickRecording(double ns, double ew, float z, NavOverlaySettings o, + bool teleported, double preNS, double preEW, double preZ) + { + if (!_settings.IsRecordingNav) + { + if (_recordingActive) StopRecordingSession(); + return; + } + if (!_recordingActive) + { + _recordingActive = true; + _recNS = double.NaN; + _recAdded = 0; + _recSinceSave = 0; + _portalCandidate = null; + RynthLog.Write(LogCat.Navigation, "[NavRecord] recording started."); + } + + TrackPortalSelection(); + + if (teleported) + { + // Portal used just before the jump → Portal step (+ pause); the arrival point + // then records immediately because _recNS is reset. + if (o.RecordPortals && _portalCandidate is { } pc && Environment.TickCount64 - pc.At <= PortalCreditMs) + { + AddRecorded(new NavPoint + { + Type = NavPointType.PortalNPC, + NS = preNS, EW = preEW, Z = preZ / NavCoordinateHelper.NavZScale, + TargetName = pc.Name, ObjectClass = pc.Cls, + PortalExitNS = pc.NS, PortalExitEW = pc.EW, PortalExitZ = pc.NavZ, + }); + if (o.RecordPauseAfterPortalMs > 0) + AddRecorded(new NavPoint { Type = NavPointType.Pause, NS = ns, EW = ew, Z = z / NavCoordinateHelper.NavZScale, PauseTimeMs = o.RecordPauseAfterPortalMs }); + _chat($"[RynthAi] Nav record: added Portal step '{pc.Name}'."); + } + else + { + _chat("[RynthAi] Nav record: teleport detected — add a Portal or Recall step for it if the route needs one."); + } + _portalCandidate = null; + _recNS = double.NaN; + } + + if (!double.IsNaN(_recNS) && NavRouteEditing.DistanceYards(_recNS, _recEW, ns, ew) < o.RecordSpacingYards) + return; + + AddRecorded(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / NavCoordinateHelper.NavZScale }); + _recNS = ns; + _recEW = ew; + } + + /// Remembers the last selected portal (name, class, position) for the teleport step. + private void TrackPortalSelection() + { + if (!_host.HasGetSelectedItemId) return; + uint sel = _host.GetSelectedItemId(); + if (sel == 0) return; + if (_portalCandidate is { } cur && Environment.TickCount64 - cur.At < 1000) return; // refresh ~1/s + if (_describePortal(sel) is not { } info) return; + + double pns = 0, pew = 0, pz = 0; + if (_host.HasGetObjectPosition + && _host.TryGetObjectPosition(sel, out uint pcell, out float ox, out float oy, out float oz) + && NavCoordinateHelper.TryConvertPoseToCoords(pcell, ox, oy, out pns, out pew)) + pz = oz / NavCoordinateHelper.NavZScale; + _portalCandidate = (info.Name, info.ObjectClass, pns, pew, pz, Environment.TickCount64); + } + + private void AddRecorded(NavPoint p) + { + NavRouteEditing.Apply(_settings, list => { list.Add(p); return list; }); + Interlocked.Increment(ref _recAdded); + if (++_recSinceSave >= RecordAutosaveEvery) + { + _recSinceSave = 0; + SaveRouteFile(); + } + } + + /// Session teardown: saves a recording in progress (no chat — the session is ending). + public void Shutdown() + { + if (_recordingActive) StopRecordingSession(announce: false); + } + + private void StopRecordingSession(bool announce = true) + { + _recordingActive = false; + _portalCandidate = null; + SaveRouteFile(); + RynthLog.Write(LogCat.Navigation, $"[NavRecord] recording stopped ({_recAdded} waypoints added)."); + if (announce) + _chat($"[RynthAi] Nav record stopped: {_recAdded} waypoints added" + + (string.IsNullOrEmpty(_settings.CurrentNavPath) ? " (route not saved yet — use Save As)." : " and saved.")); + } + + private void SaveRouteFile() + { + if (string.IsNullOrEmpty(_settings.CurrentNavPath)) return; + try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); } + catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"[NavRecord] save failed: {ex.Message}"); } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs index 4f39261..9343333 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavMarkerRenderer.cs @@ -123,6 +123,10 @@ internal sealed class NavMarkerRenderer playerNS = playerEW = 0.0; ringRadius = 0f; heightOffset = 0f; + // Route overlay switched off (Nav panel / "/ra navoverlay off"): no rings or lines. + if (!_settings.NavOverlay.ShowRouteMarkers) + return false; + var r = _settings.CurrentRoute; if (r?.Points == null || r.Points.Count == 0) return false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs new file mode 100644 index 0000000..8b98a0c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/NavOverlayRenderer.cs @@ -0,0 +1,354 @@ +// NavOverlayRenderer.cs — on-screen navigation aids on top of NavMarkerRenderer's route rings: +// +// * Waypoint HUD: small movable window with the active waypoint, distance, a direction +// arrow relative to the character's facing, the next step, remaining route length, +// breadcrumb / recording status. +// * Waypoint labels: "#12 34yd" over the next N travel points in the 3D view. +// * Guide line: player → active waypoint (UB-IT world-overlay "breadcrumb" line). +// * Breadcrumb trail: NavBreadcrumbTracker samples drawn on the ground, fading with age. +// +// 3D geometry (guide line, trail) is submitted from OnTick through the engine's Nav3D buffer +// (shared budget: 512 lines across all plugins), with an ImGui projected fallback when the +// engine has no Nav3D API. HUD and labels are ImGui and need the overlay. +using System; +using System.IO; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +internal sealed class NavOverlayRenderer +{ + /// Most trail segments submitted per frame (route markers use up to 128 lines). + private const int MaxTrailLines = 200; + /// Label text sits this far above the waypoint ring, world units. + private const float LabelLift = 1.2f; + + private readonly RynthCoreHost _host; + private readonly LegacyUiSettings _settings; + private readonly NavBreadcrumbTracker _trail; + + public NavOverlayRenderer(RynthCoreHost host, LegacyUiSettings settings, NavBreadcrumbTracker trail) + { + _host = host; + _settings = settings; + _trail = trail; + } + + /// Player frame shared by every pass (marker world frame: X=EW, Y=up, Z=NS). + private readonly record struct Frame(double NS, double EW, float Px, float Py, float Pz, float HeadingDeg); + + private bool TryGetFrame(out Frame f) + { + f = default; + if (_host.HasIsPortaling && _host.IsPortaling()) return false; + if (!NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) return false; + if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz, + out float qw, out _, out _, out float qz)) return false; + if ((cell >> 16) == 0) return false; + // Physics yaw (CCW from north) → compass heading (0 = north, clockwise), as NavigationEngine. + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + f = new Frame(ns, ew, px, py, pz, (float)((-yaw + 720.0) % 360.0)); + return true; + } + + private Vector3 ToWorld(in Frame f, double ns, double ew, float worldY) + => new(f.Px + (float)((ew - f.EW) * NavRouteEditing.NavToYards), worldY, + f.Py + (float)((ns - f.NS) * NavRouteEditing.NavToYards)); + + private float WaypointWorldY(NavPoint p) => (float)(p.Z * NavCoordinateHelper.NavZScale) + _settings.NavHeightOffset; + + /// Active waypoint when it is a travel Point, else null. + private NavPoint? ActivePoint(out int index) + { + var pts = _settings.CurrentRoute?.Points; + index = _settings.ActiveNavIndex; + if (pts == null || index < 0 || index >= pts.Count) return null; + return pts[index]; + } + + // ═══════════════════════════════════════════════════════════════════ + // 3D (tick thread) + // ═══════════════════════════════════════════════════════════════════ + + /// Guide line + breadcrumb trail into the Nav3D buffer. Call from OnTick. + public void SubmitNav3D() + { + if (!_host.HasNav3D) return; + try + { + if (!TryGetFrame(out var f)) return; + var o = _settings.NavOverlay; + float lineThick = _settings.NavLineThickness * 0.01f; + + if (o.TrailVisible()) + ForEachTrailSegment(f, o, (a, b, fade) => + _host.Nav3DAddLine(a.X, a.Y, a.Z, b.X, b.Y, b.Z, lineThick * 0.7f, + NavOverlaySettings.ScaleAlpha(o.ColorBreadcrumb, fade))); + + if (o.GuideLineVisible() && ActivePoint(out _) is { Type: NavPointType.Point } ap) + { + Vector3 me = new(f.Px, f.Pz + _settings.NavHeightOffset, f.Py); + Vector3 to = ToWorld(f, ap.NS, ap.EW, WaypointWorldY(ap)); + _host.Nav3DAddLine(me.X, me.Y, me.Z, to.X, to.Y, to.Z, lineThick * 0.8f, o.ColorGuide); + } + } + catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"NavOverlay(3D): {ex.Message}"); } + } + + /// + /// Newest-first walk of the trail within draw range, capped at ; + /// no segment crosses a teleport break. fade is 1 for the newest segment. + /// + private void ForEachTrailSegment(in Frame f, NavOverlaySettings o, Action draw) + { + NavCrumb[] trail = _trail.Trail; + if (trail.Length < 2) return; + float lift = _settings.NavHeightOffset + 0.03f; + int drawn = 0, total = Math.Min(trail.Length - 1, MaxTrailLines); + for (int i = trail.Length - 1; i >= 1 && drawn < MaxTrailLines; i--) + { + NavCrumb b = trail[i], a = trail[i - 1]; + if (b.SegmentStart) continue; + if (NavRouteEditing.DistanceYards(f.NS, f.EW, b.NS, b.EW) > o.BreadcrumbDrawRangeYards) continue; + float fade = o.BreadcrumbFade ? 1f - 0.8f * drawn / Math.Max(1, total) : 1f; + draw(ToWorld(f, a.NS, a.EW, a.Z + lift), ToWorld(f, b.NS, b.EW, b.Z + lift), fade); + drawn++; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ImGui (render thread) + // ═══════════════════════════════════════════════════════════════════ + + /// HUD window, waypoint labels, and the projected fallback for trail/guide. Call inside an ImGui frame. + public void Render() + { + try + { + var o = _settings.NavOverlay; + var route = _settings.CurrentRoute; + bool hasRoute = route?.Points is { Count: > 0 }; + bool navigating = _settings.IsMacroRunning && _settings.EnableNavigation; + bool wantFallback3D = !_host.HasNav3D && (o.TrailVisible() || o.GuideLineVisible()); + bool wantLabels = o.LabelsVisible() && hasRoute; + bool wantHud = o.ShowHud && (hasRoute || _settings.IsRecordingNav) && (!o.HudOnlyWhileNavigating || navigating); + if (!wantFallback3D && !wantLabels && !wantHud) return; + if (!TryGetFrame(out var f)) return; + + if (wantFallback3D || wantLabels) RenderWorldOverlay(f, o, wantLabels, wantFallback3D); + if (wantHud) RenderHud(f, o); + } + catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"NavOverlay(ImGui): {ex.Message}"); } + } + + private void RenderWorldOverlay(in Frame f, NavOverlaySettings o, bool labels, bool fallback3D) + { + if (!_host.HasWorldToScreen || !_host.HasGetViewportSize) return; + if (!_host.TryGetViewportSize(out uint vpW, out uint vpH) || vpW == 0 || vpH == 0) return; + + ImGui.SetNextWindowPos(Vector2.Zero); + ImGui.SetNextWindowSize(new Vector2(vpW, vpH)); + ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u); + ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = true; + bool visible = ImGui.Begin("##NavWaypointOverlay", ref open, + ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | + ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoCollapse | + ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoBringToFrontOnFocus | + ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoSavedSettings); + try + { + if (!visible) return; + var dl = ImGui.GetWindowDrawList(); + float thick = Math.Max(1f, _settings.NavLineThickness * 0.5f); + var frame = f; + + if (fallback3D && o.TrailVisible()) + { + ForEachTrailSegment(f, o, (a, b, fade) => + { + if (Project(a, out var sa) && Project(b, out var sb)) + dl.AddLine(sa, sb, NavOverlaySettings.ArgbToImGui(NavOverlaySettings.ScaleAlpha(o.ColorBreadcrumb, fade)), thick); + }); + } + if (fallback3D && o.GuideLineVisible() && ActivePoint(out _) is { Type: NavPointType.Point } ap + && Project(new Vector3(f.Px, f.Pz + _settings.NavHeightOffset, f.Py), out var sMe) + && Project(ToWorld(frame, ap.NS, ap.EW, WaypointWorldY(ap)), out var sTo)) + dl.AddLine(sMe, sTo, NavOverlaySettings.ArgbToImGui(o.ColorGuide), thick); + + if (labels) DrawWaypointLabels(dl, f, o); + } + finally + { + ImGui.End(); + ImGui.PopStyleVar(2); + ImGui.PopStyleColor(); + } + } + + private bool Project(Vector3 w, out Vector2 s) + { + bool ok = _host.WorldToScreen(w.X, w.Y, w.Z, out float sx, out float sy); + s = new Vector2(sx, sy); + return ok; + } + + /// "#12 34yd" over the active travel point and the next ones in route order. + private void DrawWaypointLabels(ImDrawListPtr dl, in Frame f, NavOverlaySettings o) + { + var route = _settings.CurrentRoute; + var pts = route.Points; + int n = pts.Count; + int idx = Math.Clamp(_settings.ActiveNavIndex, 0, n - 1); + bool circular = route.RouteType == NavRouteType.Circular; + uint activeCol = NavOverlaySettings.ArgbToImGui(o.ColorActiveRing); + uint nextCol = NavOverlaySettings.ArgbToImGui(o.ColorRing); + uint bg = 0xB0000000; + + int labelled = 0; + for (int step = 0; step < n && labelled < o.LabelsAhead; step++) + { + int i = circular ? (idx + step) % n : idx + step; + if (i >= n) break; + var p = pts[i]; + if (p.Type != NavPointType.Point) continue; + + Vector3 w = ToWorld(f, p.NS, p.EW, WaypointWorldY(p) + LabelLift); + if (!Project(w, out var s)) { labelled++; continue; } + + double yd = NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW); + string text = $"#{i} {yd:F0}yd"; + Vector2 size = ImGui.CalcTextSize(text); + Vector2 tl = s - new Vector2(size.X * 0.5f + 4, size.Y + 2); + dl.AddRectFilled(tl, tl + size + new Vector2(8, 4), bg, 3f); + dl.AddText(tl + new Vector2(4, 2), i == _settings.ActiveNavIndex ? activeCol : nextCol, text); + labelled++; + } + } + + private void RenderHud(in Frame f, NavOverlaySettings o) + { + ImGui.SetNextWindowPos(new Vector2(20, 220), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowBgAlpha(0.65f); + if (!ImGui.Begin("Nav HUD##RynthAiNavHud", ref o.ShowHud, + ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | + ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav)) + { + ImGui.End(); + return; + } + + var route = _settings.CurrentRoute; + var pts = route.Points; + string name = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "(unsaved)" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath); + ImGui.TextColored(new Vector4(1f, 0.85f, 0.3f, 1f), $"{name} [{route.RouteType}]"); + if (_settings.IsRecordingNav) + { + ImGui.SameLine(); + ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 1f), $"REC +{_trail.RecordedCount}"); + } + + int idx = _settings.ActiveNavIndex; + if (pts.Count > 0 && idx >= 0 && idx < pts.Count) + { + var p = pts[idx]; + bool travel = p.Type == NavPointType.Point; + ImGui.BeginGroup(); + ImGui.Text($"WP {idx}/{pts.Count - 1} {TypeLabel(p)}"); + if (travel) + { + double yd = NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW); + double dz = (p.Z * NavCoordinateHelper.NavZScale) - f.Pz; + ImGui.Text(Math.Abs(dz) >= 3 ? $"{yd:F1} yd ({(dz > 0 ? "up" : "down")} {Math.Abs(dz):F0})" : $"{yd:F1} yd"); + } + else + { + ImGui.TextDisabled(p.ToString()); + } + int ni = NextIndex(route, idx); + if (ni >= 0) ImGui.TextDisabled($"Next: [{ni}] {pts[ni]}"); + double remain = RemainingYards(route, idx, f); + if (remain > 0) ImGui.TextDisabled(route.RouteType == NavRouteType.Circular ? $"Loop: {remain:F0} yd" : $"Remaining: ~{remain:F0} yd"); + ImGui.EndGroup(); + + if (travel) + { + ImGui.SameLine(); + double bearing = Math.Atan2(p.EW - f.EW, p.NS - f.NS) * (180.0 / Math.PI); + DrawArrow((float)(bearing - f.HeadingDeg), NavOverlaySettings.ArgbToImGui(o.ColorGuide)); + } + } + else if (pts.Count == 0) + { + ImGui.TextDisabled("Route is empty."); + } + + if (!string.IsNullOrEmpty(_settings.NavStatusLine)) + ImGui.TextColored(_settings.NavIsStuck ? new Vector4(0.91f, 0.70f, 0.20f, 1f) : new Vector4(0.6f, 0.75f, 0.6f, 1f), + _settings.NavStatusLine); + if (o.TrackBreadcrumbs) + ImGui.TextDisabled($"Trail: {_trail.Trail.Length} pts, {_trail.TrailYards:F0} yd"); + ImGui.End(); + } + + /// Direction arrow in a 36 px box; 0 = straight ahead, clockwise. + private static void DrawArrow(float relDeg, uint color) + { + const float Box = 36f; + Vector2 tl = ImGui.GetCursorScreenPos(); + ImGui.Dummy(new Vector2(Box, Box)); + var dl = ImGui.GetWindowDrawList(); + Vector2 c = tl + new Vector2(Box * 0.5f, Box * 0.5f); + dl.AddCircle(c, Box * 0.48f, 0x60FFFFFF, 24, 1.5f); + + double a = relDeg * Math.PI / 180.0; + var dir = new Vector2((float)Math.Sin(a), -(float)Math.Cos(a)); + var perp = new Vector2(-dir.Y, dir.X); + dl.AddTriangleFilled(c + dir * 14f, c - dir * 8f + perp * 7f, c - dir * 8f - perp * 7f, color); + } + + private static string TypeLabel(NavPoint p) => p.Type switch + { + NavPointType.Point => "Point", + NavPointType.Recall => "Recall", + NavPointType.Pause => "Pause", + NavPointType.Chat => "Chat", + NavPointType.OpenVendor => "Vendor", + NavPointType.PortalNPC => "Portal", + NavPointType.Npc => "NPC", + _ => p.Type.ToString(), + }; + + /// Following waypoint in route order (wraps on circular), or -1 at the end. + private static int NextIndex(NavRouteParser route, int idx) + { + int n = route.Points.Count; + if (idx + 1 < n) return idx + 1; + return route.RouteType == NavRouteType.Circular && n > 1 ? 0 : -1; + } + + /// Player → active point → … end of route (one lap for circular), walking legs only. + private static double RemainingYards(NavRouteParser route, int idx, in Frame f) + { + var pts = route.Points; + int n = pts.Count; + if (idx < 0 || idx >= n) return 0; + double total = 0; + NavPoint? prev = null; + int steps = route.RouteType == NavRouteType.Circular ? n : n - idx; + for (int s = 0; s < steps; s++) + { + var p = pts[(idx + s) % n]; + if (p.Type != NavPointType.Point) { prev = null; continue; } + total += prev == null + ? (s == 0 ? NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW) : 0) + : NavRouteEditing.DistanceYards(prev.NS, prev.EW, p.NS, p.EW); + prev = p; + } + return total; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 2487766..2539317 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -65,6 +65,19 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); + // Local ImGui windows (ILT Hub, HUDs, translator, item info, nav overlay). The engine + // calls this when the export exists; the main panels stay on the engine side. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() => Runtime.OnRender(); + + /// Engine calls this instead of RynthPluginRender while its ImGui shell is off. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderOverlay", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void RenderOverlay() + { + try { Runtime.Plugin?.OnRenderOverlay(); } + catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ } + } + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); @@ -626,6 +639,56 @@ public static unsafe class PluginExports } } + private static IntPtr _progressionPtr = IntPtr.Zero; + + /// + /// Skills panel Progression tab (ILT augmentations / enlightenment). Same contract as + /// RynthPluginGetPatrolInfoJson: one static buffer, valid until the next call; the engine + /// polls it from its pump thread only. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetProgressionJson() + { + try + { + string json = Runtime.Plugin?.BuildProgressionJson() ?? "{\"available\":false}"; + IntPtr newPtr = Marshal.StringToHGlobalAnsi(json); + IntPtr oldPtr = Interlocked.Exchange(ref _progressionPtr, newPtr); + if (oldPtr != IntPtr.Zero) + Marshal.FreeHGlobal(oldPtr); + return newPtr; + } + catch + { + return IntPtr.Zero; + } + } + + private static IntPtr _charmsPtr = IntPtr.Zero; + + /// + /// Settings panel Charms Tracking tab (ACECustom registry charms: acquired / active / server + /// state). Same contract as RynthPluginGetProgressionJson: one static buffer, valid until the + /// next call; the engine polls it from its pump thread only. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetCharmsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetCharmsJson() + { + try + { + string json = Runtime.Plugin?.BuildCharmsJson() ?? "{\"available\":false}"; + IntPtr newPtr = Marshal.StringToHGlobalAnsi(json); + IntPtr oldPtr = Interlocked.Exchange(ref _charmsPtr, newPtr); + if (oldPtr != IntPtr.Zero) + Marshal.FreeHGlobal(oldPtr); + return newPtr; + } + catch + { + return IntPtr.Zero; + } + } + // ── Items bridge (engine-side Avalonia ItemsPanel) ────────────────────── private static IntPtr _itemsPtr = IntPtr.Zero; diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs new file mode 100644 index 0000000..501a800 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankProfileImporter.cs @@ -0,0 +1,329 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.ProfileImport; + +/// +/// Copies VirindiTank-style loot files (.utl) and merges Rynth-format monster JSON found under common VT install paths. +/// +public static class VirindiTankProfileImporter +{ + /// Standard VirindiTank install locations (wiki / community bundles). + public static IReadOnlyList DefaultVirindiTankRoots() + { + var list = new List + { + @"C:\Games\VirindiPlugins\VirindiTank", + }; + + try + { + string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + if (!string.IsNullOrEmpty(docs)) + { + list.Add(Path.Combine(docs, "VirindiPlugins", "VirindiTank")); + list.Add(Path.Combine(docs, "Decal", "VirindiPlugins", "VirindiTank")); + } + } + catch { } + + try + { + string loc = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (!string.IsNullOrEmpty(loc)) + list.Add(Path.Combine(loc, "VirindiPlugins", "VirindiTank")); + } + catch { } + + return list.Distinct(StringComparer.OrdinalIgnoreCase).Where(Directory.Exists).ToList(); + } + + public sealed class Result + { + public int LootFilesCopied; + public int MonsterRulesAdded; + /// Full paths of .utl files copied into the Rynth loot folder this run (for activating loot). + public List CopiedLootDestPaths { get; } = new(); + public List LogLines { get; } = new(); + } + + /// RynthAi LootProfiles folder. + /// When true, deserialized rules are merged into . + public static Result Import(string lootDestDir, LegacyUiSettings settings, bool mergeMonsterRules) + { + var result = new Result(); + if (string.IsNullOrEmpty(lootDestDir)) + { + result.LogLines.Add("Loot destination folder is empty."); + return result; + } + + try { Directory.CreateDirectory(lootDestDir); } + catch (Exception ex) + { + result.LogLines.Add($"Cannot create loot folder: {ex.Message}"); + return result; + } + + var seenSrc = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string root in DefaultVirindiTankRoots()) + { + foreach (string utl in EnumerateFilesRecursive(root, "*.utl", maxDepth: 6)) + { + if (!seenSrc.Add(utl)) continue; + string baseName = Path.GetFileName(utl); + string dest = Path.Combine(lootDestDir, baseName); + int suffix = 0; + while (File.Exists(dest)) + { + suffix++; + dest = Path.Combine(lootDestDir, $"VT_{suffix}_{baseName}"); + } + + try + { + File.Copy(utl, dest, overwrite: false); + result.LootFilesCopied++; + result.CopiedLootDestPaths.Add(dest); + result.LogLines.Add($"Loot: {baseName} -> {Path.GetFileName(dest)}"); + } + catch (Exception ex) + { + result.LogLines.Add($"Loot skip {baseName}: {ex.Message}"); + } + } + + if (mergeMonsterRules) + { + foreach (string jsonPath in EnumerateFilesRecursive(root, "monsters.json", maxDepth: 8)) + TryMergeMonsterFile(jsonPath, settings, result); + + foreach (string usdPath in EnumerateFilesRecursive(root, "*.usd", maxDepth: 6)) + TryMergeUsdMyMonstersScf(usdPath, settings, result); + } + } + + if (result.LootFilesCopied == 0 && result.MonsterRulesAdded == 0) + result.LogLines.Add("No .utl loot files, Rynth monsters.json, or text MyMonsters .usd found under VirindiTank paths."); + + return result; + } + + /// SQLite-backed VT profiles are skipped here; use Monster Editor import for those. + private static bool LooksLikeSqliteFile(string path) + { + try + { + using var fs = File.OpenRead(path); + var hdr = new byte[16]; + int n = fs.Read(hdr, 0, hdr.Length); + const string sig = "SQLite format 3\0"; + if (n < sig.Length) + return false; + for (int i = 0; i < sig.Length; i++) + { + if (hdr[i] != sig[i]) + return false; + } + + return true; + } + catch + { + return false; + } + } + + /// Text SCF .usd with MyMonsters — same subset as Monster Editor import for the current character merge. + private static void TryMergeUsdMyMonstersScf(string usdPath, LegacyUiSettings settings, Result result) + { + if (string.IsNullOrWhiteSpace(usdPath) || !File.Exists(usdPath)) + return; + if (LooksLikeSqliteFile(usdPath)) + { + result.LogLines.Add($"Monsters: skip SQLite .usd (use Monster Editor): {Path.GetFileName(usdPath)}"); + return; + } + + string allText; + try + { + allText = File.ReadAllText(usdPath, Encoding.UTF8); + } + catch (Exception ex) + { + result.LogLines.Add($"Monsters: skip .usd read {Path.GetFileName(usdPath)}: {ex.Message}"); + return; + } + + var tmp = new List(); + if (!VirindiTankUsdMyMonstersScfParser.TryParseMyMonsters(allText, tmp, out string? note) || tmp.Count == 0) + return; + + int addedBefore = result.MonsterRulesAdded; + MergeVtMonsterRows(tmp, settings, result); + int newNamed = result.MonsterRulesAdded - addedBefore; + result.LogLines.Add( + $"Monsters: VT MyMonsters from {Path.GetFileName(usdPath)} — parsed {tmp.Count} row(s), +{newNamed} new rule(s).{(string.IsNullOrEmpty(note) ? "" : " " + note)}"); + } + + /// Merges VT-style rows into like Monster Editor external import. + private static void MergeVtMonsterRows(IReadOnlyList src, LegacyUiSettings settings, Result result) + { + settings.EnsureDefaultRule(); + List rules = settings.MonsterRules; + + MonsterRule? srcDefault = src.FirstOrDefault(x => x.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + if (srcDefault != null && rules.Count > 0 && rules[0].Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) + CopyCombatOntoDefault(rules[0], srcDefault); + + var nameSet = new HashSet(rules.Select(x => x.Name), StringComparer.OrdinalIgnoreCase); + var exprSet = new HashSet( + rules.Where(x => !string.IsNullOrWhiteSpace(x.MatchExpression)).Select(x => x.MatchExpression), + StringComparer.Ordinal); + + foreach (MonsterRule row in src) + { + if (row.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) + continue; + + if (!string.IsNullOrEmpty(row.Name)) + { + if (nameSet.Contains(row.Name)) + continue; + } + else if (!string.IsNullOrEmpty(row.MatchExpression)) + { + if (exprSet.Contains(row.MatchExpression)) + continue; + } + else + { + continue; + } + + var c = CloneMonsterRule(row); + if (!string.IsNullOrEmpty(c.Name)) + { + if (!nameSet.Add(c.Name)) + continue; + } + + if (!string.IsNullOrEmpty(c.MatchExpression)) + exprSet.Add(c.MatchExpression); + + rules.Add(c); + result.MonsterRulesAdded++; + } + } + + private static void CopyCombatOntoDefault(MonsterRule dst, MonsterRule src) + { + dst.Category = src.Category; + dst.MatchExpression = src.MatchExpression; + dst.Priority = src.Priority; + dst.DamageType = src.DamageType; + dst.WeaponId = src.WeaponId; + dst.Fester = src.Fester; + dst.Broadside = src.Broadside; + dst.GravityWell = src.GravityWell; + dst.Imperil = src.Imperil; + dst.Yield = src.Yield; + dst.Vuln = src.Vuln; + dst.UseArc = src.UseArc; + dst.UseBolt = src.UseBolt; + dst.UseRing = src.UseRing; + dst.UseStreak = src.UseStreak; + dst.ExVuln = src.ExVuln; + dst.OffhandId = src.OffhandId; + dst.PreferredAmmoItemId = src.PreferredAmmoItemId; + dst.PetDamage = src.PetDamage; + } + + private static MonsterRule CloneMonsterRule(MonsterRule row) => + new() + { + Name = row.Name, + Category = row.Category, + MatchExpression = row.MatchExpression, + Priority = row.Priority, + DamageType = row.DamageType, + WeaponId = row.WeaponId, + Fester = row.Fester, + Broadside = row.Broadside, + GravityWell = row.GravityWell, + Imperil = row.Imperil, + Yield = row.Yield, + Vuln = row.Vuln, + UseArc = row.UseArc, + UseBolt = row.UseBolt, + UseRing = row.UseRing, + UseStreak = row.UseStreak, + ExVuln = row.ExVuln, + OffhandId = row.OffhandId, + PreferredAmmoItemId = row.PreferredAmmoItemId, + PetDamage = row.PetDamage, + }; + + private static void TryMergeMonsterFile(string jsonPath, LegacyUiSettings settings, Result result) + { + try + { + string json = File.ReadAllText(jsonPath); + var imported = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList); + if (imported == null || imported.Count == 0) return; + + int added = 0; + foreach (var rule in imported) + { + if (string.IsNullOrWhiteSpace(rule.Name)) continue; + if (rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) continue; + if (settings.MonsterRules.Any(m => m.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase))) + continue; + settings.MonsterRules.Add(rule); + added++; + } + + if (added > 0) + { + result.MonsterRulesAdded += added; + result.LogLines.Add($"Monsters: merged {added} rule(s) from {Path.GetFileName(jsonPath)}"); + } + } + catch (Exception ex) + { + result.LogLines.Add($"Monsters skip {jsonPath}: {ex.Message}"); + } + } + + private static IEnumerable EnumerateFilesRecursive(string root, string pattern, int maxDepth) + { + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) yield break; + var stack = new Stack<(string Path, int Depth)>(); + stack.Push((root, 0)); + while (stack.Count > 0) + { + var (dir, depth) = stack.Pop(); + IEnumerable files; + try { files = Directory.EnumerateFiles(dir, pattern); } + catch { continue; } + + foreach (string f in files) + yield return f; + + if (depth >= maxDepth) continue; + + IEnumerable subdirs; + try { subdirs = Directory.EnumerateDirectories(dir); } + catch { continue; } + + foreach (string sub in subdirs) + stack.Push((sub, depth + 1)); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs new file mode 100644 index 0000000..cd73ec1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs @@ -0,0 +1,339 @@ +// Line-oriented uTank2 SCF .usd MyMonsters table — logic mirrors Tools/RynthCore.MonsterEditor/VirindiTankUsdTextScfParser.cs +// for LegacyUi.MonsterRule. If VT changes the SCF layout, update both files together. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi.ProfileImport; + +/// Parses VirindiTank text-format .usd files that contain a MyMonsters SCF block. +internal static class VirindiTankUsdMyMonstersScfParser +{ + /// Returns false if the file is not SCF MyMonsters (e.g. SQLite binary profile). + public static bool TryParseMyMonsters(string allText, List outList, out string? note) + { + outList.Clear(); + note = null; + if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0) + return false; + + string[] L = allText + .Split(new[] { "\r\n", "\n" }, StringSplitOptions.None) + .Select(s => s.Trim()) + .ToArray(); + if (L.Length < 8) + { + note = "File too short."; + return false; + } + + int idx = 0; + for (; idx < L.Length; idx++) + if (L[idx] == "MyMonsters") + break; + if (idx >= L.Length) + { + note = "MyMonsters not found."; + return false; + } + + idx++; + if (!int.TryParse(L[idx], out int colCount) || colCount < 1) + { + note = "MyMonsters: bad column count."; + return false; + } + + idx += 1 + colCount * 2; + if (idx >= L.Length) + { + note = "MyMonsters: truncated after header."; + return false; + } + + if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0) + { + note = "MyMonsters: bad row count."; + return false; + } + + idx++; + if (rowCount == 0) + { + note = "MyMonsters has no rows."; + return false; + } + + if (colCount < 4 + 3) + { + note = "MyMonsters: column count too small."; + return false; + } + + int nBool = colCount - 4 - 3; + + for (int r = 0; r < rowCount; r++) + { + if (idx + 1 >= L.Length) + { + note = $"No data for row {r + 1} (early EOF)."; + return outList.Count > 0; + } + + if (!T(L, "s", ref idx)) + { + note = RowErr(r, "s"); + return outList.Count > 0; + } + + if (!ValStr(L, ref idx, out string raw)) + { + note = RowErr(r, "name"); + return outList.Count > 0; + } + + if (!T(L, "i", ref idx)) + { + note = RowErr(r, "i ap"); + return outList.Count > 0; + } + + if (!ValInt(L, ref idx, out int ap, out int err) || err != 0) + { + note = RowErr(r, "ap int"); + return outList.Count > 0; + } + + if (!T(L, "i", ref idx)) + { + note = RowErr(r, "i dt"); + return outList.Count > 0; + } + + if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0) + { + note = RowErr(r, "dt int"); + return outList.Count > 0; + } + + if (!T(L, "i", ref idx)) + { + note = RowErr(r, "i wep"); + return outList.Count > 0; + } + + if (!ValInt(L, ref idx, out int wep, out err) || err != 0) + { + note = RowErr(r, "wep int"); + return outList.Count > 0; + } + + if (nBool < 14) + { + note = "Expected at least 14 bool columns in mob row."; + return outList.Count > 0; + } + + if (nBool < 1) + { + note = "nBool<1."; + return false; + } + + var b = new bool[nBool]; + for (int k = 0; k < nBool; k++) + { + if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k])) + { + note = RowErr(r, $"b{k}"); + return outList.Count > 0; + } + } + + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0) + { + note = RowErr(r, "sec vuln int"); + return outList.Count > 0; + } + + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0) + { + note = RowErr(r, "offh int"); + return outList.Count > 0; + } + + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0) + { + note = RowErr(r, "pet int"); + return outList.Count > 0; + } + + outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet)); + } + + if (outList.Count == 0) + { + note = "No rows were parsed from MyMonsters."; + return false; + } + + return true; + } + + private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what})."; + + private static bool T(string[] L, string t, ref int i) + { + if (i >= L.Length || L[i] != t) + return false; + i++; + return true; + } + + private static bool ValStr(string[] L, ref int i, out string s) + { + s = ""; + if (i >= L.Length) + return false; + s = L[i++]; + return true; + } + + private static bool ValInt(string[] L, ref int i, out int v, out int err) + { + err = 0; + v = 0; + if (i >= L.Length) + { + err = 1; + return false; + } + + if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) && + !int.TryParse(L[i], out v)) + { + err = 1; + return false; + } + + i++; + return true; + } + + private static bool ValBool(string[] L, ref int i, out bool b) + { + b = false; + if (i >= L.Length) + return false; + string t = L[i++]; + if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase)) + { + b = true; + return true; + } + + if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase)) + { + b = false; + return true; + } + + return false; + } + + private static MonsterRule MakeRule(string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet) + { + string n = Nm(raw); + if (b.Length < 14) + b = Pad(b, 14); + bool i = b[0], v = b[1], y = b[2], gW = b[3]; + bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7]; + bool strk = b[13]; + + return new MonsterRule + { + Name = n, + Priority = ap, + DamageType = MapDmg(vtDmg), + WeaponId = WepId(wep), + Imperil = i, + Vuln = v, + Yield = y, + GravityWell = gW, + UseBolt = useBolt, + UseRing = useRing, + Broadside = broad, + Fester = fest, + UseStreak = strk, + ExVuln = "None", + OffhandId = WepId(ofh), + PetDamage = MapPet(pet, sev), + }; + } + + private static bool[] Pad(bool[] b, int min) + { + if (b.Length >= min) + return b; + var r = new bool[min]; + for (int i = 0; i < b.Length; i++) + r[i] = b[i]; + return r; + } + + private static string Nm(string s) + { + s = s.Trim(); + if (s.Length > 1 && s[0] == '<' && s[^1] == '>') + { + string t = s.Substring(1, s.Length - 2); + if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) + return "Default"; + return t; + } + + return s; + } + + private static int WepId(int w) => w; + + private static string MapDmg(int c) => c switch + { + 8 => "Auto", + 1 => "Slash", + 2 => "Pierce", + 3 => "Bludgeon", + 4 => "Acid", + 5 => "Fire", + 6 => "Cold", + 7 => "Lightning", + 0 => "Nether", + _ => "Auto", + }; + + private static string MapPet(int pdt, int _) + { + if (pdt is 0 or 101) + return "PAuto"; + if (pdt is >= 1 and <= 8) + { + return pdt switch + { + 1 => "Slash", + 2 => "Pierce", + 3 => "Bludgeon", + 4 => "Fire", + 5 => "Cold", + 6 => "Lightning", + 7 => "Acid", + 8 => "Nether", + _ => "PAuto", + }; + } + + return "PAuto"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs index f128203..e41a9ed 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RadarWallRenderer.cs @@ -7,6 +7,7 @@ using ImGuiNET; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.Plugin.RynthAi.Raycasting; using RynthCore.PluginSdk; +using RynthCore.Install; namespace RynthCore.Plugin.RynthAi; @@ -17,7 +18,7 @@ namespace RynthCore.Plugin.RynthAi; /// dungeons stack would be unreadable otherwise. /// /// Explored state is per-EnvCell and persisted per-landblock under -/// C:\Games\RynthSuite\RynthAi\ExploredDungeons\XXYY0000.json. +/// \RynthAi\ExploredDungeons\XXYY0000.json. /// internal sealed class RadarWallRenderer { @@ -49,7 +50,7 @@ internal sealed class RadarWallRenderer private readonly bool[] _inside = new bool[MaxPolyVerts]; private static readonly string ExploredDir = - @"C:\Games\RynthSuite\RynthAi\ExploredDungeons"; + System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"ExploredDungeons"); public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings) { @@ -62,7 +63,7 @@ internal sealed class RadarWallRenderer public void Render() { try { RenderCore(); } - catch (Exception ex) { _host.Log($"RadarWalls: {ex.Message}"); } + catch (Exception ex) { RynthLog.Write(LogCat.Radar, $"RadarWalls: {ex.Message}"); } } private void RenderCore() @@ -288,7 +289,7 @@ internal sealed class RadarWallRenderer } catch (Exception ex) { - _host.Log($"RadarWalls: load {path} failed: {ex.Message}"); + RynthLog.Write(LogCat.Radar, $"RadarWalls: load {path} failed: {ex.Message}"); } } @@ -309,7 +310,7 @@ internal sealed class RadarWallRenderer } catch (Exception ex) { - _host.Log($"RadarWalls: save failed: {ex.Message}"); + RynthLog.Write(LogCat.Radar, $"RadarWalls: save failed: {ex.Message}"); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs index 2f541f4..b0c3a76 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs @@ -1072,6 +1072,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting private static void Log(string msg) { System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}"); + RynthLog.Trace(LogCat.Raycast, $"[DungeonLOS] {msg}"); // visible via /ra trace raycast } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs index 6ee10c1..8ceb995 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs @@ -1788,6 +1788,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting { string line = $"[GeoLoader] {msg}"; System.Diagnostics.Debug.WriteLine(line); + RynthLog.Trace(LogCat.Raycast, line); // visible via /ra trace raycast if (DiagLog.Count < 200) DiagLog.Add(msg); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs index 693986f..b58f84e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs @@ -164,6 +164,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting private static void Log(string msg) { System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}"); + RynthLog.Trace(LogCat.Raycast, $"[LandblockInfo] {msg}"); // visible via /ra trace raycast } } @@ -282,6 +283,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting private static void Log(string msg) { System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}"); + RynthLog.Trace(LogCat.Raycast, $"[EnvCell] {msg}"); // visible via /ra trace raycast } } @@ -585,6 +587,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting private static void Log(string msg) { System.Diagnostics.Debug.WriteLine($"[Setup] {msg}"); + RynthLog.Trace(LogCat.Raycast, $"[Setup] {msg}"); // visible via /ra trace raycast } } @@ -755,6 +758,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting private static void Log(string msg) { System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}"); + RynthLog.Trace(LogCat.Raycast, $"[GfxObj] {msg}"); // visible via /ra trace raycast } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs index 0dbb17f..58fd761 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs @@ -1027,6 +1027,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting { string line = $"[Scatter] {msg}"; System.Diagnostics.Debug.WriteLine(line); + RynthLog.Trace(LogCat.Raycast, line); // visible via /ra trace raycast if (DiagLog.Count < 100) DiagLog.Add(msg); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 5e25525..08cd4cc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -2993,8 +2993,8 @@ public sealed partial class RynthAiPlugin return sb.ToString(); } - // Minimal JSON string escaper for route names (which can contain user-chosen chars). - private static string JsonEscape(string s) + // Minimal JSON string escaper for hand-built export JSON (route names, ILT Hub text). + internal static string JsonEscape(string s) { var sb = new System.Text.StringBuilder(s.Length + 8); foreach (char c in s) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs new file mode 100644 index 0000000..99145fc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiItemInfo.cs @@ -0,0 +1,381 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Threading; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi.ItemInfo; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// /ra iteminfo — Mag-style item info (ratings, damage, spells, slayer, imbues …) as one line or +/// as pet-roster style lines, printed on demand, on select or on a left/right mouse click; +/// ported from UtilityBelt ub-IT / Mag-Tools ItemInfo. Partial class of RynthAiPlugin. +/// +/// /ra iteminfo describe the selected item (IDs it first when needed) +/// /ra iteminfo on|off describe every item you select +/// /ra iteminfo settings open/close the Item Info settings window +/// /ra iteminfo fields list fields and ratings with their on/off state +/// /ra iteminfo field <name> on|off show/hide one field (ratings, slayer, spells, …) +/// /ra iteminfo rating <tag> on|off show/hide one rating (D, CD, CDR, …) +/// /ra iteminfo value on|off append value + burden +/// /ra iteminfo verbose on|off list every spell instead of Mag's filter +/// /ra iteminfo click left|right|off print the selected item after a mouse click +/// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner +/// /ra iteminfo reset restore defaults +/// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi). +/// +public sealed partial class RynthAiPlugin +{ + // One pending describe at a time: the newest request replaces the previous one. + private int _itemInfoPendingId; + private long _itemInfoPendingSince; + + // Automatic triggers (select + click) can both fire for one click; the same item inside + // this window prints once. + private const long AutoDedupeMs = 1500; + private int _itemInfoLastAutoId; + private long _itemInfoLastAutoAt; + + // Click trigger. A press counts as a click only if it started outside every overlay window, + // was released within ClickMaxHoldMs and moved at most ClickMaxMovePx — so item drags and + // right-button mouse-look never print. The client updates the selection after it handles + // the click, so the selection is read ClickSettleMs after the release, on the tick thread. + private const long ClickMaxHoldMs = 600; + private const float ClickMaxMovePx = 6f; + private const long ClickSettleMs = 150; + private bool _iiClickPrevDown; + private bool _iiClickArmed; + private long _iiClickPressAt; + private Vector2 _iiClickPressPos; + private long _iiClickResolveAt; // TickCount64 to read the selection at; 0 = none (Interlocked) + + /// Character settings when loaded, else null (commands then use defaults / refuse edits). + private MagItemInfoSettings? ItemInfoSettings => _dashboard?.Settings.ItemInfoSettings; + + private void HandleItemInfoCommand(string[] parts) + { + var s = ItemInfoSettings; + string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; + string arg3 = parts.Length >= 4 ? parts[3] : string.Empty; + string arg4 = parts.Length >= 5 ? parts[4] : string.Empty; + + if (sub.Length == 0) + { + PrintSelectedItemInfo(); + return; + } + if (s == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; } + + switch (sub) + { + case "settings": + case "gui": + case "window": + s.ShowWindow = !s.ShowWindow; + ChatLine($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}."); + return; + + case "value": + if (ParseOnOff(arg3) is bool v) s.ShowValueAndBurden = v; + ChatLine($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}"); + return; + + case "verbose": + if (ParseOnOff(arg3) is bool all) + s.SpellMode = all ? MagItemInfoSettings.SpellModeAll : MagItemInfoSettings.SpellModeMag; + ChatLine($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}"); + return; + + case "field": + if (!MagItemInfoCatalog.TryFindField(arg3, out MagItemInfoField field)) + { + ChatLine($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them."); + return; + } + if (ParseOnOff(arg4) is bool fieldOn) s.SetHidden(field, !fieldOn); + ChatLine($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}"); + return; + + case "rating": + int r = MagItemInfoCatalog.FindRating(arg3); + if (r < 0) + { + ChatLine($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them."); + return; + } + if (ParseOnOff(arg4) is bool ratingOn) s.SetRatingHidden(r, !ratingOn); + var rating = MagItemInfoCatalog.Ratings[r]; + ChatLine($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}"); + return; + + case "fields": + ListItemInfoFields(s); + return; + + case "click": + switch (arg3.ToLowerInvariant()) + { + case "left": case "l": s.ClickTrigger = MagItemInfoSettings.ClickLeft; break; + case "right": case "r": s.ClickTrigger = MagItemInfoSettings.ClickRight; break; + case "off": case "none": s.ClickTrigger = MagItemInfoSettings.ClickOff; break; + case "": break; + default: + ChatLine("[RynthAi] Usage: /ra iteminfo click left|right|off"); + return; + } + ChatLine($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}"); + return; + + case "layout": + switch (arg3.ToLowerInvariant()) + { + case "pet": case "pets": case "lines": s.Layout = MagItemInfoSettings.LayoutPetLines; break; + case "line": case "mag": case "one": s.Layout = MagItemInfoSettings.LayoutOneLine; break; + case "": break; + default: + ChatLine("[RynthAi] Usage: /ra iteminfo layout pet|line"); + return; + } + ChatLine($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}"); + return; + + case "reset": + s.ResetToDefaults(); + ChatLine("[RynthAi] Item info settings reset to defaults."); + return; + } + + if (ParseOnOff(sub) is bool onSelect) + { + s.OnSelect = onSelect; + ChatLine($"[RynthAi] Item info on select: {OnOff(onSelect)}"); + return; + } + ChatLine("[RynthAi] Usage: /ra iteminfo [on|off|settings|fields|field on|off|rating on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]"); + } + + private static string OnOff(bool on) => on ? "ON" : "OFF"; + + /// "/ra iteminfo fields" — current state of every field and rating. + private void ListItemInfoFields(MagItemInfoSettings s) + { + var sb = new StringBuilder("[RynthAi] Fields: "); + bool first = true; + foreach (var f in MagItemInfoCatalog.Fields) + { + if (!first) sb.Append(", "); + sb.Append(f.Field).Append(s.IsHidden(f.Field) ? " off" : " on"); + first = false; + } + ChatLine(sb.ToString()); + + sb.Clear().Append("[RynthAi] Ratings: "); + var ratings = MagItemInfoCatalog.Ratings; + for (int i = 0; i < ratings.Length; i++) + { + if (i > 0) sb.Append(", "); + sb.Append(ratings[i].Tag).Append(s.IsRatingHidden(i) ? " off" : " on"); + } + ChatLine(sb.ToString()); + } + + /// /ra iteminfo and the window's "Print to chat" button. + private void PrintSelectedItemInfo() + { + if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; } + uint selected = Host.GetSelectedItemId(); + if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; } + QueueItemInfo(unchecked((int)selected), requestId: true); + } + + /// On-select class filters from the Item Info window. + private static bool ItemInfoWantsClass(MagItemInfoSettings s, AcObjectClass cls) => cls switch + { + AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb => s.OnSelectWeapons, + AcObjectClass.Armor or AcObjectClass.Clothing => s.OnSelectArmor, + AcObjectClass.Jewelry => s.OnSelectJewelry, + _ => s.OnSelectOther, + }; + + /// + /// Describe now if its appraisal is cached, otherwise (optionally) + /// request an ID and print from once it lands or times out. + /// + internal void QueueItemInfo(int itemId, bool requestId) + { + if (itemId == 0) return; + uint uid = unchecked((uint)itemId); + if (!Host.HasHasAppraisalData || Host.HasAppraisalData(uid)) + { + _itemInfoPendingId = 0; + PrintItemInfo(itemId, identified: true); + return; + } + if (requestId && Host.HasRequestId) Host.RequestId(uid); + _itemInfoPendingId = itemId; + _itemInfoPendingSince = Environment.TickCount64; + } + + /// + /// Select / click triggers: unless the same item was queued + /// automatically within (one click can raise both triggers). + /// + internal void QueueAutoItemInfo(int itemId, bool requestId) + { + long now = Environment.TickCount64; + if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) return; + _itemInfoLastAutoId = itemId; + _itemInfoLastAutoAt = now; + QueueItemInfo(itemId, requestId); + } + + /// + /// Render-thread click watcher (OnRender / OnRenderOverlay, ImGui context current). The ImGui + /// backend sees every mouse message on the game window, including the ones the game handles, + /// so the raw button state is edge-detected here; the selection is resolved in + /// . + /// + private void DetectItemInfoClick() + { + int trigger = ItemInfoSettings?.ClickTrigger ?? MagItemInfoSettings.ClickOff; + int button = trigger switch + { + MagItemInfoSettings.ClickLeft => 0, + MagItemInfoSettings.ClickRight => 1, + _ => -1, + }; + if (button < 0) + { + _iiClickPrevDown = false; + _iiClickArmed = false; + return; + } + + ImGuiIOPtr io = ImGui.GetIO(); + bool down = io.MouseDown[button]; + long now = Environment.TickCount64; + + if (down && !_iiClickPrevDown) + { + // A press on an overlay window belongs to the overlay, not to an item in the game. + _iiClickArmed = !io.WantCaptureMouse; + _iiClickPressAt = now; + _iiClickPressPos = io.MousePos; + } + else if (down && _iiClickArmed) + { + bool held = now - _iiClickPressAt > ClickMaxHoldMs; + bool moved = Vector2.DistanceSquared(io.MousePos, _iiClickPressPos) > ClickMaxMovePx * ClickMaxMovePx; + if (held || moved) _iiClickArmed = false; // drag or mouse-look, not a click + } + else if (!down && _iiClickPrevDown && _iiClickArmed) + { + _iiClickArmed = false; + Interlocked.Exchange(ref _iiClickResolveAt, now + ClickSettleMs); + } + _iiClickPrevDown = down; + } + + /// Tick-thread half of the click trigger: describe whatever item the click selected. + private void ResolveItemInfoClick() + { + long at = Interlocked.Read(ref _iiClickResolveAt); + if (at == 0 || Environment.TickCount64 < at) return; + if (Interlocked.CompareExchange(ref _iiClickResolveAt, 0, at) != at) return; + + var s = ItemInfoSettings; + if (s == null || s.ClickTrigger == MagItemInfoSettings.ClickOff || !Host.HasGetSelectedItemId) return; + uint selected = Host.GetSelectedItemId(); + if (selected == 0) return; + + int id = unchecked((int)selected); + WorldObject? obj = _objectCache?[id]; + if (obj == null || !IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) return; + QueueAutoItemInfo(id, requestId: true); + } + + /// Plugin-tick poll for a pending describe (no appraisal-arrived event in the SDK). + private void TickItemInfo() + { + ResolveItemInfoClick(); + + int id = _itemInfoPendingId; + if (id == 0) return; + bool ready = Host.HasAppraisalData(unchecked((uint)id)); + long timeoutMs = (long)((ItemInfoSettings?.IdTimeoutSec ?? 3f) * 1000f); + bool timedOut = Environment.TickCount64 - _itemInfoPendingSince > timeoutMs; + if (!ready && !timedOut) return; + _itemInfoPendingId = 0; + PrintItemInfo(id, identified: ready); + } + + /// + /// Builds the output lines (no prefix / indent) in the configured layout, or returns null + /// with set. The one-line layout returns a single line. + /// + private List? BuildItemInfoLines(int itemId, out string? error) + { + error = null; + WorldObject? wo = _objectCache?[itemId]; + if (wo == null) { error = $"Item 0x{(uint)itemId:X8} is not in the object cache."; return null; } + try + { + var s = ItemInfoSettings; + MagItemDescription d = MagItemDescriber.Build(new CacheItemPropertySource(Host, wo), MagItemInfoOptions.From(s)); + return (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine + ? new List { d.ToOneLine() } + : d.ToPetLines(); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.General, ex, $"item info 0x{(uint)itemId:X8}"); + error = $"Item info failed for {wo.Name}: {ex.Message}"; + return null; + } + } + + /// + /// Chat output. Pet-style: line 1 carries the prefix in , + /// later lines are indented like the pet roster and use . + /// + private void PrintItemInfo(int itemId, bool identified) + { + List? lines = BuildItemInfoLines(itemId, out string? error); + if (lines == null || lines.Count == 0) { ChatLine("[RynthAi] " + error); return; } + if (!identified) lines[0] += " (not identified — stats may be incomplete)"; + + var s = ItemInfoSettings; + string prefix = s?.Prefix ?? "[RynthAi] "; + int headerType = s?.ChatType ?? 1; + int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType; + + Host.WriteToChat(prefix + lines[0], headerType); + for (int i = 1; i < lines.Count; i++) + Host.WriteToChat(prefix + " " + lines[i], detailType); + } + + /// Item Info window preview: the selected item's lines, or null when nothing is selected. + private string? DescribeSelectedItemForPreview() + { + if (!Host.HasGetSelectedItemId) return null; + uint selected = Host.GetSelectedItemId(); + if (selected == 0) return null; + int id = unchecked((int)selected); + List? lines = BuildItemInfoLines(id, out string? error); + if (lines == null || lines.Count == 0) return error; + if (Host.HasHasAppraisalData && !Host.HasAppraisalData(selected)) + lines[0] += " (not identified yet — Print to chat IDs it)"; + // The window adds the prefix to the first line; indent the rest like chat. + return string.Join("\n ", lines); + } + + /// Item Info window "Test" button: sample line in the chosen chat type. + private void TestItemInfoChatType(int chatType) + { + string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi] "; + Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs new file mode 100644 index 0000000..620439a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -0,0 +1,467 @@ +// RynthAiPlugin.LocalFeatures.cs — ILT Hub, floating HUDs, chat translation, item info, the nav +// overlay and the UB damage seed. +// +// The engine draws the main panels. These features draw their own ImGui windows from +// RynthPluginRender / RynthPluginRenderOverlay. Lifecycle methods on RynthAiPlugin call into +// this file; they add to combat, loot and navigation and never replace them. +using System; +using System.Collections.Generic; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + private NavBreadcrumbTracker? _navBreadcrumbs; + private NavOverlayRenderer? _navOverlay; + private IltHub.IltHubController? _iltHub; + private Huds.HudController? _huds; + private Huds.HudIconCache? _hudIcons; + private Translate.ChatTranslator? _translator; + private Translate.TranslateUi? _translateUi; + private LegacyItemInfoUi? _itemInfoUi; + private CreatureData.UbMobSeedStore? _mobSeedStore; + + // One-time overlay diagnostics (render thread only). + private string? _overlaySkipReasonLogged; + private bool _overlayEnteredLogged; + + /// Daily diagnostics log. Feature code writes through . + private void InitLocalDiagnostics() + { + try { RynthLog.Init(Host); } + catch (Exception ex) { Host.Log($"[RynthAi] diagnostics init failed: {ex.Message}"); } + try { _mobSeedStore = new CreatureData.UbMobSeedStore(); } + catch (Exception ex) { Host.Log($"[RynthAi] mob seed store failed: {ex.Message}"); } + } + + /// + /// CombatManager.MobSeedLookup: the seed's damage types for a monster, best first (highest + /// Score), or null when the seed has nothing for it. Feeds the Auto element ranking only + /// after the server table and the learned element (see CreatureWeakness.Rank). + /// + private IReadOnlyList? LookupMobSeed(uint wcid, string name) + { + var store = _mobSeedStore; + if (store == null || !store.TryGetRanked(wcid, name, out var ranked) || ranked.Count == 0) + return null; + var ordered = new List(ranked); + ordered.Sort((a, b) => b.Score.CompareTo(a.Score)); + var elements = new List(ordered.Count); + foreach (var e in ordered) elements.Add(e.Element); + return elements; + } + + /// Chat translator survives logout; session language resets on each login. + private void EnsureTranslator() + { + try + { + if (_translator == null) + { + _translator = new Translate.ChatTranslator(Host, CurrentCharacterName); + _translateUi = new Translate.TranslateUi(_translator); + } + _translator.ResetSession(); + if (_huds != null) _huds.Translate = _translateUi; + } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator init"); } + } + + /// The logged-in character's name, or empty before login. + private string CurrentCharacterName() + => _playerId != 0 && Host.HasGetObjectName && Host.TryGetObjectName(_playerId, out string name) ? name ?? string.Empty : string.Empty; + + /// Waypoint HUD, labels, guide line, and the breadcrumb recorder. + private void CreateNavOverlay() + { + if (_dashboard == null) return; + _navBreadcrumbs = new NavBreadcrumbTracker(Host, _dashboard.Settings, DescribeNavPortal, ChatLine); + _navOverlay = new NavOverlayRenderer(Host, _dashboard.Settings, _navBreadcrumbs); + _dashboard.NavBreadcrumbs = _navBreadcrumbs; // Nav panel: trail -> route, trail stats + } + + /// Nav recorder hook: (name, object class) when is a portal. + private (string Name, int ObjectClass)? DescribeNavPortal(uint id) + { + WorldObject? wo = _objectCache?[unchecked((int)id)]; + if (wo == null || wo.ObjectClass != AcObjectClass.Portal || string.IsNullOrEmpty(wo.Name)) return null; + return (wo.Name, (int)AcObjectClass.Portal); + } + + /// + /// ILT Hub and floating HUDs for the loaded character. No-op until the per-character + /// folder exists, so login and the deferred settings load in OnTick both call this. + /// + private void CreateIltHub() + { + if (_dashboard == null || string.IsNullOrEmpty(_dashboard.CharFolder) || _iltHub != null) + return; + + var dash = _dashboard; + _iltHub = new IltHub.IltHubController(Host, dash.CharFolder, + () => _objectCache, () => dash.Settings, () => _questTracker, + () => dash.SaveSettings()); + _hudIcons ??= new Huds.HudIconCache(Host, () => _raycast?.GeometryLoader?.PortalDat); + _huds = new Huds.HudController(Host, dash.CharFolder, () => _objectCache, dash, () => _iltHub, _hudIcons, + () => _combatManager?.activeTargetId ?? 0); + if (_translateUi != null) _huds.Translate = _translateUi; + + // The Mini Remote is the Hub's main window: "/ra hub [show|hide|toggle]" drives it, and + // while it is up the Hub keeps its bank / gear data fresh. + var huds = _huds; + _iltHub.MiniRemoteCommand = mode => "[ILT Hub] " + huds.HandleCommand("remote", mode); + _iltHub.MiniRemoteVisible = () => huds.State.ShowMiniRemote; + EnsureItemInfoUi(); + } + + /// Item Info window, created once settings exist. + private void EnsureItemInfoUi() + { + if (_dashboard == null || _itemInfoUi != null) return; + _itemInfoUi = new LegacyItemInfoUi(_dashboard.Settings); + _itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType); + } + + /// Pump-thread work for the ported features. Safe before login (each call is null-checked). + private void TickLocalFeatures() + { + try { RynthLog.Pump(); } + catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); } + try { _iltHub?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); } + try { _huds?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "Tick"); } + try { _translator?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator Tick"); } + try { TickItemInfo(); } + catch (Exception ex) { RynthLog.Exception(LogCat.General, ex, "item info tick"); } + try { _navBreadcrumbs?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav breadcrumbs tick"); } + } + + /// Drop per-character feature objects. The translator is disposed only on plugin shutdown. + private void TeardownLocalFeatures(bool disposeTranslator) + { + try { _navBreadcrumbs?.Shutdown(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav recorder shutdown"); } + _navBreadcrumbs = null; + if (_dashboard != null) _dashboard.NavBreadcrumbs = null; + _navOverlay = null; + try { _iltHub?.OnLogout(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); } + _iltHub = null; + try { _huds?.OnLogout(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); } + _huds = null; + _itemInfoUi = null; + ResetGroundLoot(clearCaches: true); + if (!disposeTranslator) return; + try { _translator?.Dispose(); } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator dispose"); } + _translator = null; + _translateUi = null; + } + + /// ILT Hub may eat a server reply; the translator records the line either way. + private void OnChatLocalFeatures(string text, int chatType, ref int eat) + { + try + { + if (_iltHub?.OnChat(text) == true) eat = 1; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); } + try { _translator?.OnChatWindowText(text, chatType); } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator inbound"); } + } + + /// True when the translator swallowed an outbound chat line (it will resend the translation). + private bool TryEatOutboundTranslation(string trimmed) + { + try + { + return _translator != null && _translator.TryInterceptOutbound(trimmed); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.Chat, ex, "translator outbound"); + return false; + } + } + + /// ImGui windows the engine panels do not draw. + public override void OnRender() + { + if (!_initialized || !_loginComplete || Host.ImGuiContext == IntPtr.Zero) + return; + + IntPtr previousContext = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + try + { + DetectItemInfoClick(); + _navOverlay?.Render(); + _itemInfoUi?.Render(); + _iltHub?.Render(); + _huds?.Render(); + RenderTranslateWindow(); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.UI, ex, "OnRender"); + } + finally + { + ImGui.SetCurrentContext(previousContext); + } + } + + /// + /// Called when the engine's ImGui shell is off. Same local windows as ; + /// the engine panels are absent in that mode, so these windows are the only UI for them. + /// + public void OnRenderOverlay() + { + if (!_initialized || !_loginComplete || Host.ImGuiContext == IntPtr.Zero) + { + string reason = !_initialized ? "not initialized" : !_loginComplete ? "login not complete" : "no ImGui context"; + if (reason != _overlaySkipReasonLogged) + { + _overlaySkipReasonLogged = reason; + RynthLog.Write(LogCat.UI, $"[Overlay] OnRenderOverlay skipped: {reason}."); + } + return; + } + + if (!_overlayEnteredLogged) + { + _overlayEnteredLogged = true; + RynthLog.Write(LogCat.UI, $"[Overlay] OnRenderOverlay drawing (iltHub={(_iltHub != null ? "ready" : "null")})."); + } + + IntPtr previousContext = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + try + { + DetectItemInfoClick(); + int pushedColors = LegacyDashboardRenderer.PushDashboardStyle(); + try { _iltHub?.Render(); } + finally { ImGui.PopStyleColor(pushedColors); } + _huds?.Render(); + RenderTranslateWindow(); + _navOverlay?.Render(); + _itemInfoUi?.Render(); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.UI, ex, "OnRenderOverlay"); + } + finally + { + ImGui.SetCurrentContext(previousContext); + } + } + + /// Chat Translate window in the dashboard colours (no-op while hidden). + private void RenderTranslateWindow() + { + var ui = _translateUi; + if (ui == null || _translator?.Settings.ShowWindow != true) return; + int pushedColors = LegacyDashboardRenderer.PushDashboardStyle(); + try { ui.RenderWindow(); } + finally { ImGui.PopStyleColor(pushedColors); } + } + + /// "/ra huds|itemhud|remote|miniremote [show|hide|toggle]". + private void HandleHudCommand(string which, string mode) + { + if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; } + ChatLine("[RynthAi] " + _huds.HandleCommand(which, mode)); + } + + /// Skills panel Progression tab snapshot (RynthPluginGetProgressionJson). Pump thread. + internal string BuildProgressionJson() => _iltHub?.BuildProgressionJson() ?? "{\"available\":false}"; + + /// Settings panel Charms Tracking tab snapshot (RynthPluginGetCharmsJson). Pump thread. + internal string BuildCharmsJson() => _iltHub?.BuildCharmsJson() ?? "{\"available\":false}"; + + /// "prog ..." remote command from the Skills panel's Progression tab. Pump thread. + private void HandleProgressionRemote(string value) + { + if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); return; } + _iltHub.Progression.HandleRemote(value.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + /// "/ra itemhud add <name>" and the inventory panel's "Add to item count HUD". Pump thread. + private void HandleItemHudAdd(string name) + { + if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; } + if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ra itemhud add "); return; } + ChatLine("[RynthAi] " + _huds.AddToItemHudAndShow(name)); + } + + /// /ra translate ... — forwards to the chat translator. + private void HandleTranslateCommand(string[] parts) + { + if (_translator == null) { ChatLine("[RynthAi] Chat translator not ready (log in first)."); return; } + _translator.HandleCommand(parts.Length > 2 ? parts[2..] : Array.Empty(), ChatLine); + } + + /// Parses an on/off word; returns null for anything else (caller treats it as status). + private static bool? ParseOnOff(string? word) => word?.ToLowerInvariant() switch + { + "on" or "true" or "1" or "enable" => true, + "off" or "false" or "0" or "disable" => false, + _ => null, + }; + + /// "/ra debug [on|off|status]" — echoes trace and exception lines to chat. + private void HandleDebugCommand(string[] parts) + { + string arg = parts.Length > 2 ? parts[2] : "status"; + bool? state = arg.Equals("toggle", StringComparison.OrdinalIgnoreCase) ? !RynthLog.DebugToChat : ParseOnOff(arg); + if (state.HasValue) RynthLog.DebugToChat = state.Value; + ChatLine($"[RynthAi] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")}." + + (RynthLog.DebugToChat && RynthLog.TracedCategories().Count == 0 ? " (no categories traced — see /ra trace list)" : "")); + } + + /// "/ra trace <cat|all|ilt|list> [on|off|status]". + private void HandleTraceCommand(string[] parts) + { + string target = parts.Length > 2 ? parts[2] : "status"; + string? action = parts.Length > 3 ? parts[3] : null; + + if (target.Equals("status", StringComparison.OrdinalIgnoreCase)) + { + foreach (string l in RynthLog.StatusLines()) ChatLine(l); + return; + } + + if (target.Equals("list", StringComparison.OrdinalIgnoreCase)) + { + var names = new System.Collections.Generic.List(); + foreach (LogCat c in Enum.GetValues()) + names.Add(RynthLog.IsTracing(c) ? c + "*" : c.ToString()); + ChatLine("[RynthAi] Trace categories (* = on): " + string.Join(", ", names)); + return; + } + + bool? state = ParseOnOff(action); + bool isAll = target.Equals("all", StringComparison.OrdinalIgnoreCase); + bool isIlt = target.Equals("ilt", StringComparison.OrdinalIgnoreCase); + if (isAll || isIlt) + { + if (!state.HasValue) { foreach (string l in RynthLog.StatusLines()) ChatLine(l); return; } + int n = RynthLog.SetTracingByPrefix(isIlt ? "Ilt" : string.Empty, state.Value); + ChatLine($"[RynthAi] Tracing {(state.Value ? "enabled" : "disabled")} for {n} {(isIlt ? "ILT Hub " : "")}categories."); + return; + } + + if (!RynthLog.TryParseCategory(target, out LogCat cat)) + { + ChatLine($"[RynthAi] Unknown trace category '{target}'. Use /ra trace list."); + return; + } + + if (action != null && action.Equals("status", StringComparison.OrdinalIgnoreCase)) + { + ChatLine($"[RynthAi] Trace {cat}: {(RynthLog.IsTracing(cat) ? "ON" : "off")}"); + return; + } + + bool enable = state ?? !RynthLog.IsTracing(cat); + RynthLog.SetTracing(cat, enable); + ChatLine($"[RynthAi] Trace {cat}: {(enable ? "ON" : "off")} → {RynthLog.TraceDirectory}"); + } + + /// "/ra logs [open|prune|flush|file on|off]". + private void HandleLogsCommand(string[] parts) + { + string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : "status"; + switch (sub) + { + case "open": + try + { + RynthLog.Flush(); + System.IO.Directory.CreateDirectory(RynthLog.Directory); + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", $"\"{RynthLog.Directory}\"") { UseShellExecute = true }); + } + catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "logs open"); ChatLine($"[RynthAi] Could not open {RynthLog.Directory}: {ex.Message}"); } + break; + case "prune": + ChatLine($"[RynthAi] Pruned {RynthLog.Prune()} old diagnostics file(s)."); + break; + case "flush": + RynthLog.Flush(); + ChatLine("[RynthAi] Diagnostics flushed to disk."); + break; + case "file": + bool? state = ParseOnOff(parts.Length > 3 ? parts[3] : null); + if (state.HasValue) RynthLog.FileLogAll = state.Value; + ChatLine($"[RynthAi] Daily RynthAi log file is {(RynthLog.FileLogAll ? "ON" : "off")}."); + break; + default: + foreach (string l in RynthLog.StatusLines()) ChatLine(l); + break; + } + } + + /// /ra navrec [on|off] — toggles route recording. + private void HandleNavRecordCommand(string[] parts) + { + if (_dashboard == null) return; + var s = _dashboard.Settings; + string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + s.IsRecordingNav = arg switch { "on" => true, "off" => false, _ => !s.IsRecordingNav }; + ChatLine($"[RynthAi] Nav recording {(s.IsRecordingNav ? "ON — walk the route; portals are captured" : "OFF")}."); + } + + /// /ra navhud [on|off] — shows or hides the navigation HUD window. + private void HandleNavHudCommand(string[] parts) + { + if (_dashboard == null) return; + var o = _dashboard.Settings.NavOverlay; + string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + o.ShowHud = arg switch { "on" => true, "off" => false, _ => !o.ShowHud }; + ChatLine($"[RynthAi] Nav HUD {(o.ShowHud ? "shown" : "hidden")}."); + } + + /// /ra navtrail [on|off|toggle|clear] — breadcrumb tracking switch, wipe, or a status report. + private void HandleNavTrailCommand(string[] parts) + { + string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + if (arg == "clear") + { + _navBreadcrumbs?.RequestClear(); + ChatLine("[RynthAi] Breadcrumb trail cleared."); + return; + } + if (arg is "on" or "off" or "toggle") + { + if (_dashboard == null) return; + var o = _dashboard.Settings.NavOverlay; + o.TrackBreadcrumbs = arg switch { "on" => true, "off" => false, _ => !o.TrackBreadcrumbs }; + _dashboard.SaveSettings(); + ChatLine($"[RynthAi] Breadcrumb tracking {(o.TrackBreadcrumbs ? "on" : "off")}."); + return; + } + bool tracking = _dashboard?.Settings.NavOverlay.TrackBreadcrumbs ?? false; + int n = _navBreadcrumbs?.Trail.Length ?? 0; + double yd = _navBreadcrumbs?.TrailYards ?? 0; + ChatLine($"[RynthAi] Breadcrumbs {(tracking ? "on" : "off")}: {n} points, {yd:F0} yd. Use /ra navtrail on|off|clear."); + } + + /// /ra navoverlay [on|off] — route overlay (rings / lines, waypoint labels, guide line); no argument toggles. + private void HandleNavOverlayCommand(string[] parts) + { + if (_dashboard == null) return; + var o = _dashboard.Settings.NavOverlay; + string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + o.ShowRouteMarkers = arg switch { "on" => true, "off" => false, _ => !o.ShowRouteMarkers }; + _dashboard.SaveSettings(); + ChatLine($"[RynthAi] Route overlay {(o.ShowRouteMarkers ? "on" : "off")}."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 6a37fb7..98976bc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -164,6 +164,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // constructor does no ImGui work. (RynthAi no longer exports RynthPluginRender // and never reads Host.ImGuiContext.) ComponentDatabase.SetLog(msg => Log(msg)); + InitLocalDiagnostics(); + // The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module. + ImGuiNativeBinding.Ensure(); _dashboard = new LegacyDashboardRenderer(Host); // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line // each, and no automatic door/corpse use while the macro is off. @@ -232,6 +235,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } catch { } long tAfterGc = Environment.TickCount64; + try { _translator?.Dispose(); } catch { } + _translator = null; + _translateUi = null; + try { RynthLog.Shutdown(); } catch { } Log($"RynthAi: Shutdown done — SaveSettings={tAfterSettings - t0} ms, TeardownSession={tAfterTeardown - tAfterSettings} ms, SaveCreatureStore={tAfterStore - tAfterTeardown} ms, GC={tAfterGc - tGc} ms (heap now {GC.GetGCMemoryInfo().HeapSizeBytes / (1024 * 1024)} MB), total={tAfterGc - t0} ms"); } @@ -390,6 +397,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _autoVendor = null; _autoTrade?.Reset(); _autoTrade = null; + TeardownLocalFeatures(disposeTranslator: false); _playerId = 0; _loginComplete = false; _pendingGives.Clear(); @@ -454,6 +462,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _loginComplete = true; _dashboard.OnLoginComplete(); _dashboard.ChatSubmitHandler = HandleRynthChatSubmit; + EnsureTranslator(); + EnsureItemInfoUi(); _navigationEngine = new NavigationEngine(Host, _dashboard.Settings) { ChatSubmit = HandleRynthChatSubmit, @@ -480,6 +490,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { GeometrySource = () => _raycast is { IsInitialized: true } rc ? rc.GeometryLoader : null, }; + CreateNavOverlay(); _radarWallRenderer = new RadarWallRenderer(Host, _dashboard.Settings); _terrainOverlay = new TerrainPassabilityOverlay(Host); Log($"RynthAi: NavMarkerRenderer created, HasNav3D={Host.HasNav3D}, version={Host.Version}"); @@ -614,6 +625,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.SetCharacterSkills(_charSkills); _combatManager.SetPlayerId(_playerId); _combatManager.SetDamageStores(_creatureStore, _damageStore); + _combatManager.MobSeedLookup = LookupMobSeed; _combatManager.SetAwakenedTier(_tier); // The raycast init thread may already have finished (warm dats): hand it over now. WireRaycastIntoCombat(); @@ -658,6 +670,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.SummonOut = () => _petManager?.CurrentSummon(); } + CreateIltHub(); + if (_iltHub?.SkipLoginQuestRefresh == true) + Log("RynthAi: ILT Hub says /myquests is off on this server; login quest refresh already ran."); + try + { + string hubChar = CurrentCharacterName(); + _iltHub?.OnLoginComplete(hubChar, _petManager); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "login"); } + _salvageManager = new SalvageManager(Host, _dashboard.Settings, _objectCache); // Hand the salvage manager a live accessor for the loot profile's // SalvageCombine config so combining respects per-material workmanship @@ -814,15 +836,64 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick case "sendchat": if (!string.IsNullOrEmpty(value)) HandleRynthChatSubmit(value); break; case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted) + case "hub": + case "quests": + case "pets": + case "guardian": + // Dashboard Char launcher (hub=show opens the Mini Remote) and its right-click menu + // (hub=open
toggle); value carries the "/ra hub|quests|pets" arguments. + if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); break; } + _iltHub.HandleCommand(action.ToLowerInvariant(), value.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + break; + case "huds": + case "itemhud": + case "remote": + case "miniremote": + // Dashboard Hub launcher: left-click remote=toggle, right-click huds=show. + HandleHudCommand(action.ToLowerInvariant(), value); + break; + case "itemhudadd": + // Inventory panel "Add to item count HUD"; value is the item name. + HandleItemHudAdd(value); + break; + case "remoteslot": + // Inventory panel "Add to Mini Remote"; value is " ". + if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); break; } + if (!_huds.HandleRemoteSlot(value)) Host.Log($"[RynthAi] bad remoteslot value: {value}"); + break; + case "prog": + // Skills panel Progression tab (augmentations / enlightenment edits). + HandleProgressionRemote(value); + break; + case "trace": + case "logs": + case "iteminfo": + // Settings panel buttons (Diagnostics tab, Item Info options); value carries the + // same arguments as "/ra trace|logs|iteminfo ...". + { + var args = new List { "/ra", action.ToLowerInvariant() }; + args.AddRange(value.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + string[] parts = args.ToArray(); + switch (parts[1]) + { + case "trace": HandleTraceCommand(parts); break; + case "logs": HandleLogsCommand(parts); break; + case "iteminfo": HandleItemInfoCommand(parts); break; + } + } + break; // movestart/movestop are applied DIRECTLY by the RynthRemote plugin (pure Host.SetAutoRun/ // SetMotion + its own dead-man watchdog) and are never forwarded here. + default: + Host.Log($"[RynthAi] ignored unknown remote command: {action}={value}"); + return; } Host.Log($"[RynthAi] applied remote command: {action}={value}"); } // Settings the phone must never write (engine-populated read-only status). private static readonly HashSet ReadOnlySettingKeys = new(StringComparer.OrdinalIgnoreCase) - { "MissileCraftingState", "MissileCraftingActive", "MissileCraftingStatus" }; + { "MissileCraftingState", "MissileCraftingActive", "MissileCraftingStatus", "DiagFolder" }; // Authoritative server-side clamp (min,max) per numeric setting — a bad/garbage phone value can never // push a setting out of range and brick a client. Ranges mirror the in-AC SettingsPanel rows. Booleans @@ -1332,6 +1403,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _buffManager?.SetTimerPath(_dashboard.CharFolder); _damageStore?.SetCharacter(_dashboard.CharFolder); _patrolOnLoginPending = _dashboard.Settings.PatrolOnLogin; + if (_iltHub == null) + { + CreateIltHub(); + try { _iltHub?.OnLoginComplete(lateName, _petManager); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "late login"); } + } Log($"RynthAi: per-character settings established late for '{lateName}' (early OnLoginComplete read had failed)."); } } @@ -1359,6 +1436,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // longer calls, so edits waited for the next login. A flag check when idle. _dashboard?.TickMonsterReload(); _questTracker?.Tick(); + TickLocalFeatures(); if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); DrainGiveQueue(); if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); @@ -1926,7 +2004,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // this fires even when an early return short-circuits the body // (Buffing / missile-crafting / BoostNavPriority branches). if (Host.HasNav3D) + { _navMarkerRenderer?.SubmitNav3D(); + _navOverlay?.SubmitNav3D(); + } } } } @@ -1966,7 +2047,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase WorldObject? obj = _objectCache?[sid]; // Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.) if (obj != null && IsLootableClass(obj.ObjectClass)) + { InspectLootRuleForItem(sid, quiet: true); + var itemInfo = _dashboard?.Settings.ItemInfoSettings; + if (itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass)) + QueueAutoItemInfo(sid, requestId: false); + } } } @@ -1991,6 +2077,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase try { mmEat = MetaScheduleChat(text); } catch { } if (mmEat) eat = 1; else _dashboard?.PushChatLine(text, chatType); + OnChatLocalFeatures(text, chatType, ref eat); _buffManager?.OnChatWindowText(text, chatType); _manaStoneManager?.OnChatWindowText(text); _petManager?.OnChatWindowText(text); @@ -2013,6 +2100,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (string.IsNullOrEmpty(deathMessage)) return; _combatManager?.OnKillNotification(deathMessage); _dashboard?.RecordKill(); // feeds the kills/hour session stat + try { _iltHub?.RecordKill(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "kill"); } } public override void OnCreateObject(uint objectId) @@ -2868,6 +2957,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase return; string trimmed = text.Trim(); + if (TryEatOutboundTranslation(trimmed)) + { + eat = 1; + return; + } NoteChatBarLineForMetaSchedule(trimmed); // Mag-Tools /mt command compatibility @@ -3031,6 +3125,32 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "scan": HandleScanCommand(); break; case "buildinfo": HandleBuildInfoCommand(); break; case "navdebug": HandleNavDebugCommand(); break; + case "navrec": HandleNavRecordCommand(parts); break; + case "navhud": HandleNavHudCommand(parts); break; + case "navtrail": HandleNavTrailCommand(parts); break; + case "navoverlay": HandleNavOverlayCommand(parts); break; + case "debug": HandleDebugCommand(parts); break; + case "trace": HandleTraceCommand(parts); break; + case "logs": HandleLogsCommand(parts); break; + case "hub": + case "quests": + case "pets": + case "guardian": + if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); break; } + _iltHub.HandleCommand(cmd, parts.Length > 2 ? parts[2..] : Array.Empty()); + break; + case "itemhud" when parts.Length > 2 && parts[2].Equals("add", StringComparison.OrdinalIgnoreCase): + HandleItemHudAdd(string.Join(" ", parts, 3, parts.Length - 3)); + break; + case "huds": + case "itemhud": + case "remote": + case "miniremote": HandleHudCommand(cmd, parts.Length > 2 ? parts[2] : string.Empty); break; + case "translate": + case "tr": HandleTranslateCommand(parts); break; + case "iteminfo": + case "ii": HandleItemInfoCommand(parts); break; + case "groundloot": HandleGroundLootCommand(parts); break; case "addnavpt": HandleAddNavPointCommand(); break; case "nav": HandleNavCommand(parts); break; case "lua": ForwardLuaCommand(parts); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index e45f8d7..66062ad 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -29,6 +29,10 @@ + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/AcChatEscapes.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/AcChatEscapes.cs new file mode 100644 index 0000000..230163c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/AcChatEscapes.cs @@ -0,0 +1,49 @@ +// AcChatEscapes.cs — AC chat text helpers for the translator. +// +// AC carries characters above Latin-1 (Hangul, CJK, Cyrillic, ...) in chat as "" UTF-16 escapes, +// and the outbound chat path converts each char to one byte, so anything above U+00FF must be escaped +// before sending. Latin-1 letters (ä ö ü ñ é) stay literal; escaping them shows "<00e4>" in chat. +// Speaker names arrive wrapped in "Name<\Tell>" link markup. +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthAi.Translate; + +internal static class AcChatEscapes +{ + private static readonly Regex RxEscape = new(@"<([0-9a-fA-F]{4})>", RegexOptions.CultureInvariant); + private static readonly Regex RxTellLink = new(@"]*>(?[^<]*)<\\Tell>", RegexOptions.CultureInvariant); + + /// Expands "<c2dc>" escapes into the characters they stand for. + public static string Decode(string text) + { + if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0) return text ?? string.Empty; + return RxEscape.Replace(text, m => + { + int cp = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + return cp is > 0 and <= 0xFFFF ? ((char)cp).ToString() : m.Value; + }); + } + + /// Escapes characters above U+00FF as "<hhhh>"; drops other control characters. + public static string EncodeForSend(string text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var sb = new StringBuilder(text.Length + 16); + foreach (char c in text) + { + if (c == '\r' || c == '\n' || c == '\t') { sb.Append(' '); continue; } + if (c < 0x20) continue; + if (c <= 0xFF) { sb.Append(c); continue; } + sb.Append('<').Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)).Append('>'); + } + return sb.ToString().Trim(); + } + + /// Replaces tell-link markup with the plain name it wraps. + public static string StripLinks(string text) + => string.IsNullOrEmpty(text) || text.IndexOf("One line in the Translate window log (immutable once added). +internal sealed record TranslateLogEntry( + DateTime Time, + TranslateDirection Direction, + TranslateChannel? Channel, + string Speaker, + string Original, + string Translated, + string From, + string To, + string Error); + +internal sealed class ChatTranslator : IDisposable +{ + /// Prefix of every line the translator writes, so its own echoes are never re-translated. + public const string EchoPrefix = "[Translate]"; + + private const int EchoSpacingMs = 150; + private const int EchoMaxAttempts = 20; + private const int MaxInboundQueue = 40; + private const int DedupWindowMs = 5000; + private const int ResendGuardMs = 15000; + private const int SaveEveryMs = 2000; + private const int ErrorChatEveryMs = 30000; + private const int ChatTypeSystem = 1; + private const int ChatTypeSpellcasting = 0x11; + + private enum JobKind { Inbound, Outbound, SendRaw, Test } + + private sealed record Job(JobKind Kind, TranslateChannel? Channel, string Speaker, string Text, + string Source, string Target, string Prefix); + + private readonly RynthCoreHost _host; + private readonly Func _myName; + private readonly TranslateStore _store; + private readonly CancellationTokenSource _cts = new(); + + // Any thread → pump. + private readonly ConcurrentQueue _incoming = new(); + private readonly ConcurrentQueue<(Job Job, TranslateResult Result)> _done = new(); + // Translated bodies we are about to resend; OnChatBarEnter lets these through untouched. + private readonly ConcurrentDictionary _resend = new(StringComparer.Ordinal); + + // Pump thread only. + private readonly Queue _outQueue = new(); + private readonly LinkedList _inQueue = new(); + private readonly Dictionary _recent = new(StringComparer.Ordinal); + private readonly Queue<(string Text, int ChatType, int Attempts)> _echo = new(); + private long _lastEchoMs; + private long _lastStartMs; + private long _lastSaveMs; + private long _lastErrorChatMs = -ErrorChatEveryMs; + private int _inFlight; + + private readonly object _logLock = new(); + private readonly List _log = new(); + private TranslateLogEntry[] _logSnapshot = Array.Empty(); + + public TranslateSettings Settings { get; } + + /// Last provider error (empty after a success). Read by the UI. + public string LastError { get; private set; } = string.Empty; + + /// Characters sent to the provider this session (most plans bill per character). + public long CharsSent => Interlocked.Read(ref _charsSent); + private long _charsSent; + + public int Translated => Volatile.Read(ref _translated); + private int _translated; + + /// Requests waiting or in flight (approximate when read off the pump thread). + public int Pending => _inQueue.Count + _outQueue.Count + _incoming.Count + Volatile.Read(ref _inFlight); + + public ChatTranslator(RynthCoreHost host, Func myName, TranslateStore? store = null) + { + _host = host; + _myName = myName; + _store = store ?? new TranslateStore(); + Settings = _store.Load(); + } + + /// Per-login reset: send language back to the default, queues cleared. + public void ResetSession() + { + Settings.CurrentSendLanguage = Settings.DefaultSendLanguage; + while (_incoming.TryDequeue(out _)) { } + _outQueue.Clear(); + _inQueue.Clear(); + _echo.Clear(); + _recent.Clear(); + _resend.Clear(); + } + + // ── Entry points (any thread) ────────────────────────────────────────── + + /// Inbound chat line from the AC chat window. + public void OnChatWindowText(string text, int chatType) + { + var s = Settings; + if (!s.Enabled || !s.EnableInbound || string.IsNullOrEmpty(text)) return; + if (chatType == ChatTypeSpellcasting || text.StartsWith(EchoPrefix, StringComparison.Ordinal)) return; + if (!TryParseInbound(text, chatType, out var ch, out string speaker, out string msg, out bool own)) return; + if (!s.ListensTo(ch) || (own && s.SkipOwn)) return; + if (IsOwnName(speaker) && s.SkipOwn) return; + + msg = AcChatEscapes.Decode(msg).Trim(); + if (msg.Length == 0) return; + _incoming.Enqueue(new Job(JobKind.Inbound, ch, speaker, msg, s.InboundSource, s.MyLanguage, string.Empty)); + } + + /// + /// Typed chat line (OnChatBarEnter). Returns true when the translator took it over and the caller + /// must swallow the original. + /// + public bool TryInterceptOutbound(string text) + { + var s = Settings; + if (!TranslateChannels.TryParseOutbound(text, out var line)) return false; + string body = line.Body.Trim(); + if (_resend.TryRemove(body, out _)) return false; + if (!s.Enabled || !s.EnableOutbound || !s.SendsOn(line.Channel) || body.Length == 0) return false; + + if (s.RawPrefix.Length > 0 && body.StartsWith(s.RawPrefix, StringComparison.Ordinal)) + { + string raw = body.Substring(s.RawPrefix.Length).TrimStart(); + if (raw.Length == 0) return false; + _incoming.Enqueue(new Job(JobKind.SendRaw, line.Channel, string.Empty, raw, string.Empty, string.Empty, line.Prefix)); + return true; + } + + string target = s.CurrentSendLanguage; + if (TranslateLanguages.BaseOf(target) == TranslateLanguages.BaseOf(s.MyLanguage)) return false; + _incoming.Enqueue(new Job(JobKind.Outbound, line.Channel, string.Empty, body, TranslateLanguages.Auto, target, line.Prefix)); + return true; + } + + /// Translate window compose box: translate into the send language and send on . + public void Compose(TranslateChannel ch, string tellTarget, string text) + { + text = (text ?? string.Empty).Trim(); + if (text.Length == 0) return; + var s = Settings; + string prefix = TranslateChannels.SendPrefix(ch, tellTarget); + bool same = TranslateLanguages.BaseOf(s.CurrentSendLanguage) == TranslateLanguages.BaseOf(s.MyLanguage); + _incoming.Enqueue(same + ? new Job(JobKind.SendRaw, ch, string.Empty, text, string.Empty, string.Empty, prefix) + : new Job(JobKind.Outbound, ch, string.Empty, text, TranslateLanguages.Auto, s.CurrentSendLanguage, prefix)); + } + + /// Translates into (send language when null) without sending. + public void Test(string text, string? target = null) + { + text = (text ?? string.Empty).Trim(); + if (text.Length == 0) return; + _incoming.Enqueue(new Job(JobKind.Test, null, string.Empty, text, TranslateLanguages.Auto, + target ?? Settings.CurrentSendLanguage, string.Empty)); + } + + // ── Pump thread ──────────────────────────────────────────────────────── + + public void Tick() + { + long now = Environment.TickCount64; + DrainIncoming(now); + while (_done.TryDequeue(out var d)) ApplyResult(d.Job, d.Result); + StartNextRequest(now); + DrainEcho(now); + + if (now - _lastSaveMs >= SaveEveryMs) + { + _lastSaveMs = now; + PruneGuards(now); + _store.SaveIfDirty(Settings); + } + } + + private void DrainIncoming(long now) + { + while (_incoming.TryDequeue(out var job)) + { + switch (job.Kind) + { + case JobKind.SendRaw: + Send(job.Prefix, job.Text); + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, + job.Text, job.Text, string.Empty, string.Empty, "sent untranslated")); + break; + case JobKind.Inbound: + string key = $"{job.Channel}|{job.Speaker}|{job.Text}"; + if (_recent.TryGetValue(key, out long seen) && now - seen < DedupWindowMs) break; + _recent[key] = now; + while (_inQueue.Count >= MaxInboundQueue) _inQueue.RemoveFirst(); + _inQueue.AddLast(job); + break; + default: + _outQueue.Enqueue(job); + break; + } + } + } + + private void StartNextRequest(long now) + { + if (Volatile.Read(ref _inFlight) != 0) return; + if (now - _lastStartMs < Settings.MinIntervalMs) return; + + Job? job = null; + if (_outQueue.Count > 0) job = _outQueue.Dequeue(); + else if (_inQueue.Count > 0) { job = _inQueue.First!.Value; _inQueue.RemoveFirst(); } + if (job == null) return; + + var s = Settings; + if (!s.Enabled && job.Kind == JobKind.Inbound) return; + + _lastStartMs = now; + Volatile.Write(ref _inFlight, 1); + Interlocked.Add(ref _charsSent, job.Text.Length); + string provider = s.Provider, key = s.ApiKey, url = s.ApiUrl; + var ct = _cts.Token; + _ = Task.Run(async () => + { + TranslateResult r; + try { r = await TranslateClient.TranslateAsync(provider, key, url, job.Text, job.Source, job.Target, ct).ConfigureAwait(false); } + catch (Exception ex) { r = TranslateResult.Fail(ex.Message); } + _done.Enqueue((job, r)); + Volatile.Write(ref _inFlight, 0); + }); + } + + private void ApplyResult(Job job, TranslateResult r) + { + if (r.Ok) LastError = string.Empty; + else + { + LastError = r.Error; + RynthLog.Write(LogCat.Chat, $"[Translate] {job.Kind} failed: {r.Error}"); + } + + switch (job.Kind) + { + case JobKind.Inbound: ApplyInbound(job, r); break; + case JobKind.Outbound: ApplyOutbound(job, r); break; + case JobKind.Test: ApplyTest(job, r); break; + } + } + + private void ApplyInbound(Job job, TranslateResult r) + { + if (!r.Ok) + { + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text, + string.Empty, job.Source, job.Target, r.Error)); + ChatErrorThrottled(r.Error); + return; + } + + string translated = r.Text.Trim(); + // Already in the receive language, or nothing changed: stay quiet. + if (TranslateLanguages.BaseOf(r.DetectedSource) == TranslateLanguages.BaseOf(job.Target)) return; + if (translated.Length == 0 || string.Equals(translated, job.Text, StringComparison.OrdinalIgnoreCase)) return; + + Interlocked.Increment(ref _translated); + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text, + translated, r.DetectedSource, job.Target, string.Empty)); + + if (Settings.EchoToChat && job.Channel is { } ch) + { + string from = r.DetectedSource.Length > 0 ? $" ({r.DetectedSource})" : string.Empty; + QueueEcho($"{EchoPrefix} [{TranslateChannels.Name(ch)}] {job.Speaker}{from}: {translated}", TranslateChannels.ChatType(ch)); + } + } + + private void ApplyOutbound(Job job, TranslateResult r) + { + string body; + if (r.Ok && r.Text.Trim().Length > 0) + { + body = r.Text.Trim(); + Interlocked.Increment(ref _translated); + } + else if (Settings.SendOriginalOnError) + { + body = job.Text; + QueueEcho($"{EchoPrefix} Couldn't translate ({(r.Ok ? "empty result" : r.Error)}); sent the original.", ChatTypeSystem); + } + else + { + QueueEcho($"{EchoPrefix} Couldn't translate ({(r.Ok ? "empty result" : r.Error)}); message not sent.", ChatTypeSystem); + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text, + string.Empty, r.DetectedSource, job.Target, r.Ok ? "empty result" : r.Error)); + return; + } + + string sent = Send(job.Prefix, body); + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text, + sent, r.DetectedSource, job.Target, r.Ok ? string.Empty : r.Error)); + + if (r.Ok && Settings.EchoOutbound && job.Channel is { } ch) + QueueEcho($"{EchoPrefix} [{TranslateChannels.Name(ch)} -> {job.Target}] you typed: {job.Text}", TranslateChannels.ChatType(ch)); + } + + private void ApplyTest(Job job, TranslateResult r) + { + AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Test, null, string.Empty, job.Text, + r.Ok ? r.Text : string.Empty, r.DetectedSource, job.Target, r.Error)); + QueueEcho(r.Ok + ? $"{EchoPrefix} Test ({(r.DetectedSource.Length > 0 ? r.DetectedSource : "?")} -> {job.Target}): {r.Text}" + : $"{EchoPrefix} Test failed: {r.Error}", ChatTypeSystem); + } + + /// Sends + body through the chat parser; returns the body as sent. + private string Send(string prefix, string body) + { + string encoded = AcChatEscapes.EncodeForSend(body); + if (encoded.Length == 0) return string.Empty; + _resend[encoded] = Environment.TickCount64; + bool ok = _host.HasInvokeChatParser && _host.InvokeChatParser(prefix + encoded); + if (!ok) + { + _resend.TryRemove(encoded, out _); + QueueEcho($"{EchoPrefix} The client refused to send: {prefix}{encoded}", ChatTypeSystem); + } + return encoded; + } + + private void QueueEcho(string text, int chatType) => _echo.Enqueue((text, chatType, 0)); + + private void DrainEcho(long now) + { + if (_echo.Count == 0 || now - _lastEchoMs < EchoSpacingMs) return; + var (text, type, attempts) = _echo.Peek(); + _lastEchoMs = now; + if (_host.WriteToChat(text, type) || attempts + 1 >= EchoMaxAttempts) + { + _echo.Dequeue(); + return; + } + // Dropped by the host's rate limit: retry the same line next time. + _echo.Dequeue(); + var rest = _echo.ToArray(); + _echo.Clear(); + _echo.Enqueue((text, type, attempts + 1)); + foreach (var e in rest) _echo.Enqueue(e); + } + + private void ChatErrorThrottled(string error) + { + long now = Environment.TickCount64; + if (now - _lastErrorChatMs < ErrorChatEveryMs) return; + _lastErrorChatMs = now; + QueueEcho($"{EchoPrefix} Translation error: {error}", ChatTypeSystem); + } + + private void PruneGuards(long now) + { + foreach (var kv in _resend) + if (now - kv.Value > ResendGuardMs) _resend.TryRemove(kv.Key, out _); + if (_recent.Count > 256) + { + var stale = new List(); + foreach (var kv in _recent) if (now - kv.Value > DedupWindowMs) stale.Add(kv.Key); + foreach (var k in stale) _recent.Remove(k); + } + } + + // ── Log (pump writes, render reads) ──────────────────────────────────── + + private void AddLog(TranslateLogEntry e) + { + lock (_logLock) + { + _log.Add(e); + int max = Settings.MaxLog; + if (_log.Count > max) _log.RemoveRange(0, _log.Count - max); + _logSnapshot = _log.ToArray(); + } + } + + public TranslateLogEntry[] LogSnapshot() + { + lock (_logLock) return _logSnapshot; + } + + public void ClearLog() + { + lock (_logLock) + { + _log.Clear(); + _logSnapshot = Array.Empty(); + } + } + + // ── Inbound parsing ──────────────────────────────────────────────────── + + // "[General] " style tab prefix some servers / chat options put in front of channel lines. + private static readonly Regex RxBracket = new(@"^\[(?[A-Za-z ]{1,24})\]\s*", RegexOptions.CultureInvariant); + + // "You say ...", "You tell Bob, ..." — the server echo of your own lines. + private static readonly Regex RxOwn = new(@"^You\s+(?:say|tell)\b(?[^""]*)""(?.*)""\s*$", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + // "Bob says, "..."" / "Bob says on the General channel, "..."" / "Bob tells you, "..."" + private static readonly Regex RxSpeech = new(@"^(?.+?)\s+(?says|tells)\b(?[^""]*)""(?.*)""\s*$", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + private static readonly Regex RxOnChannel = new(@"on the (?[A-Za-z ]+?) channel", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// + /// Splits a chat line into channel, speaker and message. Channel comes from (in order) a "[Name]" + /// prefix, "on the X channel", "tells you", the chat colour, then words like "patron" / "vassal". + /// + internal static bool TryParseInbound(string raw, int chatType, out TranslateChannel channel, + out string speaker, out string message, out bool own) + { + channel = TranslateChannel.Local; + speaker = message = string.Empty; + own = false; + + string t = AcChatEscapes.StripLinks(raw).Trim(); + if (t.Length < 6 || t.IndexOf('"') < 0) return false; + + TranslateChannel? hint = null; + var b = RxBracket.Match(t); + if (b.Success && TranslateChannels.TryParse(b.Groups["b"].Value, out var bc)) + { + hint = bc; + t = t.Substring(b.Length); + } + + string mid; + bool tellsYou; + var mo = RxOwn.Match(t); + if (mo.Success) + { + own = true; + speaker = "You"; + mid = mo.Groups["mid"].Value; + message = mo.Groups["msg"].Value; + tellsYou = t.StartsWith("You tell", StringComparison.OrdinalIgnoreCase); + } + else + { + var m = RxSpeech.Match(t); + if (!m.Success) return false; + speaker = m.Groups["name"].Value.Trim().TrimStart('+'); + mid = m.Groups["mid"].Value; + message = m.Groups["msg"].Value; + tellsYou = m.Groups["verb"].Value == "tells" && mid.TrimStart().StartsWith("you", StringComparison.OrdinalIgnoreCase); + if (speaker.Length == 0 || speaker.Length > 40) return false; + } + + TranslateChannel? ch = hint; + if (ch == null) + { + var oc = RxOnChannel.Match(mid); + if (oc.Success && TranslateChannels.TryParse(oc.Groups["ch"].Value, out var named)) ch = named; + } + if (ch == null && tellsYou) ch = TranslateChannel.Tell; + ch ??= TranslateChannels.FromChatType(chatType); + ch ??= FromWords(mid); + if (ch == null) return false; + + channel = ch.Value; + return message.Trim().Length > 0; + } + + private static TranslateChannel? FromWords(string mid) + { + string m = mid.ToLowerInvariant(); + if (m.Contains("covassal")) return TranslateChannel.Covassals; + if (m.Contains("vassal")) return TranslateChannel.Vassals; + if (m.Contains("patron")) return TranslateChannel.Patron; + if (m.Contains("monarch")) return TranslateChannel.Monarch; + if (m.Contains("fellowship")) return TranslateChannel.Fellowship; + if (m.Contains("allegiance")) return TranslateChannel.Allegiance; + return null; + } + + private bool IsOwnName(string speaker) + { + string me; + try { me = _myName() ?? string.Empty; } + catch { return false; } + return me.Length > 0 && string.Equals(me.TrimStart('+'), speaker, StringComparison.OrdinalIgnoreCase); + } + + // ── Language helpers (UI + commands) ─────────────────────────────────── + + /// Swaps the receive and send languages for this session. + public void SwapLanguages() + { + var s = Settings; + string recv = s.MyLanguage; + s.MyLanguage = s.CurrentSendLanguage; + s.CurrentSendLanguage = recv; + } + + // ── /ra translate ────────────────────────────────────────────────────── + + /// + /// /ra translate [on|off|in on|off|out on|off|window|send <lang>|recv <lang>|default <lang>|swap|reset|test <text>|status] + /// + public void HandleCommand(string[] args, Action chat) + { + var s = Settings; + string verb = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; + string arg = args.Length > 1 ? args[1] : string.Empty; + switch (verb) + { + case "on": s.Enabled = true; chat($"{EchoPrefix} On. {StatusLine()}"); break; + case "off": s.Enabled = false; chat($"{EchoPrefix} Off."); break; + case "in": + case "out": + bool? v = arg.Equals("on", StringComparison.OrdinalIgnoreCase) ? true + : arg.Equals("off", StringComparison.OrdinalIgnoreCase) ? false : null; + if (verb == "in") s.EnableInbound = v ?? !s.EnableInbound; + else s.EnableOutbound = v ?? !s.EnableOutbound; + chat($"{EchoPrefix} Inbound {(s.EnableInbound ? "on" : "off")}, outbound {(s.EnableOutbound ? "on" : "off")}."); + break; + case "window": + case "show": + s.ShowWindow = !s.ShowWindow; + break; + case "send": + case "recv": + case "receive": + case "default": + string? code = TranslateLanguages.Normalize(arg); + if (code == null || code == TranslateLanguages.Auto) + { + chat($"{EchoPrefix} Unknown language '{arg}'. Codes: {string.Join(", ", TranslateLanguages.Codes, 1, TranslateLanguages.Codes.Length - 1)}"); + break; + } + if (verb == "send") s.CurrentSendLanguage = code; + else if (verb == "default") s.DefaultSendLanguage = code; + else s.MyLanguage = code; + chat($"{EchoPrefix} {StatusLine()}"); + break; + case "swap": + SwapLanguages(); + chat($"{EchoPrefix} {StatusLine()}"); + break; + case "reset": + s.CurrentSendLanguage = s.DefaultSendLanguage; + chat($"{EchoPrefix} {StatusLine()}"); + break; + case "test": + string text = string.Join(" ", args, 1, Math.Max(0, args.Length - 1)); + if (text.Length == 0) { chat($"{EchoPrefix} Usage: /ra translate test "); break; } + Test(text); + break; + default: + chat($"{EchoPrefix} {(s.Enabled ? "On" : "Off")}. {StatusLine()}" + + (LastError.Length > 0 ? $" Last error: {LastError}" : string.Empty)); + chat($"{EchoPrefix} /ra translate on|off | in|out [on|off] | window | send|recv|default | swap | reset | test "); + break; + } + } + + public string StatusLine() + { + var s = Settings; + return $"Receive {s.MyLanguage}, send {s.CurrentSendLanguage} (default {s.DefaultSendLanguage}), " + + $"inbound {(s.EnableInbound ? "on" : "off")}, outbound {(s.EnableOutbound ? "on" : "off")}, provider {s.Provider}" + + (s.ApiKey.Length == 0 && s.Provider != TranslateSettings.ProviderLibre ? " (no API key set)" : string.Empty) + "."; + } + + public void Dispose() + { + try { _cts.Cancel(); } catch { } + _store.SaveIfDirty(Settings); + _cts.Dispose(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateChannels.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateChannels.cs new file mode 100644 index 0000000..449c828 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateChannels.cs @@ -0,0 +1,186 @@ +// TranslateChannels.cs — AC chat channels the translator can listen to (inbound) or send on (outbound), +// plus parsing of typed slash commands and the chat colour used for local echoes. +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthAi.Translate; + +/// Values are bit positions in / OutboundMask; do not reorder. +internal enum TranslateChannel +{ + Local = 0, + Tell, + Fellowship, + Allegiance, + Patron, + Vassals, + Covassals, + Monarch, + General, + Trade, + Lfg, + Roleplay, + Society, + Olthoi, +} + +/// A typed chat line split into its channel, the text to keep verbatim, and the message body. +internal readonly record struct OutboundLine(TranslateChannel Channel, string Prefix, string Body, string TellTarget); + +internal static class TranslateChannels +{ + public static readonly TranslateChannel[] All = Enum.GetValues(); + + public static uint Bit(TranslateChannel ch) => 1u << (int)ch; + + public static string Name(TranslateChannel ch) => ch switch + { + TranslateChannel.Lfg => "LFG", + _ => ch.ToString(), + }; + + /// Accepts channel names and the usual short forms (case-insensitive). + public static bool TryParse(string? text, out TranslateChannel ch) + { + ch = TranslateChannel.Local; + if (string.IsNullOrWhiteSpace(text)) return false; + switch (text.Trim().ToLowerInvariant()) + { + case "local": case "say": case "area": ch = TranslateChannel.Local; return true; + case "tell": case "tells": case "t": ch = TranslateChannel.Tell; return true; + case "fellowship": case "fellow": case "f": ch = TranslateChannel.Fellowship; return true; + case "allegiance": case "alleg": case "a": ch = TranslateChannel.Allegiance; return true; + case "patron": case "p": ch = TranslateChannel.Patron; return true; + case "vassals": case "vassal": case "v": ch = TranslateChannel.Vassals; return true; + case "covassals": case "covassal": case "c": ch = TranslateChannel.Covassals; return true; + case "monarch": case "m": ch = TranslateChannel.Monarch; return true; + case "general": case "cg": case "g": ch = TranslateChannel.General; return true; + case "trade": case "ct": ch = TranslateChannel.Trade; return true; + case "lfg": case "looking for group": case "clfg": ch = TranslateChannel.Lfg; return true; + case "roleplay": case "rp": case "crp": ch = TranslateChannel.Roleplay; return true; + case "society": case "cs": ch = TranslateChannel.Society; return true; + case "olthoi": case "co": ch = TranslateChannel.Olthoi; return true; + default: return false; + } + } + + /// Chat colour for local echoes, so they land in the same chat tab as the source channel. + public static int ChatType(TranslateChannel ch) => ch switch + { + TranslateChannel.Local => 0x02, + TranslateChannel.Tell => 0x03, + TranslateChannel.Fellowship => 0x13, + TranslateChannel.Allegiance or TranslateChannel.Patron or TranslateChannel.Vassals + or TranslateChannel.Covassals or TranslateChannel.Monarch => 0x12, + TranslateChannel.General => 0x1B, + TranslateChannel.Trade => 0x1C, + TranslateChannel.Lfg => 0x1D, + TranslateChannel.Roleplay => 0x1E, + TranslateChannel.Olthoi => 0x20, + TranslateChannel.Society => 0x21, + _ => 0x01, + }; + + /// Channel implied by an inbound chat colour; null for generic colours (Channels / Social). + public static TranslateChannel? FromChatType(int chatType) => chatType switch + { + 0x02 => TranslateChannel.Local, + 0x03 => TranslateChannel.Tell, + 0x12 => TranslateChannel.Allegiance, + 0x13 => TranslateChannel.Fellowship, + 0x1B => TranslateChannel.General, + 0x1C => TranslateChannel.Trade, + 0x1D => TranslateChannel.Lfg, + 0x1E => TranslateChannel.Roleplay, + 0x20 => TranslateChannel.Olthoi, + 0x21 => TranslateChannel.Society, + _ => null, + }; + + /// + /// Command prefix used when the translator composes a line itself (Translate window). + /// A tell needs ; an empty target replies to the last tell. + /// + public static string SendPrefix(TranslateChannel ch, string? tellTarget) => ch switch + { + TranslateChannel.Local => string.Empty, + TranslateChannel.Tell => string.IsNullOrWhiteSpace(tellTarget) ? "/r " : $"/t {tellTarget.Trim()}, ", + TranslateChannel.Fellowship => "/f ", + TranslateChannel.Allegiance => "/a ", + TranslateChannel.Patron => "/p ", + TranslateChannel.Vassals => "/v ", + TranslateChannel.Covassals => "/c ", + TranslateChannel.Monarch => "/m ", + TranslateChannel.General => "/cg ", + TranslateChannel.Trade => "/ct ", + TranslateChannel.Lfg => "/clfg ", + TranslateChannel.Roleplay => "/crp ", + TranslateChannel.Society => "/cs ", + TranslateChannel.Olthoi => "/co ", + _ => string.Empty, + }; + + // "/cmd rest" or "@cmd rest"; the body keeps everything after the first run of whitespace. + private static readonly Regex RxSlash = new(@"^(?[/@][A-Za-z]+)(?\s+)(?.+)$", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + // Tell target and body: "Name, message". + private static readonly Regex RxTellArgs = new(@"^(?[^,]+?)\s*,\s*(?.+)$", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + /// + /// Splits a typed chat line into channel + verbatim prefix + body. Plain text is Local speech. + /// Returns false for slash commands that are not chat (emotes, /ra, /loc, ...). + /// + public static bool TryParseOutbound(string text, out OutboundLine line) + { + line = default; + if (string.IsNullOrWhiteSpace(text)) return false; + string t = text.Trim(); + + if (t[0] != '/' && t[0] != '@') + { + line = new OutboundLine(TranslateChannel.Local, string.Empty, t, string.Empty); + return true; + } + + var m = RxSlash.Match(t); + if (!m.Success) return false; + string cmd = m.Groups["cmd"].Value.Substring(1).ToLowerInvariant(); + string rest = m.Groups["rest"].Value; + string head = m.Groups["cmd"].Value + m.Groups["sp"].Value; + + TranslateChannel ch; + switch (cmd) + { + case "s": case "say": ch = TranslateChannel.Local; break; + case "f": case "fellowship": ch = TranslateChannel.Fellowship; break; + case "a": case "allegiance": ch = TranslateChannel.Allegiance; break; + case "p": case "patron": ch = TranslateChannel.Patron; break; + case "v": case "vassals": ch = TranslateChannel.Vassals; break; + case "c": case "covassals": ch = TranslateChannel.Covassals; break; + case "m": case "monarch": ch = TranslateChannel.Monarch; break; + case "cg": ch = TranslateChannel.General; break; + case "ct": ch = TranslateChannel.Trade; break; + case "clfg": ch = TranslateChannel.Lfg; break; + case "crp": case "rp": ch = TranslateChannel.Roleplay; break; + case "cs": ch = TranslateChannel.Society; break; + case "co": ch = TranslateChannel.Olthoi; break; + case "r": case "reply": + line = new OutboundLine(TranslateChannel.Tell, head, rest, string.Empty); + return true; + case "t": case "tell": + var tm = RxTellArgs.Match(rest); + if (!tm.Success) return false; + string msg = tm.Groups["msg"].Value; + string prefix = t.Substring(0, t.Length - msg.Length); + line = new OutboundLine(TranslateChannel.Tell, prefix, msg, tm.Groups["name"].Value.Trim()); + return true; + default: + return false; + } + + line = new OutboundLine(ch, head, rest, string.Empty); + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateClient.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateClient.cs new file mode 100644 index 0000000..97eb87b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateClient.cs @@ -0,0 +1,286 @@ +// TranslateClient.cs — HTTP calls to the translation providers. NativeAOT-safe: request JSON is written +// with Utf8JsonWriter and responses are read with JsonDocument (no reflection serialization). +// +// google Cloud Translation Basic v2 POST .../language/translate/v2?key=KEY {q,target,format,source?} +// deepl DeepL API v2 POST .../v2/translate Authorization: DeepL-Auth-Key KEY +// (keys ending ":fx" are Free-plan keys and must use api-free.deepl.com) +// libre LibreTranslate POST {server}/translate {q,source,target,format,api_key?} +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.Plugin.RynthAi.Translate; + +/// Outcome of one request. is empty when the provider didn't report it. +internal readonly record struct TranslateResult(bool Ok, string Text, string DetectedSource, string Error) +{ + public static TranslateResult Fail(string error) => new(false, string.Empty, string.Empty, error); +} + +internal static class TranslateClient +{ + public const string GoogleUrl = "https://translation.googleapis.com/language/translate/v2"; + public const string DeepLProUrl = "https://api.deepl.com/v2/translate"; + public const string DeepLFreeUrl = "https://api-free.deepl.com/v2/translate"; + public const string LibreUrl = "https://libretranslate.com"; + + private static readonly HttpClient Http = CreateHttp(); + + private static HttpClient CreateHttp() + { + var handler = new SocketsHttpHandler + { + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + PooledConnectionLifetime = TimeSpan.FromMinutes(5), + }; + var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthAi-Translate/1.0"); + http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return http; + } + + /// Endpoint shown in the UI when the URL box is blank. + public static string DefaultUrl(string provider, string apiKey) => provider switch + { + TranslateSettings.ProviderDeepL => IsDeepLFreeKey(apiKey) ? DeepLFreeUrl : DeepLProUrl, + TranslateSettings.ProviderLibre => LibreUrl, + _ => GoogleUrl, + }; + + private static bool IsDeepLFreeKey(string apiKey) + => apiKey.Trim().EndsWith(":fx", StringComparison.OrdinalIgnoreCase); + + /// + /// Translates from ("auto" = detect) into + /// . Never throws; failures come back as . + /// + public static async Task TranslateAsync(string provider, string apiKey, string apiUrl, + string text, string source, string target, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(text)) return TranslateResult.Fail("nothing to translate"); + apiKey = (apiKey ?? string.Empty).Trim(); + apiUrl = (apiUrl ?? string.Empty).Trim(); + bool auto = string.IsNullOrWhiteSpace(source) || source.Equals(TranslateLanguages.Auto, StringComparison.OrdinalIgnoreCase); + + try + { + return provider switch + { + TranslateSettings.ProviderDeepL => await DeepLAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false), + TranslateSettings.ProviderLibre => await LibreAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false), + _ => await GoogleAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false), + }; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return TranslateResult.Fail("request timed out"); + } + catch (OperationCanceledException) + { + return TranslateResult.Fail("cancelled"); + } + catch (HttpRequestException ex) + { + return TranslateResult.Fail("network error: " + ex.Message); + } + catch (Exception ex) + { + return TranslateResult.Fail($"{ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Google Cloud Translation Basic v2 ────────────────────────────────── + + private static async Task GoogleAsync(string key, string url, string text, string? source, string target, CancellationToken ct) + { + if (key.Length == 0) return TranslateResult.Fail("Google needs an API key (Cloud Translation API)."); + string baseUrl = url.Length == 0 ? GoogleUrl : url; + int q = baseUrl.IndexOf('?'); + if (q >= 0) baseUrl = baseUrl.Substring(0, q); + + string body = BuildJson(w => + { + w.WriteString("q", text); + w.WriteString("target", target); + w.WriteString("format", "text"); + if (source != null) w.WriteString("source", source); + }); + + using var req = new HttpRequestMessage(HttpMethod.Post, baseUrl + "?key=" + Uri.EscapeDataString(key)) + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + var (status, json) = await SendAsync(req, ct).ConfigureAwait(false); + if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json)); + + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("data", out var data) + && data.TryGetProperty("translations", out var arr) + && arr.ValueKind == JsonValueKind.Array && arr.GetArrayLength() > 0) + { + var first = arr[0]; + string translated = first.TryGetProperty("translatedText", out var t) ? t.GetString() ?? string.Empty : string.Empty; + string detected = first.TryGetProperty("detectedSourceLanguage", out var d) ? d.GetString() ?? string.Empty : source ?? string.Empty; + return new TranslateResult(true, WebUtility.HtmlDecode(translated), detected, string.Empty); + } + return TranslateResult.Fail("unexpected Google response: " + Truncate(json, 160)); + } + + // ── DeepL v2 ─────────────────────────────────────────────────────────── + + private static async Task DeepLAsync(string key, string url, string text, string? source, string target, CancellationToken ct) + { + if (key.Length == 0) return TranslateResult.Fail("DeepL needs an API key (Free keys end in :fx)."); + string endpoint = url.Length == 0 ? (IsDeepLFreeKey(key) ? DeepLFreeUrl : DeepLProUrl) : url; + + string body = BuildJson(w => + { + w.WriteStartArray("text"); + w.WriteStringValue(text); + w.WriteEndArray(); + w.WriteString("target_lang", DeepLTarget(target)); + if (source != null) w.WriteString("source_lang", DeepLSource(source)); + }); + + using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + req.Headers.TryAddWithoutValidation("Authorization", "DeepL-Auth-Key " + key); + var (status, json) = await SendAsync(req, ct).ConfigureAwait(false); + if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json)); + + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("translations", out var arr) + && arr.ValueKind == JsonValueKind.Array && arr.GetArrayLength() > 0) + { + var first = arr[0]; + string translated = first.TryGetProperty("text", out var t) ? t.GetString() ?? string.Empty : string.Empty; + string detected = first.TryGetProperty("detected_source_language", out var d) ? (d.GetString() ?? string.Empty).ToLowerInvariant() : string.Empty; + return new TranslateResult(true, translated, detected, string.Empty); + } + return TranslateResult.Fail("unexpected DeepL response: " + Truncate(json, 160)); + } + + /// DeepL target codes: upper-case, English / Portuguese need a regional variant. + private static string DeepLTarget(string code) => code.ToLowerInvariant() switch + { + "en" => "EN-US", + "pt" => "PT-BR", + "zh-cn" => "ZH-HANS", + "zh-tw" => "ZH-HANT", + "no" => "NB", + var c => c.ToUpperInvariant(), + }; + + /// DeepL source codes: base language only. + private static string DeepLSource(string code) + { + string b = TranslateLanguages.BaseOf(code); + return (b == "no" ? "nb" : b).ToUpperInvariant(); + } + + // ── LibreTranslate ───────────────────────────────────────────────────── + + private static async Task LibreAsync(string key, string url, string text, string? source, string target, CancellationToken ct) + { + string server = (url.Length == 0 ? LibreUrl : url).TrimEnd('/'); + string endpoint = server.EndsWith("/translate", StringComparison.OrdinalIgnoreCase) ? server : server + "/translate"; + + string body = BuildJson(w => + { + w.WriteString("q", text); + w.WriteString("source", source == null ? "auto" : LibreCode(source)); + w.WriteString("target", LibreCode(target)); + w.WriteString("format", "text"); + if (key.Length > 0) w.WriteString("api_key", key); + }); + + using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + var (status, json) = await SendAsync(req, ct).ConfigureAwait(false); + if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json)); + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.TryGetProperty("translatedText", out var t)) + { + string detected = root.TryGetProperty("detectedLanguage", out var d) && d.ValueKind == JsonValueKind.Object + && d.TryGetProperty("language", out var lang) + ? lang.GetString() ?? string.Empty + : source ?? string.Empty; + return new TranslateResult(true, t.GetString() ?? string.Empty, detected, string.Empty); + } + return TranslateResult.Fail("unexpected LibreTranslate response: " + Truncate(json, 160)); + } + + /// LibreTranslate uses "zh" for Simplified and "zt" for Traditional Chinese. + private static string LibreCode(string code) => code.ToLowerInvariant() switch + { + "zh-cn" => "zh", + "zh-tw" => "zt", + "no" => "nb", + var c => c, + }; + + // ── Shared helpers ───────────────────────────────────────────────────── + + private static async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpRequestMessage req, CancellationToken ct) + { + using var resp = await Http.SendAsync(req, ct).ConfigureAwait(false); + string body = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + return (resp.StatusCode, body); + } + + private static string BuildJson(Action writeProperties) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + writeProperties(w); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + /// Pulls the provider's error message (Google error.message, DeepL message, Libre error). + private static string ErrorText(HttpStatusCode status, string json) + { + string detail = string.Empty; + try + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.ValueKind == JsonValueKind.Object) + { + if (root.TryGetProperty("error", out var err)) + detail = err.ValueKind == JsonValueKind.Object && err.TryGetProperty("message", out var m) + ? m.GetString() ?? string.Empty + : err.ValueKind == JsonValueKind.String ? err.GetString() ?? string.Empty : string.Empty; + else if (root.TryGetProperty("message", out var msg)) + detail = msg.GetString() ?? string.Empty; + } + } + catch (JsonException) { detail = Truncate(json, 160); } + string hint = status switch + { + HttpStatusCode.Forbidden or HttpStatusCode.Unauthorized => " (check the API key)", + (HttpStatusCode)429 => " (rate limited, slow down)", + (HttpStatusCode)456 => " (DeepL quota used up)", + _ => string.Empty, + }; + return $"HTTP {(int)status}{hint}" + (detail.Length > 0 ? ": " + Truncate(detail, 200) : string.Empty); + } + + internal static string Truncate(string s, int max) + => string.IsNullOrEmpty(s) || s.Length <= max ? s ?? string.Empty : s.Substring(0, max) + "..."; +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs new file mode 100644 index 0000000..1265c6b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateLanguages.cs @@ -0,0 +1,92 @@ +// TranslateLanguages.cs — Language codes offered by the chat translator (ISO 639-1 / Google style). +// Providers that use other codes (DeepL upper-case, LibreTranslate "zh") are mapped in TranslateClient. +using System; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthAi.Translate; + +internal static class TranslateLanguages +{ + /// Pseudo-code meaning "let the provider detect the source language". + public const string Auto = "auto"; + + /// Codes in display order; index-aligned with . + public static readonly string[] Codes = + { + Auto, "en", "es", "fr", "de", "it", "pt", "nl", "sv", "no", "da", "fi", "pl", "cs", "hu", + "ro", "el", "tr", "ru", "uk", "ar", "he", "hi", "th", "vi", "id", "ja", "ko", "zh-CN", "zh-TW", + }; + + public static readonly string[] Names = + { + "Auto-detect", "English", "Spanish", "French", "German", "Italian", "Portuguese", "Dutch", "Swedish", + "Norwegian", "Danish", "Finnish", "Polish", "Czech", "Hungarian", "Romanian", "Greek", "Turkish", + "Russian", "Ukrainian", "Arabic", "Hebrew", "Hindi", "Thai", "Vietnamese", "Indonesian", "Japanese", + "Korean", "Chinese (Simplified)", "Chinese (Traditional)", + }; + + public static int IndexOf(string? code) + { + if (string.IsNullOrWhiteSpace(code)) return -1; + for (int i = 0; i < Codes.Length; i++) + if (string.Equals(Codes[i], code.Trim(), StringComparison.OrdinalIgnoreCase)) return i; + return -1; + } + + /// True when the code is in the list (auto only counts when ). + public static bool IsKnown(string? code, bool allowAuto) + { + int i = IndexOf(code); + return i > 0 || (i == 0 && allowAuto); + } + + /// Canonical spelling of a known code (e.g. "ZH-cn" → "zh-CN"); null when unknown. + public static string? Normalize(string? code) + { + int i = IndexOf(code); + return i < 0 ? null : Codes[i]; + } + + /// "Spanish (es)" for UI and chat feedback; unknown codes are shown as-is. + public static string Label(string? code) + { + int i = IndexOf(code); + return i < 0 ? (code ?? string.Empty) : i == 0 ? Names[0] : $"{Names[i]} ({Codes[i]})"; + } + + /// Base language of a code ("zh-CN" → "zh"), lower-case, for same-language checks. + public static string BaseOf(string? code) + { + if (string.IsNullOrWhiteSpace(code)) return string.Empty; + string c = code.Trim().ToLowerInvariant(); + int dash = c.IndexOf('-'); + return dash > 0 ? c.Substring(0, dash) : c; + } + + /// + /// ImGui language picker. Returns true when the selection changed. Render thread only. + /// + public static bool Combo(string label, ref string code, bool allowAuto, float width = 0f) + { + bool changed = false; + if (width > 0f) ImGui.SetNextItemWidth(width); + int current = IndexOf(code); + string preview = current < 0 ? code : current == 0 ? Names[0] : Codes[current]; + if (ImGui.BeginCombo(label, preview, ImGuiComboFlags.HeightLarge)) + { + for (int i = allowAuto ? 0 : 1; i < Codes.Length; i++) + { + bool selected = i == current; + if (ImGui.Selectable(i == 0 ? Names[0] : $"{Codes[i]} {Names[i]}", selected)) + { + code = Codes[i]; + changed = true; + } + if (selected) ImGui.SetItemDefaultFocus(); + } + ImGui.EndCombo(); + } + if (ImGui.IsItemHovered() && current > 0) ImGui.SetTooltip(Names[current]); + return changed; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateSettings.cs new file mode 100644 index 0000000..f9b9c7e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateSettings.cs @@ -0,0 +1,180 @@ +// TranslateSettings.cs — Chat translator settings, shared by every character (RynthAi\translate.json). +// Fields are written by the render thread (UI) and read by the pump thread; each one is a single +// reference / 32-bit value so reads never tear. The JSON keeps channels as names; the masks are the +// runtime form. +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Install; + +namespace RynthCore.Plugin.RynthAi.Translate; + +internal sealed class TranslateSettings +{ + public const string ProviderGoogle = "google"; + public const string ProviderDeepL = "deepl"; + public const string ProviderLibre = "libre"; + public static readonly string[] Providers = { ProviderGoogle, ProviderDeepL, ProviderLibre }; + public static readonly string[] ProviderNames = { "Google Cloud Translation", "DeepL", "LibreTranslate" }; + + /// Master switch; off means no API calls and no chat interception. + public bool Enabled; + + public string Provider = ProviderGoogle; + + /// Stored in plain text in translate.json. + public string ApiKey = string.Empty; + + /// Blank uses the provider's default endpoint (LibreTranslate needs a server URL). + public string ApiUrl = string.Empty; + + /// "Receive" language: inbound chat is translated into this. + public string MyLanguage = "en"; + + /// Source language of inbound chat; "auto" lets the provider detect it. + public string InboundSource = TranslateLanguages.Auto; + + /// Send language each session starts with (Advanced Settings > Translate). + public string DefaultSendLanguage = "es"; + + public bool EnableInbound = true; + public bool EnableOutbound; + + public List? InboundChannels; + public List? OutboundChannels; + + /// Skip your own lines inbound (the server echoes what you send). + public bool SkipOwn = true; + + /// Write inbound translations into chat (AC chat window and RynthChat). + public bool EchoToChat = true; + + /// After an outbound translation, show what you typed locally next to what was sent. + public bool EchoOutbound = true; + + /// When an outbound translation fails, send the original text instead of dropping it. + public bool SendOriginalOnError = true; + + /// Lines starting with this go out untranslated (the prefix is removed). + public string RawPrefix = "\\"; + + /// Minimum spacing between API requests. + public int MinIntervalMs = 750; + + /// Entries kept in the Translate window log. + public int MaxLog = 200; + + public bool ShowWindow; + + // ── Runtime only ──────────────────────────────────────────────────────── + + /// Send language for this session; starts as . + [JsonIgnore] public string CurrentSendLanguage = "es"; + + [JsonIgnore] public uint InboundMask; + [JsonIgnore] public uint OutboundMask; + + public bool ListensTo(TranslateChannel ch) => (InboundMask & TranslateChannels.Bit(ch)) != 0; + public bool SendsOn(TranslateChannel ch) => (OutboundMask & TranslateChannels.Bit(ch)) != 0; + + public static uint DefaultInboundMask() + => Mask(TranslateChannel.Tell, TranslateChannel.Fellowship, TranslateChannel.Allegiance, TranslateChannel.Patron, + TranslateChannel.Vassals, TranslateChannel.Covassals, TranslateChannel.Monarch, TranslateChannel.General, + TranslateChannel.Trade, TranslateChannel.Lfg, TranslateChannel.Roleplay, TranslateChannel.Society, + TranslateChannel.Olthoi); + + public static uint DefaultOutboundMask() + => Mask(TranslateChannel.Tell, TranslateChannel.Fellowship, TranslateChannel.Allegiance, + TranslateChannel.General, TranslateChannel.Roleplay); + + private static uint Mask(params TranslateChannel[] channels) + { + uint m = 0; + foreach (var ch in channels) m |= TranslateChannels.Bit(ch); + return m; + } + + internal static uint MaskFromNames(List? names, uint fallback) + { + if (names == null) return fallback; + uint m = 0; + foreach (var n in names) + if (TranslateChannels.TryParse(n, out var ch)) m |= TranslateChannels.Bit(ch); + return m; + } + + internal static List NamesFromMask(uint mask) + { + var list = new List(); + foreach (var ch in TranslateChannels.All) + if ((mask & TranslateChannels.Bit(ch)) != 0) list.Add(TranslateChannels.Name(ch)); + return list; + } +} + +/// Loads / saves ; writes only when the JSON changed. +internal sealed class TranslateStore +{ + private readonly string _path; + private string _lastJson = string.Empty; + + public TranslateStore(string? path = null) + => _path = path ?? Path.Combine(RynthInstallPaths.RynthAiDir, "translate.json"); + + public string FilePath => _path; + + public TranslateSettings Load() + { + TranslateSettings? s = null; + try + { + if (File.Exists(_path)) + { + string json = File.ReadAllText(_path); + s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.TranslateSettings); + if (s != null) _lastJson = json; + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, $"translate load {_path}"); } + s ??= new TranslateSettings(); + Normalize(s); + return s; + } + + public void SaveIfDirty(TranslateSettings s) + { + try + { + s.InboundChannels = TranslateSettings.NamesFromMask(s.InboundMask); + s.OutboundChannels = TranslateSettings.NamesFromMask(s.OutboundMask); + string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.TranslateSettings); + if (json == _lastJson) return; + string? dir = Path.GetDirectoryName(_path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = _path + ".tmp"; + File.WriteAllText(tmp, json); + File.Move(tmp, _path, overwrite: true); + _lastJson = json; + } + catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, $"translate save {_path}"); } + } + + /// Repairs unknown codes / out-of-range numbers and builds the runtime masks. + private static void Normalize(TranslateSettings s) + { + if (Array.IndexOf(TranslateSettings.Providers, s.Provider ?? string.Empty) < 0) s.Provider = TranslateSettings.ProviderGoogle; + s.ApiKey ??= string.Empty; + s.ApiUrl ??= string.Empty; + s.RawPrefix ??= string.Empty; + s.MyLanguage = TranslateLanguages.Normalize(s.MyLanguage) is { } my && my != TranslateLanguages.Auto ? my : "en"; + s.InboundSource = TranslateLanguages.Normalize(s.InboundSource) ?? TranslateLanguages.Auto; + s.DefaultSendLanguage = TranslateLanguages.Normalize(s.DefaultSendLanguage) is { } send && send != TranslateLanguages.Auto ? send : "es"; + s.CurrentSendLanguage = s.DefaultSendLanguage; + s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, 250, 10000); + s.MaxLog = Math.Clamp(s.MaxLog, 20, 2000); + s.InboundMask = TranslateSettings.MaskFromNames(s.InboundChannels, TranslateSettings.DefaultInboundMask()); + s.OutboundMask = TranslateSettings.MaskFromNames(s.OutboundChannels, TranslateSettings.DefaultOutboundMask()); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs new file mode 100644 index 0000000..c2c8e4f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Translate/TranslateUi.cs @@ -0,0 +1,348 @@ +// TranslateUi.cs — ImGui views for the chat translator. Render thread only. +// +// RenderWindow "Chat Translate" window: language row, log, compose box, channels, settings +// RenderSettings provider / key / languages / options (also the Advanced Settings > Translate page) +// RenderHubSection compact on/off + receive/send swap row for the Mini Remote +// +// Settings fields are edited in place (single-value writes the pump thread tolerates); anything that +// needs the pump thread goes through ChatTranslator's thread-safe enqueue methods. +using System; +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthAi.Translate; + +internal sealed class TranslateUi +{ + private static readonly Vector4 ColIn = new(0.45f, 0.85f, 0.95f, 1f); + private static readonly Vector4 ColOut = new(0.40f, 0.95f, 0.45f, 1f); + private static readonly Vector4 ColTest = new(0.95f, 0.80f, 0.35f, 1f); + private static readonly Vector4 ColError = new(0.95f, 0.45f, 0.40f, 1f); + private static readonly Vector4 ColDim = new(0.60f, 0.64f, 0.70f, 1f); + + private readonly ChatTranslator _tr; + private string _composeText = string.Empty; + private string _tellTarget = string.Empty; + private string _testText = string.Empty; + private TranslateChannel _composeChannel = TranslateChannel.Fellowship; + private bool _showKey; + private bool _refocusCompose; + private int _lastLogCount; + + public TranslateUi(ChatTranslator translator) => _tr = translator; + + private TranslateSettings S => _tr.Settings; + + // ── Window ───────────────────────────────────────────────────────────── + + public void RenderWindow() + { + var s = S; + if (!s.ShowWindow) return; + + ImGui.SetNextWindowSize(new Vector2(520, 420), ImGuiCond.FirstUseEver); + bool open = true; + bool visible = ImGui.Begin("Chat Translate##rynthtranslate", ref open, ImGuiWindowFlags.NoCollapse); + if (!open) s.ShowWindow = false; + if (!visible) { ImGui.End(); return; } + + RenderHeader(); + RenderLanguageRow("##win", 110f); + ImGui.Separator(); + + if (ImGui.BeginTabBar("##translatetabs")) + { + if (ImGui.BeginTabItem("Log")) { RenderLog(); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Compose")) { RenderCompose(); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Channels")) { RenderChannels(); ImGui.EndTabItem(); } + if (ImGui.BeginTabItem("Settings")) { RenderSettings("##win"); ImGui.EndTabItem(); } + ImGui.EndTabBar(); + } + ImGui.End(); + } + + private void RenderHeader() + { + var s = S; + ImGui.Checkbox("Enabled##trenabled", ref s.Enabled); + ImGui.SameLine(); + ImGui.Checkbox("Incoming##trin", ref s.EnableInbound); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate chat you receive into your receive language."); + ImGui.SameLine(); + ImGui.Checkbox("Outgoing##trout", ref s.EnableOutbound); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Translate what you type on the ticked Send channels before it goes out.\n" + + $"Start a line with '{s.RawPrefix}' to send it untranslated."); + ImGui.SameLine(); + ImGui.TextColored(ColDim, $"| {_tr.Translated} done, {_tr.CharsSent:N0} chars, {_tr.Pending} queued"); + + if (s.ApiKey.Length == 0 && s.Provider != TranslateSettings.ProviderLibre) + ImGui.TextColored(ColError, "No API key: open the Settings tab to add one."); + else if (_tr.LastError.Length > 0) + ImGui.TextColored(ColError, "Last error: " + _tr.LastError); + } + + /// Receive / swap / send / reset-to-default row (window and Advanced page). + public void RenderLanguageRow(string id, float comboWidth) + { + var s = S; + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Receive"); + ImGui.SameLine(); + string recv = s.MyLanguage; + if (TranslateLanguages.Combo("##recv" + id, ref recv, allowAuto: false, comboWidth)) s.MyLanguage = recv; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Incoming chat is translated into this language."); + ImGui.SameLine(); + if (ImGui.Button("<->##swap" + id)) _tr.SwapLanguages(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Swap the receive and send languages."); + ImGui.SameLine(); + ImGui.TextUnformatted("Send"); + ImGui.SameLine(); + string send = s.CurrentSendLanguage; + if (TranslateLanguages.Combo("##send" + id, ref send, allowAuto: false, comboWidth)) s.CurrentSendLanguage = send; + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"What you type is translated into this language.\nDefault: {TranslateLanguages.Label(s.DefaultSendLanguage)}"); + ImGui.SameLine(); + bool atDefault = s.CurrentSendLanguage == s.DefaultSendLanguage; + if (atDefault) ImGui.BeginDisabled(); + if (ImGui.Button("Default##senddef" + id)) s.CurrentSendLanguage = s.DefaultSendLanguage; + if (atDefault) ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); + } + + private void RenderLog() + { + var log = _tr.LogSnapshot(); + if (ImGui.SmallButton("Clear")) _tr.ClearLog(); + ImGui.SameLine(); + ImGui.TextColored(ColDim, $"{log.Length} entries (hover a line for the original)"); + + if (!ImGui.BeginChild("##trlog", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGui.EndChild(); return; } + foreach (var e in log) + { + var (tag, col) = e.Direction switch + { + TranslateDirection.In => ("IN ", ColIn), + TranslateDirection.Out => ("OUT", ColOut), + _ => ("TST", ColTest), + }; + ImGui.TextColored(ColDim, e.Time.ToString("HH:mm:ss")); + ImGui.SameLine(); + ImGui.TextColored(e.Error.Length > 0 && e.Translated.Length == 0 ? ColError : col, tag); + ImGui.SameLine(); + string ch = e.Channel is { } c ? $"[{TranslateChannels.Name(c)}] " : string.Empty; + string who = e.Speaker.Length > 0 ? e.Speaker + ": " : string.Empty; + string body = e.Translated.Length > 0 ? e.Translated : e.Original; + ImGui.TextWrapped($"{ch}{who}{body}"); + if (ImGui.IsItemHovered()) + { + string langs = e.From.Length > 0 || e.To.Length > 0 ? $"\n{(e.From.Length > 0 ? e.From : "?")} -> {e.To}" : string.Empty; + ImGui.SetTooltip($"Original: {e.Original}{langs}{(e.Error.Length > 0 ? "\n" + e.Error : string.Empty)}"); + } + } + // Follow new lines unless the user scrolled up. + if (log.Length != _lastLogCount && ImGui.GetScrollY() >= ImGui.GetScrollMaxY() - 20f) + ImGui.SetScrollHereY(1f); + _lastLogCount = log.Length; + ImGui.EndChild(); + } + + private void RenderCompose() + { + var s = S; + ImGui.TextWrapped($"Type in any language; it is translated into {TranslateLanguages.Label(s.CurrentSendLanguage)} and sent on the chosen channel."); + ImGui.Spacing(); + + ImGui.SetNextItemWidth(140f); + if (ImGui.BeginCombo("Channel##trcompose", TranslateChannels.Name(_composeChannel))) + { + foreach (var ch in TranslateChannels.All) + if (ImGui.Selectable(TranslateChannels.Name(ch), ch == _composeChannel)) _composeChannel = ch; + ImGui.EndCombo(); + } + if (_composeChannel == TranslateChannel.Tell) + { + ImGui.SameLine(); + ImGui.SetNextItemWidth(160f); + ImGui.InputTextWithHint("##trtell", "name (blank = reply)", ref _tellTarget, 64u); + } + + ImGui.SetNextItemWidth(-1f); + if (_refocusCompose) + { + ImGui.SetKeyboardFocusHere(); + _refocusCompose = false; + } + bool enter = ImGui.InputTextWithHint("##trcomposetext", "message", ref _composeText, 400u, ImGuiInputTextFlags.EnterReturnsTrue); + if (ImGui.Button("Translate && send") || enter) + { + if (_composeText.Trim().Length > 0) + { + _tr.Compose(_composeChannel, _tellTarget, _composeText); + _composeText = string.Empty; + _refocusCompose = enter; + } + } + ImGui.SameLine(); + if (ImGui.Button("Preview only")) _tr.Test(_composeText); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate without sending; the result appears in the Log tab and chat."); + if (!s.Enabled) ImGui.TextColored(ColDim, "The compose box works even while auto-translate is off."); + } + + private void RenderChannels() + { + var s = S; + ImGui.TextWrapped("Listen: incoming lines on these channels are translated into your receive language. " + + "Send: lines you type on these channels are translated into your send language."); + if (ImGui.SmallButton("Listen all")) s.InboundMask = AllMask(); + ImGui.SameLine(); + if (ImGui.SmallButton("Listen none")) s.InboundMask = 0; + ImGui.SameLine(); + if (ImGui.SmallButton("Send all")) s.OutboundMask = AllMask(); + ImGui.SameLine(); + if (ImGui.SmallButton("Send none")) s.OutboundMask = 0; + ImGui.SameLine(); + if (ImGui.SmallButton("Defaults")) + { + s.InboundMask = TranslateSettings.DefaultInboundMask(); + s.OutboundMask = TranslateSettings.DefaultOutboundMask(); + } + + if (!ImGui.BeginTable("##trchannels", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp)) + return; + ImGui.TableSetupColumn("Channel", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Listen", ImGuiTableColumnFlags.WidthFixed, 60f); + ImGui.TableSetupColumn("Send", ImGuiTableColumnFlags.WidthFixed, 60f); + ImGui.TableHeadersRow(); + foreach (var ch in TranslateChannels.All) + { + uint bit = TranslateChannels.Bit(ch); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(TranslateChannels.Name(ch)); + if (ch == TranslateChannel.Local && ImGui.IsItemHovered()) + ImGui.SetTooltip("Local speech includes NPCs; listening here uses more of your API quota."); + ImGui.TableNextColumn(); + bool inOn = (s.InboundMask & bit) != 0; + if (ImGui.Checkbox("##in" + (int)ch, ref inOn)) s.InboundMask = inOn ? s.InboundMask | bit : s.InboundMask & ~bit; + ImGui.TableNextColumn(); + bool outOn = (s.OutboundMask & bit) != 0; + if (ImGui.Checkbox("##out" + (int)ch, ref outOn)) s.OutboundMask = outOn ? s.OutboundMask | bit : s.OutboundMask & ~bit; + } + ImGui.EndTable(); + } + + private static uint AllMask() + { + uint m = 0; + foreach (var ch in TranslateChannels.All) m |= TranslateChannels.Bit(ch); + return m; + } + + // ── Settings (window tab + Advanced Settings page) ───────────────────── + + public void RenderSettings(string id) + { + var s = S; + + ImGui.TextColored(ColIn, "Service"); + int provider = Math.Max(0, Array.IndexOf(TranslateSettings.Providers, s.Provider)); + ImGui.SetNextItemWidth(220f); + if (ImGui.Combo("Provider" + id, ref provider, TranslateSettings.ProviderNames, TranslateSettings.ProviderNames.Length)) + s.Provider = TranslateSettings.Providers[provider]; + ImGui.TextColored(ColDim, ProviderHint(s.Provider)); + + var keyFlags = _showKey ? ImGuiInputTextFlags.None : ImGuiInputTextFlags.Password; + ImGui.SetNextItemWidth(300f); + ImGui.InputTextWithHint("API key" + id, s.Provider == TranslateSettings.ProviderLibre ? "optional" : "required", + ref s.ApiKey, 256u, keyFlags); + ImGui.SameLine(); + ImGui.Checkbox("Show" + id + "key", ref _showKey); + + ImGui.SetNextItemWidth(300f); + ImGui.InputTextWithHint("Endpoint" + id, TranslateClient.DefaultUrl(s.Provider, s.ApiKey), ref s.ApiUrl, 256u); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Leave blank for the provider's default.\nLibreTranslate: your server URL, e.g. http://localhost:5000"); + + ImGui.Spacing(); + ImGui.TextColored(ColIn, "Languages"); + string my = s.MyLanguage; + if (TranslateLanguages.Combo("Receive (my language)" + id, ref my, allowAuto: false, 180f)) s.MyLanguage = my; + string src = s.InboundSource; + if (TranslateLanguages.Combo("Incoming chat is in" + id, ref src, allowAuto: true, 180f)) s.InboundSource = src; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Auto-detect works for mixed channels; pick a language to force it."); + string def = s.DefaultSendLanguage; + if (TranslateLanguages.Combo("Default send language" + id, ref def, allowAuto: false, 180f)) + { + // Following the default keeps the hub in step unless the user picked something else this session. + if (s.CurrentSendLanguage == s.DefaultSendLanguage) s.CurrentSendLanguage = def; + s.DefaultSendLanguage = def; + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Each login starts with this send language; swap it any time from the Mini Remote."); + + ImGui.Spacing(); + ImGui.TextColored(ColIn, "Behaviour"); + ImGui.Checkbox("Skip my own lines" + id, ref s.SkipOwn); + ImGui.Checkbox("Write incoming translations to chat" + id, ref s.EchoToChat); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Shown as \"[Translate] [Channel] Name (lang): text\" in AC chat and RynthChat,\nin the same tab as the original. Always kept in the Translate log."); + ImGui.Checkbox("Show what I typed after sending a translation" + id, ref s.EchoOutbound); + ImGui.Checkbox("Send the original if translation fails" + id, ref s.SendOriginalOnError); + ImGui.SetNextItemWidth(60f); + ImGui.InputText("Send-untranslated prefix" + id, ref s.RawPrefix, 4u); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A typed line starting with this goes out as-is (prefix removed)."); + ImGui.SetNextItemWidth(180f); + if (ImGui.SliderInt("Min ms between requests" + id, ref s.MinIntervalMs, 250, 5000)) s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, 250, 10000); + ImGui.SetNextItemWidth(180f); + if (ImGui.SliderInt("Log size" + id, ref s.MaxLog, 20, 1000)) s.MaxLog = Math.Clamp(s.MaxLog, 20, 2000); + + ImGui.Spacing(); + ImGui.TextColored(ColIn, "Test"); + ImGui.SetNextItemWidth(260f); + bool go = ImGui.InputTextWithHint("##trtest" + id, "text to translate", ref _testText, 400u, ImGuiInputTextFlags.EnterReturnsTrue); + ImGui.SameLine(); + if ((ImGui.Button("Test" + id) || go) && _testText.Trim().Length > 0) _tr.Test(_testText); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translates into the current send language and prints the result in chat."); + + ImGui.Spacing(); + ImGui.TextColored(ColDim, "Shared by all characters. The API key is stored in plain text in RynthAi\\translate.json."); + ImGui.TextColored(ColDim, "AC's chat font can't draw CJK / Thai / Arabic script; those show as boxes."); + } + + private static string ProviderHint(string provider) => provider switch + { + TranslateSettings.ProviderDeepL => "DeepL API key (deepl.com/pro-api). Free plan keys end in :fx, 500k chars/month.", + TranslateSettings.ProviderLibre => "Self-hosted or public LibreTranslate server; libretranslate.com needs a key.", + _ => "Cloud Translation API key (console.cloud.google.com), 500k chars/month free.", + }; + + // ── Mini Remote section ──────────────────────────────────────────────── + + public void RenderHubSection() + { + var s = S; + ImGui.PushID("##mrtranslate"); + ImGui.Checkbox("Translate", ref s.Enabled); + if (ImGui.IsItemHovered()) ImGui.SetTooltip(_tr.StatusLine() + (_tr.LastError.Length > 0 ? "\nLast error: " + _tr.LastError : string.Empty)); + ImGui.SameLine(); + if (ImGui.SmallButton("Window")) s.ShowWindow = !s.ShowWindow; + + string recv = s.MyLanguage; + if (TranslateLanguages.Combo("##mrrecv", ref recv, allowAuto: false, 62f)) s.MyLanguage = recv; + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Receive: {TranslateLanguages.Label(s.MyLanguage)}"); + ImGui.SameLine(); + if (ImGui.Button("<->")) _tr.SwapLanguages(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Swap receive and send languages."); + ImGui.SameLine(); + string send = s.CurrentSendLanguage; + if (TranslateLanguages.Combo("##mrsend", ref send, allowAuto: false, 62f)) s.CurrentSendLanguage = send; + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Send: {TranslateLanguages.Label(s.CurrentSendLanguage)}"); + // Right-click belongs to the Mini Remote options menu, so the reset is a button. + if (s.CurrentSendLanguage != s.DefaultSendLanguage) + { + ImGui.SameLine(); + if (ImGui.SmallButton("def")) s.CurrentSendLanguage = s.DefaultSendLanguage; + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage})."); + } + ImGui.PopID(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/UiPlacement.cs b/Plugins/RynthCore.Plugin.RynthAi/UiPlacement.cs new file mode 100644 index 0000000..fd7dfee --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/UiPlacement.cs @@ -0,0 +1,54 @@ +// UiPlacement.cs - Shared first-use placement and off-screen rescue for RynthAi's floating +// ImGui windows (render thread only). +// +// Windows with no imgui.ini entry open near the middle of the game view instead of ImGui's +// default (60,60), where a popped-out panel above the game frame would hide them. A window +// whose saved position leaves it (almost) off the game view is moved back to the middle. +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthAi; + +internal static class UiPlacement +{ + /// Pixels of a window that must stay inside the game view to count as on-screen. + private const float MinVisible = 40f; + + private static readonly Vector2 CenterPivot = new(0.5f, 0.5f); + + /// + /// Before Begin: if the window has no saved position, centre it in the game view, shifted by + /// so windows opened together don't stack exactly. + /// + public static void CenterFirstUse(Vector2 offset = default) + { + Vector2 display = ImGui.GetIO().DisplaySize; + if (display.X <= 1 || display.Y <= 1) return; // no display size yet: ImGui's default spot + ImGui.SetNextWindowPos(display * 0.5f + offset, ImGuiCond.FirstUseEver, CenterPivot); + } + + /// + /// Between Begin and End, once per show ( is cleared by the + /// caller while the window is hidden): moves the window to the middle of the game view if + /// less than 40 px of it is on screen. Returns true when it moved the window. + /// + public static bool RescueOncePerShow(ref bool checkedThisShow) + { + if (checkedThisShow) return false; + checkedThisShow = true; + + Vector2 pos = ImGui.GetWindowPos(); + Vector2 size = ImGui.GetWindowSize(); + Vector2 display = ImGui.GetIO().DisplaySize; + if (display.X <= MinVisible * 2 || display.Y <= MinVisible * 2) return false; + if (IsOnScreen(pos, size, display)) return false; + + ImGui.SetWindowPos(Vector2.Max(Vector2.Zero, (display - size) * 0.5f)); + return true; + } + + /// True when at least 40 px of the window overlaps the game view on each axis. + public static bool IsOnScreen(Vector2 pos, Vector2 size, Vector2 display) => + pos.X + size.X >= MinVisible && pos.Y + size.Y >= MinVisible + && pos.X <= display.X - MinVisible && pos.Y <= display.Y - MinVisible; +} diff --git a/Shared/RynthInstallPaths.cs b/Shared/RynthInstallPaths.cs new file mode 100644 index 0000000..89d64ab --- /dev/null +++ b/Shared/RynthInstallPaths.cs @@ -0,0 +1,128 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace RynthCore.Install; + +/// +/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick +/// both folders and records them under Software\Rynth (HKCU for a per-user install, +/// HKLM for an all-users install), so nothing may assume C:\Games\... any more. +/// +/// Resolution order per folder: environment override (RYNTHCORE_DIR / +/// RYNTHSUITE_DIR, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit +/// installer writes) → the historical default under C:\Games. Results are cached +/// for the life of the process. +/// +/// Linked into the RynthAi plugin and the Loot / Monster editors. RynthCore keeps an identical copy in +/// src/RynthCore.App/RynthInstallPaths.cs (engine, launcher, injector) — change both together. +/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming +/// without pulling in Microsoft.Win32.Registry. +/// +internal static class RynthInstallPaths +{ + /// Default RynthCore folder (pre-2026.10.4.2 installs always used this). + public const string DefaultCoreDir = @"C:\Games\RynthCore"; + + /// Default RynthSuite folder (pre-2026.10.4.2 installs always used this). + public const string DefaultSuiteDir = @"C:\Games\RynthSuite"; + + /// Registry key (under HKCU or HKLM) written by the installer. + public const string RegistryKey = @"Software\Rynth"; + + private static string? _coreDir; + private static string? _suiteDir; + + /// RynthCore install folder (launcher, Runtime\, Logs\, Tools\). + public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir); + + /// RynthSuite folder (plugins and their data, e.g. RynthAi\). + public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir); + + /// Unified RynthCore log folder (<CoreDir>\Logs). + public static string CoreLogsDir => Path.Combine(CoreDir, "Logs"); + + /// RynthAi plugin home and data root (<SuiteDir>\RynthAi). + public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi"); + + /// Reads a string value from Software\Rynth (HKCU first, then HKLM 32-bit view); null when absent. + public static string? ReadSetting(string valueName) + => ReadRegistryString(HKEY_CURRENT_USER, valueName, 0) + ?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY); + + /// Deletes a value from HKCU Software\Rynth (used for one-shot installer hand-offs). Best effort. + public static void DeleteUserSetting(string valueName) + { + try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { } + } + + private static string Resolve(string envVar, string valueName, string fallback) + { + string? fromEnv = null; + try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { } + + foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) }) + { + string? normalized = Normalize(candidate); + if (normalized != null) return normalized; + } + return fallback; + } + + /// Accepts only absolute paths; trims whitespace, quotes and trailing separators. + private static string? Normalize(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return null; + string p = path.Trim().Trim('"').TrimEnd('\\', '/'); + if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\" + try + { + if (!Path.IsPathFullyQualified(p)) return null; + string full = Path.GetFullPath(p); + return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root + } + catch + { + return null; + } + } + + // ── Win32 registry (advapi32) ─────────────────────────────────────────── + + private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001)); + private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002)); + private const uint RRF_RT_REG_SZ = 0x00000002; + private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004; + private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000; + private const int ERROR_SUCCESS = 0; + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags, + IntPtr pdwType, char[]? pvData, ref uint pcbData); + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName); + + private static string? ReadRegistryString(IntPtr root, string valueName, uint viewFlags) + { + try + { + uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags; + uint bytes = 0; + if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2) + return null; + + var buffer = new char[(bytes + 1) / 2]; + if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS) + return null; + + int len = Array.IndexOf(buffer, '\0'); + return new string(buffer, 0, len >= 0 ? len : buffer.Length); + } + catch + { + // Missing advapi32 entry point or access denied — fall back to the defaults. + return null; + } + } +} diff --git a/Shared/UbMobSeed.cs b/Shared/UbMobSeed.cs new file mode 100644 index 0000000..fbdf56d --- /dev/null +++ b/Shared/UbMobSeed.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; + +namespace RynthCore.CreatureSeed; + +/// +/// Monster damage-type seed derived from UtilityBelt's mob_damage_insights.ldb. +/// Written by the Monster Editor ("Import UB damage insights"); read (never written) +/// by the RynthAi plugin as a fallback for the "Auto" damage type when a monster +/// has no appraised resists yet. +/// File: <SuiteDir>\RynthAi\CreatureData\ub-mob-seed.json. +/// Compiled into both projects so the schema cannot drift; plain properties with +/// defaults keep it source-generator (NativeAOT) friendly. +/// +public sealed class UbMobSeedFile +{ + /// Current schema version written by the importer. + public const int CurrentVersion = 1; + + /// File name inside RynthAi\CreatureData. + public const string FileName = "ub-mob-seed.json"; + + /// Schema version of this file; readers ignore files with a newer major version. + public int Version { get; set; } = CurrentVersion; + + /// UTC time the importer produced the file (ISO-8601). + public string GeneratedUtc { get; set; } = string.Empty; + + /// Most common UB world name across the imported rows (e.g. "InfiniteLeaftide"). + public string World { get; set; } = string.Empty; + + /// Hits a damage type needs before it is ranked at all. + public int MinHitsPerType { get; set; } + + /// Source databases that contributed rows (full paths, for traceability). + public List Sources { get; set; } = new(); + + /// One entry per monster with at least two comparable damage types. + public List Entries { get; set; } = new(); +} + +/// Seeded damage-type ranking for one monster. +public sealed class UbMobSeedEntry +{ + /// Weenie class id; 0 for name-only rows imported from Mag-Tools. + public uint Wcid { get; set; } + + /// Last display name UB saw for this monster. + public string Name { get; set; } = string.Empty; + + /// "ub" (live UB wcid rows) or "magtools" (name-keyed Mag-Tools XML imports). + public string Source { get; set; } = string.Empty; + + /// All hits UB recorded against this monster (every type, including unranked ones). + public long TotalHits { get; set; } + + /// Ranked damage types, best first. Only types meeting the hit threshold are listed. + public List Elements { get; set; } = new(); +} + +/// Observed outgoing-damage statistics for one damage type against one monster. +public sealed class UbMobSeedElement +{ + /// RynthAi element name: Slash, Pierce, Bludgeon, Fire, Cold, Lightning, Acid or Nether. + public string Element { get; set; } = string.Empty; + + /// Hits recorded with this damage type. + public int Hits { get; set; } + + /// Average damage per hit with this damage type. + public double AvgDamage { get; set; } + + /// Largest single hit (0 for Mag-Tools rows, which do not record it). + public long MaxHit { get; set; } + + /// Relative effectiveness 0..1 (1 = best type for this monster); used for the ranking. + public double Score { get; set; } +} diff --git a/Tools/RynthCore.MonsterEditor/JsonContext.cs b/Tools/RynthCore.MonsterEditor/JsonContext.cs index 2aed3a6..526041c 100644 --- a/Tools/RynthCore.MonsterEditor/JsonContext.cs +++ b/Tools/RynthCore.MonsterEditor/JsonContext.cs @@ -5,5 +5,7 @@ namespace RynthCore.MonsterEditor; [JsonSerializable(typeof(List))] [JsonSerializable(typeof(EditorSettings))] +// UB damage-insights seed written for the RynthAi plugin (see UbMobSeedImport). +[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))] [JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true)] internal partial class EditorJsonContext : JsonSerializerContext { } diff --git a/Tools/RynthCore.MonsterEditor/Models.cs b/Tools/RynthCore.MonsterEditor/Models.cs index 5e0666f..e2ba0de 100644 --- a/Tools/RynthCore.MonsterEditor/Models.cs +++ b/Tools/RynthCore.MonsterEditor/Models.cs @@ -15,10 +15,22 @@ public class MonsterRule : INotifyPropertyChanged private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast; private string _exVuln = "None"; private int _offhandId; + private int _preferredAmmoItemId; private string _petDamage = "PAuto"; + /// Dashboard-only label; optional (empty shows as "Default" in the game UI). + private string _category = string.Empty; + /// vTank-style match expression. Empty = for named rules, match on Name substring; for the Default row, it is the global fallback when nothing else matches. + private string _matchExpression = string.Empty; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } } + public string Category { get => _category; set { _category = value ?? string.Empty; OnPropertyChanged(); } } + /// vTank-style match expression. Empty matches on the rule name. + public string MatchExpression + { + get => _matchExpression; + set { _matchExpression = value ?? string.Empty; OnPropertyChanged(); } + } public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } } public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } } public bool Fester { get => _fester; set { _fester = value; OnPropertyChanged(); } } @@ -34,11 +46,70 @@ public class MonsterRule : INotifyPropertyChanged public bool UseBlast { get => _useBlast; set { _useBlast = value; OnPropertyChanged(); } } public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } } public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } } + /// Optional loose ammo stack id for missile combat while this rule matches (0 = auto). + public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } } public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } } [JsonIgnore] + /// True for the special row named "Default" — the catch-all when no other rule matches. public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase); + /// Full copy (for import merge). Copies every rule field, UseBlast included. + public MonsterRule Clone() + { + return new MonsterRule + { + Name = _name, + Category = _category, + MatchExpression = _matchExpression, + Priority = _priority, + DamageType = _damageType, + WeaponId = _weaponId, + Fester = _fester, + Broadside = _broadside, + GravityWell = _gravityWell, + Imperil = _imperil, + Yield = _yield, + Vuln = _vuln, + UseArc = _useArc, + UseBolt = _useBolt, + UseRing = _useRing, + UseStreak = _useStreak, + UseBlast = _useBlast, + ExVuln = _exVuln, + OffhandId = _offhandId, + PreferredAmmoItemId = _preferredAmmoItemId, + PetDamage = _petDamage, + }; + } + + /// Overwrites combat fields (used to merge a VT Default row into the Rynth Default row). + public void CopyCombatSettingsFrom(MonsterRule? src) + { + if (src == null) return; + // Keep Name: must stay "Default". Use public setters so the grid updates. + Category = src.Category; + MatchExpression = src.MatchExpression; + Priority = src.Priority; + DamageType = src.DamageType; + WeaponId = src.WeaponId; + Fester = src.Fester; + Broadside = src.Broadside; + GravityWell = src.GravityWell; + Imperil = src.Imperil; + Yield = src.Yield; + Vuln = src.Vuln; + UseArc = src.UseArc; + UseBolt = src.UseBolt; + UseRing = src.UseRing; + UseStreak = src.UseStreak; + UseBlast = src.UseBlast; + ExVuln = src.ExVuln; + OffhandId = src.OffhandId; + PreferredAmmoItemId = src.PreferredAmmoItemId; + PetDamage = src.PetDamage; + } + public event PropertyChangedEventHandler? PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); diff --git a/Tools/RynthCore.MonsterEditor/RynthCore.MonsterEditor.csproj b/Tools/RynthCore.MonsterEditor/RynthCore.MonsterEditor.csproj index d900897..36d64ac 100644 --- a/Tools/RynthCore.MonsterEditor/RynthCore.MonsterEditor.csproj +++ b/Tools/RynthCore.MonsterEditor/RynthCore.MonsterEditor.csproj @@ -16,6 +16,18 @@ + + + + + + + + + + + + diff --git a/Tools/RynthCore.MonsterEditor/UbMobSeedImport.cs b/Tools/RynthCore.MonsterEditor/UbMobSeedImport.cs new file mode 100644 index 0000000..72ba1b6 --- /dev/null +++ b/Tools/RynthCore.MonsterEditor/UbMobSeedImport.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using LiteDB; +using RynthCore.CreatureSeed; +// LiteDB ships its own JsonSerializer; the seed is written with System.Text.Json (source-generated). +using StjSerializer = System.Text.Json.JsonSerializer; + +namespace RynthCore.MonsterEditor; + +/// +/// Converts UtilityBelt's mob_damage_insights.ldb (LiteDB 5) into the RynthAi +/// damage-type seed (). Runs here rather than in the plugin +/// because LiteDB is reflection-heavy and the RynthAi plugin is NativeAOT. +/// +/// UB rows record damage players dealt TO each monster, per damage type. The +/// per-character databases are pushed into the shared server database every 12 hours, +/// so they are mostly a subset of it: for each monster the single row with the most hits +/// wins (summing would double-count). +/// +/// +internal static class UbMobSeedImport +{ + /// Hits a damage type needs before it is ranked. + public const int DefaultMinHitsPerType = 20; + + private const string DbFileName = "mob_damage_insights.ldb"; + private const string WcidCollection = "mob_damage_agg"; + private const string MagCollection = "mob_mag_name_agg"; + + /// UB damage-type flags (ACE DamageType) mapped to RynthAi element names. + /// Normal (0) and combined flags are not castable choices and are skipped. + private static readonly Dictionary FlagToElement = new() + { + ["1"] = "Slash", + ["2"] = "Pierce", + ["4"] = "Bludgeon", + ["8"] = "Cold", + ["16"] = "Fire", + ["32"] = "Acid", + ["64"] = "Lightning", + ["1024"] = "Nether", + }; + + /// Outcome of an import run. + public sealed record Result(bool Ok, string Message, UbMobSeedFile? Seed); + + /// UB's per-world folder for InfiniteLeaftide (holds the shared server database). + public static string DefaultServerFolder => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "Decal Plugins", "UtilityBelt", "InfiniteLeaftide"); + + /// Where the plugin reads the seed: <SuiteDir>\RynthAi\CreatureData\ub-mob-seed.json. + public static string DefaultOutputPath => Path.Combine( + RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName); + + /// + /// Lists the shared server database (first) and every per-character database + /// one level below it. + /// + public static List FindDatabases(string serverFolder) + { + var list = new List(); + if (!Directory.Exists(serverFolder)) return list; + + string shared = Path.Combine(serverFolder, DbFileName); + if (File.Exists(shared)) list.Add(shared); + + foreach (string dir in Directory.GetDirectories(serverFolder).OrderBy(d => d, StringComparer.OrdinalIgnoreCase)) + { + string perChar = Path.Combine(dir, DbFileName); + if (File.Exists(perChar)) list.Add(perChar); + } + return list; + } + + /// + /// Reads every database under , ranks damage types per + /// monster and writes the seed to atomically. + /// + public static Result Run(string serverFolder, string outputPath, int minHitsPerType = DefaultMinHitsPerType) + { + List dbs = FindDatabases(serverFolder); + if (dbs.Count == 0) + return new Result(false, $"No {DbFileName} found in {serverFolder}.", null); + + // Best row per wcid / per normalized Mag-Tools name, across all sources. + var bestWcid = new Dictionary(); + var bestMag = new Dictionary(StringComparer.OrdinalIgnoreCase); + var used = new List(); + var errors = new List(); + + foreach (string db in dbs) + { + try + { + ReadDatabase(db, bestWcid, bestMag); + used.Add(db); + } + catch (Exception ex) + { + errors.Add($"{Path.GetFileName(Path.GetDirectoryName(db))}: {ex.Message}"); + } + } + if (used.Count == 0) + return new Result(false, "Could not read any UB database: " + string.Join("; ", errors), null); + + var seed = new UbMobSeedFile + { + GeneratedUtc = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), + MinHitsPerType = minHitsPerType, + Sources = used, + World = MostCommonWorld(bestWcid.Values), + }; + + // Live UB rows keyed by wcid. + var wcidNames = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var (wcid, doc) in bestWcid.OrderBy(kv => kv.Key)) + { + string name = Str(doc, "LastSeenName"); + if (name.Length > 0) wcidNames.Add(name); + + var elements = RankElements(doc, minHitsPerType, hasPeaks: true); + if (elements.Count < 2) continue; // one type alone says nothing about weakness + + seed.Entries.Add(new UbMobSeedEntry + { + Wcid = wcid, + Name = name, + Source = "ub", + TotalHits = Num(doc, "TotalHits"), + Elements = elements, + }); + } + + // Mag-Tools name-only rows, skipped when a wcid row already covers the name. + foreach (var doc in bestMag.Values) + { + string name = Str(doc, "LastSeenDisplayName"); + if (name.Length == 0) name = Str(doc, "NormalizedMobName"); + if (name.Length == 0 || wcidNames.Contains(name)) continue; + + var elements = RankElements(doc, minHitsPerType, hasPeaks: false); + if (elements.Count < 2) continue; + + seed.Entries.Add(new UbMobSeedEntry + { + Wcid = 0, + Name = name, + Source = "magtools", + TotalHits = elements.Sum(e => (long)e.Hits), + Elements = elements, + }); + } + + WriteAtomic(outputPath, StjSerializer.Serialize(seed, EditorJsonContext.Default.UbMobSeedFile)); + + int ub = seed.Entries.Count(e => e.Source == "ub"); + int mag = seed.Entries.Count - ub; + string msg = $"UB seed written: {ub} monster(s) by wcid + {mag} by name (Mag-Tools) from {used.Count} database(s) → {outputPath}"; + if (errors.Count > 0) msg += $" Skipped: {string.Join("; ", errors)}"; + return new Result(true, msg, seed); + } + + /// + /// Opens a snapshot copy of (UB may have the live file open) + /// and folds its rows into the best-row maps. + /// + private static void ReadDatabase(string dbPath, Dictionary bestWcid, + Dictionary bestMag) + { + string tempDir = Path.Combine(Path.GetTempPath(), "RynthUbSeed-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string copy = Path.Combine(tempDir, DbFileName); + CopyShared(dbPath, copy); + // LiteDB 5 keeps uncommitted pages in "-log.ldb"; copy it so recent hits are included. + string log = Path.Combine(Path.GetDirectoryName(dbPath)!, Path.GetFileNameWithoutExtension(dbPath) + "-log.ldb"); + if (File.Exists(log)) + CopyShared(log, Path.Combine(tempDir, Path.GetFileNameWithoutExtension(DbFileName) + "-log.ldb")); + + // Writable connection on the private copy so LiteDB can replay the log; the original is untouched. + using var db = new LiteDatabase(new ConnectionString { Filename = copy, Connection = ConnectionType.Direct }); + + if (db.CollectionExists(WcidCollection)) + { + foreach (var doc in db.GetCollection(WcidCollection).FindAll()) + { + long wcid = Num(doc, "Wcid"); + // wcid 1 is the player weenie (self/PvP lines), not a monster. + if (wcid <= 1 || wcid > uint.MaxValue) continue; + KeepBest(bestWcid, (uint)wcid, doc, Num(doc, "TotalHits")); + } + } + + if (db.CollectionExists(MagCollection)) + { + foreach (var doc in db.GetCollection(MagCollection).FindAll()) + { + string key = Str(doc, "NormalizedMobName"); + if (key.Length == 0) continue; + KeepBest(bestMag, key, doc, SumValues(doc, "HitsByType")); + } + } + } + finally + { + try { Directory.Delete(tempDir, recursive: true); } catch { /* temp cleanup is best-effort */ } + } + } + + /// Keeps the row with the most hits per key (sources overlap; see class remarks). + private static void KeepBest(Dictionary map, TKey key, BsonDocument doc, long hits) + where TKey : notnull + { + if (!map.TryGetValue(key, out var existing) || hits > HitsOf(existing)) + map[key] = doc; + } + + /// Total hits of a row in either collection's shape. + private static long HitsOf(BsonDocument doc) + { + long total = Num(doc, "TotalHits"); + return total > 0 ? total : SumValues(doc, "HitsByType"); + } + + /// + /// Ranks the castable damage types with at least hits. + /// Score blends average damage (vs the best average) with UB's own effectiveness + /// measure, peak hit vs the best peak, when peaks are recorded. + /// + private static List RankElements(BsonDocument doc, int minHits, bool hasPeaks) + { + var hits = Doc(doc, "HitsByType"); + var sums = Doc(doc, "SumDamageByType"); + var peaks = hasPeaks ? Doc(doc, "MaxDamageByType") : null; + if (hits == null || sums == null) return new List(); + + var list = new List(); + foreach (string flag in hits.Keys) + { + if (!FlagToElement.TryGetValue(flag, out string? element)) continue; + int n = (int)Math.Min(int.MaxValue, Num(hits, flag)); + if (n < minHits || !sums.ContainsKey(flag)) continue; + + list.Add(new UbMobSeedElement + { + Element = element, + Hits = n, + AvgDamage = Math.Round(Num(sums, flag) / (double)n, 2), + MaxHit = peaks != null && peaks.ContainsKey(flag) ? Num(peaks, flag) : 0, + }); + } + if (list.Count == 0) return list; + + double bestAvg = list.Max(e => e.AvgDamage); + long bestPeak = list.Max(e => e.MaxHit); + foreach (var e in list) + { + double avgRatio = bestAvg > 0 ? e.AvgDamage / bestAvg : 0; + double score = bestPeak > 0 + ? 0.5 * avgRatio + 0.5 * (e.MaxHit / (double)bestPeak) + : avgRatio; + e.Score = Math.Round(score, 4); + } + + return list.OrderByDescending(e => e.Score).ThenByDescending(e => e.Hits).ToList(); + } + + /// Most frequent WorldName among the rows (empty when none recorded). + private static string MostCommonWorld(IEnumerable rows) => + rows.Select(r => Str(r, "WorldName")) + .Where(w => w.Length > 0) + .GroupBy(w => w, StringComparer.OrdinalIgnoreCase) + .OrderByDescending(g => g.Count()) + .Select(g => g.Key) + .FirstOrDefault() ?? string.Empty; + + /// Copies a file another process may hold open for writing. + private static void CopyShared(string source, string dest) + { + using var src = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var dst = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None); + src.CopyTo(dst); + } + + /// Writes via a temp file so the plugin never reads a half-written seed. + private static void WriteAtomic(string path, string contents) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, contents); + File.Move(tmp, path, overwrite: true); + } + + // ── BSON helpers (schema-tolerant: UB may store numbers as Int32, Int64 or Double) ── + + private static BsonDocument? Doc(BsonDocument doc, string field) => + doc.TryGetValue(field, out var v) && v.IsDocument ? v.AsDocument : null; + + private static string Str(BsonDocument doc, string field) => + doc.TryGetValue(field, out var v) && v.IsString ? v.AsString.Trim() : string.Empty; + + private static long Num(BsonDocument doc, string field) => + doc.TryGetValue(field, out var v) && v.IsNumber ? Convert.ToInt64(v.RawValue, CultureInfo.InvariantCulture) : 0; + + private static long SumValues(BsonDocument doc, string field) + { + var d = Doc(doc, field); + if (d == null) return 0; + long total = 0; + foreach (string k in d.Keys) total += Num(d, k); + return total; + } +} diff --git a/Tools/RynthCore.MonsterEditor/VirindiTankUsdImport.cs b/Tools/RynthCore.MonsterEditor/VirindiTankUsdImport.cs new file mode 100644 index 0000000..baf921c --- /dev/null +++ b/Tools/RynthCore.MonsterEditor/VirindiTankUsdImport.cs @@ -0,0 +1,548 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.Data.Sqlite; + +namespace RynthCore.MonsterEditor; + +/// +/// Best-effort import of VirindiTank "user" macro profiles (typically .usd) into RynthAi +/// rows. Tries, in order: (1) line-oriented SCF MyMonsters (classic +/// uTank2 *.usd in VirindiPlugins\VirindiTank); (2) SQLite; (3) binary scan for +/// vTank-style match expressions. +/// +public static class VirindiTankUsdImport +{ + public sealed class Result + { + public bool Ok { get; set; } + public List Rules { get; } = new(); + /// Human-readable summary: counts, method used, warnings. + public string Message { get; set; } = string.Empty; + } + + public static Result TryImport(string filePath) + { + var r = new Result(); + if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) + { + r.Message = "File not found."; + return r; + } + + string? allText; + try + { + // VT text profiles are UTF-8; invalid sequences become replacement chars, still OK for SCF. + allText = File.ReadAllText(filePath, Encoding.UTF8); + } + catch (Exception ex) + { + r.Message = $"Read failed: {ex.Message}"; + return r; + } + + // Primary path: SCF MyMonsters block (see VirindiPlugins\VirindiTank\*.usd, format 8+). + if (VirindiTankUsdTextScfParser.TryParseMyMonsters(allText, r.Rules, out string? scfNote) && r.Rules.Count > 0) + { + r.Ok = true; + r.Message = BuildMessage("MyMonsters (VT SCF / line format)", r.Rules.Count, scfNote); + return r; + } + r.Rules.Clear(); + + byte[] bytes; + try + { + bytes = File.ReadAllBytes(filePath); + } + catch (Exception ex2) + { + r.Message = $"Read as bytes failed: {ex2.Message}"; + return r; + } + + if (IsSqliteDatabase(bytes)) + { + try + { + if (TryImportFromSqlite(filePath, r.Rules, out int count, out string? sqlNote)) + { + r.Ok = true; + r.Message = BuildMessage("SQLite (Virindi uTank settings database)", count, sqlNote); + return r; + } + } + catch (Exception ex) + { + const string pfx = "SQLite read error: "; + string errMsg = pfx + ex.Message; + if (TryImportFromStringScan(bytes, r.Rules, out int exprCount, out string? scanNote)) + { + r.Ok = exprCount > 0; + r.Message = BuildMessage("Text scan (after SQLite exception)", exprCount, errMsg + " " + scanNote); + } + else + r.Message = errMsg; + return r; + } + } + + string? fallNote; + if (TryImportFromStringScan(bytes, r.Rules, out int n, out fallNote)) + { + r.Ok = n > 0; + r.Message = n > 0 + ? BuildMessage("Expression scan (non-SQLite or unreadable table)", n, fallNote) + : "Could not import: no vTank-style match expressions in file. " + (fallNote ?? string.Empty) + + " If this is a Virindi Tank user profile, ensure the file is a .usd from your VirindiPlugins\\VirindiTank folder (SQLite based)."; + } + else + { + r.Message = fallNote ?? "Import failed."; + } + + return r; + } + + private static string BuildMessage(string method, int count, string? extra) + { + var sb = new StringBuilder(); + sb.Append(CultureInfo.InvariantCulture, $"Imported {count} rule(s) using {method}."); + if (!string.IsNullOrWhiteSpace(extra)) + { + sb.Append(' '); + sb.Append(extra); + } + return sb.ToString(); + } + + private static bool IsSqliteDatabase(byte[] header) + { + const string sig = "SQLite format 3\0"; + if (header.Length < sig.Length) return false; + for (int i = 0; i < sig.Length; i++) + { + if (header[i] != sig[i]) return false; + } + return true; + } + + private static bool TryImportFromSqlite(string filePath, List outList, out int count, out string? note) + { + count = 0; + note = null; + outList.Clear(); + + var csb = new SqliteConnectionStringBuilder + { + DataSource = filePath, + Mode = SqliteOpenMode.ReadOnly, + }; + + using var con = new SqliteConnection(csb.ToString()); + con.Open(); + + // Discover tables and their columns; pick the best "monster list" table. + var tableScores = new List<(string name, int score)>(); + using (var listCmd = con.CreateCommand()) + { + listCmd.CommandText = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"; + using var r = listCmd.ExecuteReader(); + while (r.Read()) + { + string t = r.GetString(0); + if (!IsSafeTableName(t)) continue; + int s = ScoreTableIntent(con, t); + if (s > 0) tableScores.Add((t, s)); + } + } + + if (tableScores.Count == 0) + { + // Unknown schema — try every user table; ReadMonsterTable skips unsuitable ones. + using (var listCmd2 = con.CreateCommand()) + { + listCmd2.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"; + using var r2 = listCmd2.ExecuteReader(); + while (r2.Read()) + { + string t = r2.GetString(0); + if (IsSafeTableName(t)) tableScores.Add((t, 1)); + } + } + } + + if (tableScores.Count == 0) + { + note = "No user tables in SQLite file."; + return false; + } + + tableScores.Sort((a, b) => b.score.CompareTo(a.score)); + var best = tableScores[0].name; + if (!ReadMonsterTable(con, best, outList, out int readCount, out string? readErr)) + { + note = readErr; + return false; + } + + count = readCount; + note = $"Table \"{best}\" (score {tableScores[0].score}). {readErr ?? string.Empty}".Trim(); + return count > 0; + } + + private static bool IsSafeTableName(string t) + { + foreach (char c in t) + { + if (char.IsLetterOrDigit(c) || c is '_' or '-') continue; + return false; + } + return t.Length is > 0 and < 200; + } + + private static int ScoreTableIntent(SqliteConnection con, string table) + { + int s = 0; + if (table.IndexOf("monster", StringComparison.OrdinalIgnoreCase) >= 0) s += 15; + if (table.IndexOf("mob", StringComparison.OrdinalIgnoreCase) >= 0) s += 8; + if (table.IndexOf("attack", StringComparison.OrdinalIgnoreCase) >= 0) s += 4; + + using var c = con.CreateCommand(); + c.CommandText = $"PRAGMA table_info(\"{table}\")"; + using var r = c.ExecuteReader(); + while (r.Read()) + { + string col = r.GetString(1); + s += ColumnScore(col); + } + return s; + } + + private static int ColumnScore(string col) + { + string c = col.ToLowerInvariant(); + if (c.Contains("fester", StringComparison.Ordinal) || c is "f") return 4; + if (c.Contains("broad", StringComparison.Ordinal) || c is "b" or "broadside") return 4; + if (c.Contains("gravity", StringComparison.Ordinal) || c is "g") return 2; + if (c.Contains("imperil", StringComparison.Ordinal) || c is "i") return 2; + if (c.Contains("yield", StringComparison.Ordinal) || c is "y") return 2; + if (c.Contains("vuln", StringComparison.Ordinal) && c.Contains("ex", StringComparison.Ordinal) == false) return 2; + if (c is "v") return 2; + if (c.Contains("expression", StringComparison.Ordinal) || c is "matchexpr" or "matchexpression" or "match" or "expr" or "e") + return 8; + if (c is "name" or "mname" or "monstername" or "n") + return 6; + if (c.Contains("damag", StringComparison.Ordinal) || c.Contains("element", StringComparison.Ordinal) || c is "dmg" or "dt") + return 4; + if (c.Contains("priority", StringComparison.Ordinal) || c is "p" or "pri" or "sort" or "idx" or "ordinal") + return 2; + if (c.Contains("weapon", StringComparison.Ordinal) || c.Contains("wand", StringComparison.Ordinal)) return 2; + if (c is "a" or "r" or "s" or "w" or "u") return 1; // A/R/S are ambiguous; low weight + return 0; + } + + private static bool ReadMonsterTable(SqliteConnection con, string table, List outList, out int count, out string? err) + { + count = 0; + err = null; + // Prefer stable ordering when a dedicated column exists (ROWID is the SQLite insert order for many VT exports). + string orderBy = "ROWID"; + if (TableHasColumn(con, table, "Order")) orderBy = "CAST([Order] AS INTEGER)"; + else if (TableHasColumn(con, table, "SortIndex")) orderBy = "SortIndex"; + else if (TableHasColumn(con, table, "Index")) orderBy = "[Index]"; + + using var cmd = con.CreateCommand(); + cmd.CommandText = $"SELECT * FROM \"{table}\" ORDER BY {orderBy} ASC"; + using var r = cmd.ExecuteReader(); + + int ordName = FindOrdinalByHints(r, "name", "monstername", "mname", "entry", "n", "text0"); + int ordExpr = FindOrdinalByHints(r, "matchexpression", "match", "expression", "expr", "e", "ed"); + if (ordExpr < 0) ordExpr = FindExpressionColumn(r); + int ordDmg = FindOrdinalByHints(r, "damagetype", "element", "dmg", "de", "delement"); + int ordPri = FindOrdinalByHints(r, "priority", "p", "pri", "importance", "ipriority"); + int ordEx = FindOrdinalByHints(r, "exvuln", "exvul", "extravuln", "vulnextra"); + int ordWep = FindOrdinalByHints(r, "weaponid", "weapon", "windex", "weaponindex"); + int ordOff = FindOrdinalByHints(r, "offhand", "offhandid", "shield"); + int ordF = FindOrdinalByHints(r, "fester", "f", "b_fester", "bisfester", "festerb"); + int ordB = FindOrdinalByHints(r, "broadside", "b", "broad", "broadb"); + int ordG = FindOrdinalByHints(r, "gravity", "g", "grav"); + int ordI = FindOrdinalByHints(r, "imperil", "i", "imprl"); + int ordY = FindOrdinalByHints(r, "yield", "y", "yld"); + int ordV = FindOrdinalByHints(r, "vulnerability", "v", "vuln", "b_vuln", "bisfestervuln", "bisfesterv"); // be careful: skip ex vuln + // VT often: UseArc, UseRing, Streak, Bolt + int ordA = FindOrdinalByHints(r, "usearc", "arc", "a"); + int ordR = FindOrdinalByHints(r, "usering", "ring", "r", "b_ring"); + int ordS = FindOrdinalByHints(r, "streak", "s", "usestreak", "b_streak", "bisfeststreak", "bisfstreak", "bisfstreak2"); + int ordBl= FindOrdinalByHints(r, "usebolt", "bolt", "bl", "b_bolt", "bisfstreakbolt", "bisfstreakbol", "bisfb"); + + if (ordName < 0 && ordExpr < 0) + { + err = "Table has no recognizable name/expression column."; + return false; + } + + while (r.Read()) + { + var m = new MonsterRule(); + string? name = GetStr(r, ordName); + string? expr = GetStr(r, ordExpr); + if (!string.IsNullOrWhiteSpace(name) && name.Trim().Equals("default", StringComparison.OrdinalIgnoreCase)) + { + m.Name = "Default"; + m.MatchExpression = string.Empty; + } + else + { + m.Name = name?.Trim() ?? string.Empty; + m.MatchExpression = expr?.Trim() ?? string.Empty; + } + + m.Priority = 1; + if (ordPri >= 0) m.Priority = Math.Clamp(ToInt32(r, ordPri, 1), -100, 10000); + m.DamageType = string.IsNullOrEmpty(GetStr(r, ordDmg)) ? "Auto" : MapDamageType(GetStr(r, ordDmg) ?? "Auto"); + m.ExVuln = string.IsNullOrEmpty(GetStr(r, ordEx)) ? "None" : (GetStr(r, ordEx) ?? "None"); + m.WeaponId = ordWep >= 0 ? Math.Max(0, ToInt32(r, ordWep, 0)) : 0; + m.OffhandId = ordOff >= 0 ? Math.Max(0, ToInt32(r, ordOff, 0)) : 0; + m.Fester = GetBoolish(r, ordF); + m.Broadside = GetBoolish(r, ordB); + m.GravityWell= GetBoolish(r, ordG); + m.Imperil = GetBoolish(r, ordI); + m.Yield = GetBoolish(r, ordY); + m.Vuln = GetBoolish(r, ordV); + m.UseArc = GetBoolish(r, ordA); + m.UseRing = GetBoolish(r, ordR); + m.UseStreak = GetBoolish(r, ordS); + m.UseBolt = ordBl >= 0 ? GetBoolish(r, ordBl) : m.UseBolt; + + // If row is empty, skip + if (string.IsNullOrEmpty(m.Name) && string.IsNullOrEmpty(m.MatchExpression)) + { + bool anyToggle = m.Fester || m.Broadside || m.GravityWell || m.Imperil || m.Yield || m.Vuln + || m.UseArc || m.UseRing || m.UseStreak; + if (!anyToggle) continue; + } + + if (m.Name.Length == 0 && m.MatchExpression.Length == 0) + continue; + + outList.Add(m); + } + + count = outList.Count; + if (count == 0) err = "No mappable rows."; + return true; + } + + private static bool TableHasColumn(SqliteConnection con, string table, string col) + { + using var c = con.CreateCommand(); + c.CommandText = $"PRAGMA table_info(\"{table}\")"; + using var r = c.ExecuteReader(); + while (r.Read()) + { + if (r.GetString(1).Equals(col, StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + + /// Column whose name is exactly (lowercase) or a short exact code (P, V, etc.). + private static int FindOrdinalByHints(SqliteDataReader r, params string[] hints) + { + for (int i = 0; i < r.FieldCount; i++) + { + string n = r.GetName(i); + string nl = n.ToLowerInvariant(); + foreach (string h in hints) + { + if (h.Equals("p", StringComparison.Ordinal) && nl is "p" or "ipriority") + return i; + if (h.Equals("v", StringComparison.Ordinal) && (nl is "v" or "b_v" or "b_vuln" or "vuln") + && !nl.Contains("exvul", StringComparison.Ordinal) && !nl.Contains("ex_vul", StringComparison.Ordinal)) + return i; + if (nl == h.ToLowerInvariant()) return i; + } + } + return -1; + } + + private static int FindExpressionColumn(SqliteDataReader r) + { + for (int i = 0; i < r.FieldCount; i++) + { + string nl = r.GetName(i).ToLowerInvariant(); + if (nl.Contains("matchexpr", StringComparison.Ordinal) + || (nl.Contains("match", StringComparison.Ordinal) && nl.Contains("exp", StringComparison.Ordinal))) + return i; + } + return -1; + } + + private static string? GetStr(SqliteDataReader r, int ord) => ord < 0 || r.IsDBNull(ord) ? null : r.GetValue(ord)?.ToString(); + + private static int ToInt32(SqliteDataReader r, int ord, int dft) + { + try + { + if (r.IsDBNull(ord)) return dft; + return Convert.ToInt32(r.GetValue(ord), CultureInfo.InvariantCulture); + } + catch + { + if (int.TryParse(r.GetValue(ord)?.ToString(), out int p)) return p; + return dft; + } + } + + private static bool GetBoolish(SqliteDataReader r, int ord) + { + if (ord < 0 || r.IsDBNull(ord)) return false; + var v = r.GetValue(ord); + if (v is long l) return l != 0; + if (v is int i) return i != 0; + if (v is bool b) return b; + string? s = v?.ToString()?.Trim(); + if (string.IsNullOrEmpty(s)) return false; + if (s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + private static string MapDamageType(string raw) + { + string t = raw.Trim(); + if (t.Length == 0) return "Auto"; + if (t.Contains('<', StringComparison.Ordinal) && t.Contains('>', StringComparison.Ordinal)) // + { + if (t.Contains("auto", StringComparison.OrdinalIgnoreCase)) return "Auto"; + } + // VT uses words like "Slash" — normalize first letter + if (t.Equals("Auto", StringComparison.OrdinalIgnoreCase)) return "Auto"; + foreach (string s in new[] { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }) + { + if (s.Equals(t, StringComparison.OrdinalIgnoreCase)) return s; + } + // Unknown — keep for display, Rynth will treat oddly if not in list; still better than Data loss + return t; + } + + // ── Binary / UTF-16 / UTF-8 string scan: expression fallbacks ──────────── + + private static bool TryImportFromStringScan(byte[] data, List outList, out int count, out string? note) + { + count = 0; + note = null; + outList.Clear(); + var strs = new HashSet(StringComparer.Ordinal); + + foreach (string s in ExtractAllStrings(data, minLen: 8, maxLen: 480)) + { + if (LooksLikeVtExpression(s)) + strs.Add(s.Trim()); + } + + if (strs.Count == 0) + { + count = 0; + return false; + } + + // Prefer longer expressions (often more specific) + foreach (string s in strs.OrderByDescending(x => x.Length)) + { + outList.Add(new MonsterRule + { + Name = string.Empty, + MatchExpression = s, + DamageType = "Auto", + UseBolt = true, + }); + } + + count = outList.Count; + note = "Binary mode only recovers vTank **match expression** rows (name-only entries must be added by hand, or re-export from a SQLite .usd)."; + return true; + } + + /// Pull printable ASCII/UTF-8 (single-byte) and UTF-16-LE "wide string" runs from a blob. + private static IEnumerable ExtractAllStrings(byte[] data, int minLen, int maxLen) + { + // 7-bit runs (covers most human-readable .usd contents outside SQLite BLOBs) + int start = -1; + for (int i = 0; i < data.Length; i++) + { + byte b = data[i]; + if ((b >= 0x20 && b <= 0x7E) || b == 0x09) // printables + tab + { + if (start < 0) start = i; + } + else + { + if (start >= 0) + { + int len = i - start; + if (len >= minLen) + yield return Encoding.UTF8.GetString(data, start, len > maxLen ? maxLen : len); + } + start = -1; + } + } + if (start >= 0) + { + int len2 = data.Length - start; + if (len2 >= minLen) + yield return Encoding.UTF8.GetString(data, start, len2 > maxLen ? maxLen : len2); + } + + // UTF-16-LE ASCII: [char][0][char][0] (common in Windows/.NET-originated data) + for (int i = 0; i < data.Length - 1;) + { + if (data[i + 1] != 0) { i++; continue; } + if (data[i] < 0x20) { i++; continue; } + { + char ch = (char)data[i]; + if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch is not ( '<' or '=' or '(' or '!' or 'f' or 't')) { i++; continue; } + } + int p = i; + var sb = new StringBuilder(); + while (p + 1 < data.Length) + { + if (data[p + 1] != 0) break; + int c = data[p]; + if (c < 0x20) break; + if (c > 0x7E) break; + sb.Append((char)c); + p += 2; + if (sb.Length >= maxLen) break; + } + if (sb.Length >= minLen) yield return sb.ToString(); + if (p > i) { i = p; } + else { i++; } + } + } + + private static bool LooksLikeVtExpression(string s) + { + s = s.Trim(); + if (s.Length < 6) return false; + if (s.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return false; + if (s.Contains("SQLite format", StringComparison.Ordinal)) return false; + if (s.Contains("&&", StringComparison.Ordinal) || s.Contains("||", StringComparison.Ordinal)) return true; + if (s.Contains("==", StringComparison.Ordinal) && ( + s.Contains("range", StringComparison.Ordinal) + || s.Contains("species", StringComparison.Ordinal) + || s.Contains("typeid", StringComparison.Ordinal) + || s.Contains("name", StringComparison.Ordinal) + || s.Contains("maxhp", StringComparison.Ordinal) + || s.Contains("hasshield", StringComparison.Ordinal) + || s.Contains("metastate", StringComparison.Ordinal))) + return true; + // e.g. range>5 && !foo + if (Regex.IsMatch(s, @"(?i)range\s*[<>=!]+")) return true; + return false; + } +} diff --git a/Tools/RynthCore.MonsterEditor/VirindiTankUsdTextScfParser.cs b/Tools/RynthCore.MonsterEditor/VirindiTankUsdTextScfParser.cs new file mode 100644 index 0000000..5cee546 --- /dev/null +++ b/Tools/RynthCore.MonsterEditor/VirindiTankUsdTextScfParser.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace RynthCore.MonsterEditor; + +// In-game VirindiTank import uses the same MyMonsters layout in Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs — keep in sync. +/// +/// Line-oriented uTank2 SCF .usd (e.g. format 8) — the common format under +/// C:\Games\VirindiPlugins\VirindiTank\*.usd, with a MyMonsters table using s/i/b value lines. +/// Reference: --Silentkelpie_InfiniteLeaftide.usd (MyMonsters 21 columns, 110+ rows in sample file). +/// +public static class VirindiTankUsdTextScfParser +{ + public static bool TryParseMyMonsters(string allText, List outList, out string? note) + { + outList.Clear(); + note = null; + if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0) + return false; + + string[] L = allText + .Split(new[] { "\r\n", "\n" }, StringSplitOptions.None) + .Select(s => s.Trim()) + .ToArray(); + if (L.Length < 8) { note = "File too short."; return false; } + + int idx = 0; + for (; idx < L.Length; idx++) if (L[idx] == "MyMonsters") break; + if (idx >= L.Length) { note = "MyMonsters not found."; return false; } + idx++; + if (!int.TryParse(L[idx], out int colCount) || colCount < 1) { note = "MyMonsters: bad column count."; return false; } + idx += 1 + colCount * 2; // names + y/n + if (idx >= L.Length) { note = "MyMonsters: truncated after header."; return false; } + if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0) { note = "MyMonsters: bad row count."; return false; } + idx++; + // Empty table: treat as "no data" so the importer can fall back to SQLite / byte scan. + if (rowCount == 0) { note = "MyMonsters has no rows."; return false; } + if (colCount < 4 + 3) { note = "MyMonsters: column count too small."; return false; } + int nBool = colCount - 4 - 3; + + for (int r = 0; r < rowCount; r++) + { + if (idx + 1 >= L.Length) { note = $"No data for row {r + 1} (early EOF)."; return outList.Count > 0; } + if (!T(L, "s", ref idx)) { note = RowErr(r, "s"); return outList.Count > 0; } + if (!ValStr(L, ref idx, out string raw)) { note = RowErr(r, "name"); return outList.Count > 0; } + if (!T(L, "i", ref idx)) { note = RowErr(r, "i ap"); return outList.Count > 0; } + if (!ValInt(L, ref idx, out int ap, out int err) || err != 0) { note = RowErr(r, "ap int"); return outList.Count > 0; } + if (!T(L, "i", ref idx)) { note = RowErr(r, "i dt"); return outList.Count > 0; } + if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0) { note = RowErr(r, "dt int"); return outList.Count > 0; } + if (!T(L, "i", ref idx)) { note = RowErr(r, "i wep"); return outList.Count > 0; } + if (!ValInt(L, ref idx, out int wep, out err) || err != 0) { note = RowErr(r, "wep int"); return outList.Count > 0; } + if (nBool < 14) { note = "Expected at least 14 bool columns in mob row."; return outList.Count > 0; } + if (nBool < 1) { note = "nBool<1."; return false; } + var b = new bool[nBool]; + for (int k = 0; k < nBool; k++) + { + if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k])) { note = RowErr(r, $"b{k}"); return outList.Count > 0; } + } + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0) { note = RowErr(r, "sec vuln int"); return outList.Count > 0; } + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0) { note = RowErr(r, "offh int"); return outList.Count > 0; } + if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0) { note = RowErr(r, "pet int"); return outList.Count > 0; } + + outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet)); + } + + if (outList.Count == 0) { note = "No rows were parsed from MyMonsters."; return false; } + return true; + } + + private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what})."; + + private static bool T(string[] L, string t, ref int i) + { + if (i >= L.Length || L[i] != t) return false; + i++; + return true; + } + + private static bool ValStr(string[] L, ref int i, out string s) + { + s = ""; + if (i >= L.Length) return false; + s = L[i++]; return true; + } + + private static bool ValInt(string[] L, ref int i, out int v, out int err) + { + err = 0; + v = 0; + if (i >= L.Length) { err = 1; return false; } + if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) && + !int.TryParse(L[i], out v)) + { + err = 1; return false; + } + i++; + return true; + } + + private static bool ValBool(string[] L, ref int i, out bool b) + { + b = false; + if (i >= L.Length) return false; + string t = L[i++]; + if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase)) { b = true; return true; } + if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase)) { b = false; return true; } + return false; + } + + /// b[0] Imperil, [1] Vuln, [2] Yield, [3] GravityW, [4] Attack, [5] Ring, [6] Broad, [7] Fester, [8..12] WC/FC/Cp/DC/Cs, [13] Streak. + private static MonsterRule MakeRule( + string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet) + { + string n = Nm(raw); + if (b.Length < 14) b = Pad(b, 14); + bool i = b[0], v = b[1], y = b[2], gW = b[3]; + bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7]; + bool strk = b[13]; + + return new MonsterRule + { + Name = n, + Priority = ap, + DamageType = MapDmg(vtDmg), + WeaponId = WepId(wep), + Imperil = i, + Vuln = v, + Yield = y, + GravityWell = gW, + UseBolt = useBolt, + UseRing = useRing, + Broadside = broad, + Fester = fest, + UseStreak = strk, + // VT extra curses (b[8]..b[12]) — no Rynth match + ExVuln = "None", // sev = spell/element code; Rynth list is by name; leave None; user can tune + OffhandId = WepId(ofh), + PetDamage = MapPet(pet, sev), + }; + } + + private static bool[] Pad(bool[] b, int min) + { + if (b.Length >= min) return b; + var r = new bool[min]; + for (int i = 0; i < b.Length; i++) r[i] = b[i]; + return r; + } + + private static string Nm(string s) + { + s = s.Trim(); + if (s.Length > 1 && s[0] == '<' && s[^1] == '>') + { + string t = s.Substring(1, s.Length - 2); + if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return "Default"; + return t; + } + return s; + } + + private static int WepId(int w) => w; // Rynth keeps AC-style ids (often large negatives); editor shows <ID:…> if not in list + + /// uTank2 damage int — 8 and negatives typically mean "Auto" in exports. + private static string MapDmg(int c) => c switch + { + 8 => "Auto", + 1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Acid", 5 => "Fire", 6 => "Cold", 7 => "Lightning", 0 => "Nether", + _ => "Auto", + }; + + private static string MapPet(int pdt, int _ /* secondary vuln int from VT; ExVuln string not derived */) + { + if (pdt is 0 or 101) return "PAuto"; + if (pdt is >= 1 and <= 8) + { + // Narrowed 1..8: pet damage type codes in VT SCF. + return pdt switch + { + 1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Fire", 5 => "Cold", 6 => "Lightning", 7 => "Acid", 8 => "Nether", + _ => "PAuto", + }; + } + return "PAuto"; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs index 98678a7..425202f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootSalvageTests.cs @@ -28,6 +28,8 @@ internal static class LootSalvageTests private const uint ItemBase = 0x80000B00; private const uint UstWcid = 20646; private const uint ItemTypeJewelry = 0x8, ItemTypeGem = 0x800, ItemTypeContainer = 0x200, ItemTypeArmor = 0x2; + private static readonly string TestLogDirectory = + System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthAiHostTests", "Diagnostics"); public static void Register(Runner r) { @@ -143,6 +145,10 @@ internal static class LootSalvageTests } beforeCreate?.Invoke(); Host = FakeHost.Create(Player); + // SalvageManager logs through RynthLog (LogCat.Salvage), which forwards to the host it + // is bound to; bind it to this fake so FakeHost.Logs sees the [Salvage] lines. A temp + // folder keeps the test's diagnostics.json and log files out of the real install. + RynthLog.Init(Host, TestLogDirectory); Cache = FakeHost.MakeCache(Host, Player, ids); Settings.EnableCombineSalvage = false; // bag merging has its own tests in game Settings.SalvageOpenDelayFirstMs = 400; Settings.SalvageOpenDelayFastMs = 50; diff --git a/Tools/RynthCore.RynthAiTests/Tests/CreatureWeaknessTests.cs b/Tools/RynthCore.RynthAiTests/Tests/CreatureWeaknessTests.cs index c529267..8eff481 100644 --- a/Tools/RynthCore.RynthAiTests/Tests/CreatureWeaknessTests.cs +++ b/Tools/RynthCore.RynthAiTests/Tests/CreatureWeaknessTests.cs @@ -25,6 +25,7 @@ internal static class CreatureWeaknessTests r.Add("weakness: server table ranks most damage first", ServerTable); r.Add("weakness: type keyword is a whole word", TypeKeyword); r.Add("weakness: learned element goes first, then the type order", LearnedFirst); + r.Add("weakness: UB seed ranks after server data and learned, before the type", SeedBeforeType); } private static void Normalize() @@ -130,4 +131,34 @@ internal static class CreatureWeaknessTests Check.Eq(alone?.Order.Count, 1, "only the learned element"); Check.Eq(alone?.Describe(), "Fire", "describe without a multiplier"); } + + private static void SeedBeforeType() + { + var type = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null); + var r = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null, new[] { "Electric", "fire", "Holy", "Fire" }); + Check.NotNull(r, "ranking with a seed"); + if (r == null || type == null) return; + Check.Eq(r.Source, "UB seed, then Olthoi type", "source"); + Check.Eq(r.Order[0].Element, "Lightning", "seed order first (normalised)"); + Check.Eq(r.Order[1].Element, "Fire", "second seed element"); + Check.True(double.IsNaN(r.Order[1].Mult), "seed elements have no multiplier"); + Check.Eq(r.Order.Count, 8, "unknown names dropped, no element listed twice"); + var rest = new List(); + foreach (var (e, _) in type.Order) if (e != "Lightning" && e != "Fire") rest.Add(e); + for (int i = 0; i < rest.Count; i++) + Check.Eq(r.Order[i + 2].Element, rest[i], $"then the type order at {i + 2}"); + + var learned = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, "Cold", new[] { "Fire" }); + Check.Eq(learned?.Source, "learned, then Olthoi type", "learned element beats the seed"); + Check.Eq(learned?.Order[0].Element, "Cold", "learned element first"); + + var row = FirstServerRow(); + if (row is { } sr) + Check.Eq(CreatureWeakness.Rank(sr.Wcid, sr.Name, 0, null, new[] { "Nether" })?.Source, "server data", "server table beats the seed"); + + var alone = CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Acid" }); + Check.Eq(alone?.Source, "UB seed", "seed with no type"); + Check.Eq(alone?.Order.Count, 1, "only the seed element"); + Check.True(CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Holy" }) == null, "a seed with no element is ignored"); + } }