// RynthAiPlugin.MonsterStats.cs — combat per kind of monster since login (MonsterStats/), shown // under each monster in the Damage panel's Monsters tab, and /ra mstats (2026-10-30, a player's // request: "combat statistics under individual monsters, evades/resists for both the player and // the monster"). // // Where it shows: the Damage panel (the dashboard's Monsters key) draws RynthAi's rows // (BuildMonsterDamageJson); each monster row carries its numbers as "mstats", and an engine that // draws them (RynthCore feature/monster-stats-tab: UI/Data/DamageRowStats.cs, GetUiHookFlags bit 8) // puts a line under the monster. On an older engine (the owner's PC, plugin API 90) the field is // ignored, so RynthAi's own Monster Stats window (a plugin window, API v89) is the fallback, with // the Session Stats view's "Monster stats" button; on an engine with the tab neither is offered. // // Sources (MonsterStats/): melee and missile from the server's typed combat events (API v78 // server messages: 0x01B1..0x01B4, asked for in Initialize); spells from the server's spell lines // in chat (CombatLines, one table); kills from the kill notice. Not a player's chat types, never a // player's or a pet's name, and an enchantment line only for a creature (items cast the same line). // Experience per kill (2026-11-08): the kill notice and the rise of TotalExperience paired by // KillXpMatcher; the session's rows carry it ("xp", "xk"), and MonsterXpTable learns it per // character across logins for the Outdoor Hunt's Most XP choice. // Damage taken by shield and facing (same day): the row's "mstats" also carries monster_damage.txt's // TS cells (learned across logins, CombatManager.ShieldFacing.cs), sent even with nothing since login. // // Lifetime: from login to logout (per character), kept across a hot reload (MonsterStatsStore), // started over only by /ra mstats reset, the window's Reset or the Damage panel's Reset stats; not // by Reset XP (the owner's rule, 2026-10-30). Pump thread throughout, except the window (render // thread, the published view) and the Damage panel's poll (the published rows). using System; using System.Collections.Generic; using System.Globalization; using System.Numerics; using System.Text; using System.Threading; using ImGuiNET; using RynthCore.Plugin.RynthAi.MonsterStats; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi; public sealed partial class RynthAiPlugin { /// The window's title (its panel key) and surface (Huds/SectionsManifest.cs). internal const string MonsterStatsTitle = "Monster Stats", MonsterStatsSurface = "window:monsterstats"; /// The engine's Damage panel key (the dashboard's Monsters key opens it). internal const string DamagePanelKey = "Monsters"; internal const string MonsterStatsUsage = "Usage: /ra mstats [monster] | list | reset | show | hide"; /// /// GetUiHookFlags bit 8 (SDK RynthUiHookFlags.DamageRowStats on RynthCore feature/monster-stats-tab): /// the engine's Damage panel draws a row's "mstats". Spelled here so RynthAi builds against an /// SDK without the name. /// internal const uint DamageRowStatsFlag = 1u << 8; private static readonly TimeSpan MonsterStatsSaveInterval = TimeSpan.FromSeconds(30); private readonly MonsterCombatStats _monsterStats = new(); private volatile MonsterStatsView _monsterStatsView = MonsterStatsView.Empty; // tick writes, render reads private int _monsterStatsViewVersion = -1; private string _monsterStatsViewFocus = string.Empty; private bool _monsterStatsViewInWorld; private long _monsterStatsViewAtMs; private long _monsterStatsDrawnMs = long.MinValue / 2; // render writes, tick reads // The rows by name for the Damage panel's poll (BuildMonsterDamageJson, its own thread): swapped whole. private volatile Dictionary _monsterStatsByName = new(StringComparer.OrdinalIgnoreCase); private int _monsterStatsByNameVersion = -1; /// The counting has begun for this login (the save looked for); false before login and after logout. private bool _monsterStatsStarted; /// When the numbers started (login, or the last reset), UTC. private DateTime _monsterStatsSinceUtc; /// The Damage panel's Reset stats asked (its thread); done on the tick. private volatile bool _monsterStatsResetWanted; private int _monsterStatsSavedVersion = -1; private DateTime _monsterStatsSaveAtUtc; private bool _monsterStatsSaveFailedLogged; /// The engine streams the combat game events (Initialize); false = melee and missile go uncounted. private bool _combatEventsStreaming = true; private MonsterStatsWindow? _monsterStatsWindow; // render thread private int _monsterStatsFailures; // render thread // Creature names around, by class (refreshed at most every 2 s): who a line's name is. private readonly Dictionary _creatureClassByName = new(StringComparer.OrdinalIgnoreCase); private long _creatureNamesAtMs = long.MinValue / 2; // Experience per kill (2026-11-08, Tom: "the monster tab should record how much experience you get // for killing x mob"): each credited kill notice and each rise of TotalExperience go to the // matcher; a pair adds to the session's row and to the learned table the Outdoor Hunt reads. private readonly KillXpMatcher _killXp = new(); private readonly MonsterXpTable _xpTable = new(); private const uint TotalExperienceQuad = 1; // PropertyInt64.TotalExperience /// The learned XP per kill of a kind of monster, kept across logins (MonsterXpTable), or null. internal double? XpPerKill(string name) => _xpTable.XpPerKill(name); /// The learned table (tests). internal MonsterXpTable XpTableForTests => _xpTable; /// Where the save goes (tests point it at a temp folder). internal string MonsterStatsDirectory { get; set; } = MonsterStatsStore.DefaultDirectory(); /// The counters (tests, and RynthAi's own readers). internal MonsterCombatStats MonsterStatsForTests => _monsterStats; /// The engine's Damage panel shows the numbers under each monster (GetUiHookFlags bit 8). Any thread. internal bool EngineDrawsMonsterStats => Host.HasUiHooks && ((uint)Host.GetUiHookFlags() & DamageRowStatsFlag) != 0; // ── Events (pump thread) ───────────────────────────────────────────── /// One of the four combat game events (PluginExports.OnServerMessage). internal void NoteCombatEvent(uint eventType, ReadOnlySpan body) { if (!_loginComplete) return; if (!CombatEvents.TryParse(eventType, body, out PhysicalEvent kind, out string name, out int damage)) return; if (!CountsAsMonster(name, mayBeItem: false)) return; _monsterStats.OnPhysical(kind, name, damage, DateTime.UtcNow); } /// A chat line: one of the spell lines (CombatLines) about a monster, unless a player wrote it. private void NoteMonsterStatsChat(string text, int chatType) { if (!_loginComplete || RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return; if (!CombatLines.TryParse(text, out CombatLine line)) return; if (!CountsAsMonster(line.Name, line.MayBeItem)) return; _monsterStats.OnSpell(line, DateTime.UtcNow); } /// The kill notice: a kill, and the killing blow by the combat mode it was struck in. /// The monster credited (null: none, or not in the world). private string? NoteMonsterStatsKill(string? notice) { if (!_loginComplete) return null; KillBlow blow = _currentCombatMode switch { CombatMode.Melee or CombatMode.Missile => KillBlow.Physical, CombatMode.Magic => KillBlow.Spell, _ => KillBlow.None, }; DateTime now = DateTime.UtcNow; string? credited = _monsterStats.OnKill(notice, blow, now, CreatureNameIn); if (credited != null) { ApplyKillXp(_killXp.OnKill(credited, now), now); _corpseTimer.OnKill(credited, CorpseNowMs); // its corpse comes after the death animation (RynthAiPlugin.DeathWait.cs) } return credited; } /// The player's TotalExperience, read every tick, for the kills' XP. private void WatchKillXp(DateTime now) { if (!_loginComplete || _playerId == 0 || !Host.HasGetObjectQuadProperty) return; if (!Host.TryGetObjectQuadProperty(_playerId, TotalExperienceQuad, out long total)) return; ApplyKillXp(_killXp.OnTotal(total, now), now); } private void ApplyKillXp(IReadOnlyList kills, DateTime now) { foreach (KillXp k in kills) { _monsterStats.OnKillXp(k.Name, k.Xp, now); _xpTable.Record(k.Name, k.Xp); } } /// The learned XP table follows the character's folder (next to monster_damage.txt); "" detaches it. private void SetXpTableCharacter(string? charFolder) { try { _xpTable.SaveIfDirty(); _xpTable.SetCharacter(charFolder); } catch (Exception ex) { Host.Log($"[RynthAi] Couldn't read the learned XP per kill: {ex.GetType().Name}: {ex.Message}"); } } /// /// A name the stats count: not a player's or a pet's (PvP, a summon), nor an NPC's; and for a line /// an item could have sent (), a creature around or a monster already /// counted. A name the client doesn't know otherwise counts (a monster out of sight). /// private bool CountsAsMonster(string name, bool mayBeItem) { AcObjectClass? cls = CreatureClassOf(name); if (cls is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) return false; if (mayBeItem && cls == null && !_monsterStats.IsTracked(name)) return false; return true; } /// The class of the creature around with that name, or null when none is known. private AcObjectClass? CreatureClassOf(string name) { RefreshCreatureNames(false); if (_creatureClassByName.TryGetValue(name, out AcObjectClass cls)) return cls; // A creature that just came: look once more before calling it unknown (at most every 250 ms). if (Environment.TickCount64 - _creatureNamesAtMs > 250) { RefreshCreatureNames(true); if (_creatureClassByName.TryGetValue(name, out cls)) return cls; } return null; } private void RefreshCreatureNames(bool force) { long now = Environment.TickCount64; if (!force && now - _creatureNamesAtMs < 2000) return; _creatureNamesAtMs = now; _creatureClassByName.Clear(); var cache = _objectCache; if (cache == null) return; foreach (WorldObject wo in cache.GetLandscape()) { if (wo == null || string.IsNullOrEmpty(wo.Name)) continue; // The cache can file a player as a monster (a creature whose kind wasn't readable yet): // a player's guid says player. A player's name wins over a monster's of the same name. AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass; if (_creatureClassByName.TryGetValue(wo.Name, out AcObjectClass had) && had == AcObjectClass.Player) continue; _creatureClassByName[wo.Name] = cls; } // Players, NPCs and pets that aren't in the creature list (everything with a place in the // world): never a monster. Items stay unknown (an enchantment line from one doesn't count). foreach (WorldObject wo in cache.GetLandscapeObjects()) { if (wo == null || string.IsNullOrEmpty(wo.Name)) continue; AcObjectClass cls = CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)wo.Id)) ? AcObjectClass.Player : wo.ObjectClass; if (cls is AcObjectClass.Player or AcObjectClass.Npc or AcObjectClass.Vendor or AcObjectClass.CombatPet) _creatureClassByName[wo.Name] = cls; } } /// The kill notice names a monster with no numbers yet (killed by its first blow): the longest creature name around in it. private string? CreatureNameIn(string notice) { RefreshCreatureNames(true); string? best = null; foreach (var kv in _creatureClassByName) { if (kv.Value is AcObjectClass.Player or AcObjectClass.CombatPet or AcObjectClass.Npc or AcObjectClass.Vendor) continue; if ((best == null || kv.Key.Length > best.Length) && notice.IndexOf(kv.Key, StringComparison.OrdinalIgnoreCase) >= 0) best = kv.Key; } return best; } // ── Tick (pump thread) ─────────────────────────────────────────────── /// Starts the login's counting (or brings the save back after a reload), resets on asking, saves, publishes. private void TickMonsterStats() { DateTime now = DateTime.UtcNow; if (!_monsterStatsStarted && _loginComplete && _playerId != 0) { // The login's first tick with the character known: after a hot reload the save is there. _monsterStatsStarted = true; if (TryRestoreMonsterStats(now)) Host.Log($"[RynthAi] Monster stats carried over from before the reload ({_monsterStats.Count} kinds of monster)."); else { _monsterStatsSinceUtc = now; CleanupMonsterStatsSaves(now); } _monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval; } WatchKillXp(now); if (_monsterStatsResetWanted) { _monsterStatsResetWanted = false; ResetMonsterStats("the Damage panel's Reset stats"); } if (_monsterStatsStarted && now >= _monsterStatsSaveAtUtc) { _monsterStatsSaveAtUtc = now + MonsterStatsSaveInterval; if (_monsterStats.Version != _monsterStatsSavedVersion) SaveMonsterStats(now); } PublishMonsterStatsRows(); PublishMonsterStatsView(Environment.TickCount64); } /// Every monster's numbers start over (/ra mstats reset, the window's Reset, the Damage panel's Reset stats). Pump thread. private int ResetMonsterStats(string by) { int n = _monsterStats.Count; _monsterStats.Reset(); DateTime now = DateTime.UtcNow; _monsterStatsSinceUtc = now; // Saved at once, so a reload right after a reset can't bring the old numbers back. if (_monsterStatsStarted) SaveMonsterStats(now); Host.Log($"[RynthAi] Monster stats started over ({by}; {n} kinds of monster cleared)."); return n; } /// The Damage panel's Reset stats (RynthPluginClearMonsterStats, its thread): the monster stats start over too. internal void RequestMonsterStatsReset() => _monsterStatsResetWanted = true; /// The rows by name for the Damage panel's poll, when something changed. private void PublishMonsterStatsRows() { if (_monsterStats.Version == _monsterStatsByNameVersion) return; _monsterStatsByNameVersion = _monsterStats.Version; var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MonsterStatsRow r in _monsterStats.Snapshot()) byName[r.Name] = r; _monsterStatsByName = byName; } /// /// A Damage-panel row's "mstats" field and its comma, for the monster named /// (UI/Data/DamageRowStats.cs in the engine reads it); "" for a monster without numbers. Any thread. /// internal string MonsterStatsJsonFor(string name) => MonsterStatsJsonFor(name, Array.Empty(), 0); /// /// with the damage it did to us by shield and facing /// (monster_damage.txt's TS rows over , the row's kinds, at difficulty /// ), learned across logins. Sent even when nothing was counted since login. /// internal string MonsterStatsJsonFor(string name, uint[] wcids, int tier) { _monsterStatsByName.TryGetValue(name, out MonsterStatsRow? r); bool session = r != null && !r.IsEmpty; ShieldTakenCells cells = ShieldTakenFor(wcids, tier); if (!session && cells.IsEmpty) return string.Empty; return MonsterStatsJson(session ? r : null, cells) + ","; } /// /// Damage taken by shield (s = in the off hand, n = none) and facing (f = front, b = behind, /// u = unknown), added up over a row's kinds: per cell its hits, total damage (the mean is /// total / hits) and biggest hit. Index = (shield ? 0 : 3) + front 0 / behind 1 / unknown 2. /// internal sealed class ShieldTakenCells { public static readonly string[] Keys = { "sf", "sb", "su", "nf", "nb", "nu" }; public readonly int[] Hits = new int[6]; public readonly double[] Total = new double[6]; public readonly double[] Max = new double[6]; public bool IsEmpty { get { foreach (int h in Hits) if (h > 0) return false; return true; } } } internal ShieldTakenCells ShieldTakenFor(uint[] wcids, int tier) { var c = new ShieldTakenCells(); var store = _damageStore; if (store == null) return c; foreach (uint w in wcids) { if (w == 0) continue; foreach (var t in store.GetShieldTaken(w, tier)) { int i = (t.Shield ? 0 : 3) + (t.Facing == CreatureData.HitFacing.Front ? 0 : t.Facing == CreatureData.HitFacing.Behind ? 1 : 2); c.Hits[i] += t.Hits; c.Total[i] += t.Avg * t.Hits; if (t.Max > c.Max[i]) c.Max[i] = t.Max; } } return c; } /// "mstats":{...} for one monster (the field names DamageRowStats reads). internal static string MonsterStatsJson(MonsterStatsRow r) => MonsterStatsJson(r, null); /// /// "mstats":{...}: the numbers since login (, null = none) and the learned /// damage taken by shield and facing (, null or empty = none): per cell /// "h" + key hits, "d" + key total damage, "m" + key biggest hit (whole numbers: the engine reads integers). /// internal static string MonsterStatsJson(MonsterStatsRow? r, ShieldTakenCells? shield) { CultureInfo ic = CultureInfo.InvariantCulture; var sb = new StringBuilder(160); sb.Append("\"mstats\":{"); bool first = true; if (shield != null && !shield.IsEmpty) { for (int i = 0; i < 6; i++) { if (shield.Hits[i] == 0) continue; string k = ShieldTakenCells.Keys[i]; if (!first) sb.Append(','); first = false; sb.Append("\"h").Append(k).Append("\":").Append(shield.Hits[i].ToString(ic)) .Append(",\"d").Append(k).Append("\":").Append(((long)Math.Round(shield.Total[i], MidpointRounding.AwayFromZero)).ToString(ic)) .Append(",\"m").Append(k).Append("\":").Append(((long)Math.Round(shield.Max[i], MidpointRounding.AwayFromZero)).ToString(ic)); } } if (r == null) return sb.Append('}').ToString(); if (!first) sb.Append(','); sb.Append("\"sw\":").Append(r.Swings.ToString(ic)).Append(",\"ev\":").Append(r.Evaded.ToString(ic)) .Append(",\"sp\":").Append(r.SpellsAtIt.ToString(ic)).Append(",\"rs\":").Append(r.Resisted.ToString(ic)) .Append(",\"ne\":").Append(r.NoEffect.ToString(ic)) .Append(",\"at\":").Append(r.Attacks.ToString(ic)).Append(",\"yev\":").Append(r.YouEvaded.ToString(ic)) .Append(",\"ysp\":").Append(r.SpellsAtYou.ToString(ic)).Append(",\"yrs\":").Append(r.YouResisted.ToString(ic)) .Append(",\"yne\":").Append(r.NoEffectOnYou.ToString(ic)) .Append(",\"k\":").Append(r.Kills.ToString(ic)) .Append(",\"dd\":").Append(r.DamageDealt.ToString(ic)).Append(",\"dt\":").Append(r.DamageTaken.ToString(ic)) // 2026-11-08: the XP of the kills whose rise was seen, and how many (XP/kill = xp / xk). .Append(",\"xp\":").Append(r.Xp.ToString(ic)).Append(",\"xk\":").Append(r.XpKills.ToString(ic)) // Same day: the kill-to-corpse time (the death animation), its average in ms and how many were timed. .Append(",\"cd\":").Append(((long)Math.Round(r.CorpseAvgMs ?? 0, MidpointRounding.AwayFromZero)).ToString(ic)) .Append(",\"cn\":").Append(r.CorpseKills.ToString(ic)) .Append('}'); return sb.ToString(); } /// /// A new view for the fallback window when something changed (at most 4 a second): while it is on /// screen, and off screen only for a login or logout, so it never opens on the wrong one. /// private void PublishMonsterStatsView(long nowMs) { bool shown = nowMs - Volatile.Read(ref _monsterStatsDrawnMs) <= 2000; if (!shown && _monsterStatsViewVersion != -1 && _monsterStatsViewInWorld == _loginComplete) return; if (nowMs - _monsterStatsViewAtMs < 250) return; string focus = MonsterStatsFocusName(); if (_monsterStats.Version == _monsterStatsViewVersion && focus == _monsterStatsViewFocus && _loginComplete == _monsterStatsViewInWorld) return; _monsterStatsViewAtMs = nowMs; _monsterStatsViewVersion = _monsterStats.Version; _monsterStatsViewFocus = focus; _monsterStatsViewInWorld = _loginComplete; _monsterStatsView = new MonsterStatsView(_monsterStats.Snapshot(), focus, _combatEventsStreaming, _loginComplete); } /// The monster in focus: the one combat fights, else the selected creature; "" for none. private string MonsterStatsFocusName() { int id = _combatManager?.activeTargetId ?? 0; if (id == 0) id = unchecked((int)_currentTargetId); if (id == 0) return string.Empty; if (CreatureData.PlayerWeenies.IsPlayerGuid(unchecked((uint)id))) return string.Empty; WorldObject? wo = _objectCache?[id]; return wo != null && wo.ObjectClass != AcObjectClass.Player ? wo.Name ?? string.Empty : string.Empty; } /// A real logout ends them (they are per character and login), and the save with them. private void OnLogoutMonsterStats() { if (_monsterStatsStarted) DeleteMonsterStatsSave(); _monsterStats.Reset(); _killXp.Reset(); // the next character's XP is a new starting point _corpseTimer.Reset(); EndDeathWait("logged out"); _monsterStatsStarted = false; _monsterStatsSavedVersion = -1; _creatureClassByName.Clear(); PublishMonsterStatsRows(); _monsterStatsView = MonsterStatsView.Empty; _monsterStatsViewVersion = -1; } /// Plugin unload (hot reload, update, client closing): saved while counting, never deleted. private void ShutdownMonsterStats() { if (_monsterStatsStarted) SaveMonsterStats(DateTime.UtcNow); try { _xpTable.SaveIfDirty(); } catch { } } // ── Saving (MonsterStatsStore) ─────────────────────────────────────── private void SaveMonsterStats(DateTime now) { if (_playerId == 0 || !_monsterStatsStarted) return; try { var save = new MonsterStatsSave { ProcessId = Environment.ProcessId, ProcessStartUtcTicks = MonsterStatsStore.ProcessStartTicks, CharacterId = _playerId, SavedUtcTicks = now.Ticks, SinceUtcTicks = _monsterStatsSinceUtc.Ticks, Rows = new List(_monsterStats.Snapshot()), }; MonsterStatsStore.Save(MonsterStatsDirectory, save); _monsterStatsSavedVersion = _monsterStats.Version; _monsterStatsSaveFailedLogged = false; } catch (Exception ex) { if (_monsterStatsSaveFailedLogged) return; // one line until a save works again _monsterStatsSaveFailedLogged = true; Host.Log($"[RynthAi] Couldn't save the monster stats: {ex.GetType().Name}: {ex.Message}"); } } private bool TryRestoreMonsterStats(DateTime now) { if (_playerId == 0) return false; try { int pid = Environment.ProcessId; if (!MonsterStatsStore.TryLoad(MonsterStatsDirectory, pid, _playerId, out MonsterStatsSave save)) return false; if (!MonsterStatsStore.ShouldRestore(save, pid, MonsterStatsStore.ProcessStartTicks, _playerId, now)) return false; _monsterStats.Load(save.Rows); _monsterStatsSinceUtc = new DateTime(save.SinceUtcTicks, DateTimeKind.Utc); _monsterStatsSavedVersion = _monsterStats.Version; return true; } catch (Exception ex) { Host.Log($"[RynthAi] Couldn't read the saved monster stats, starting fresh: {ex.GetType().Name}: {ex.Message}"); return false; } } private void DeleteMonsterStatsSave() { if (_playerId == 0) return; try { MonsterStatsStore.Delete(MonsterStatsDirectory, Environment.ProcessId, _playerId); } catch (Exception ex) { Host.Log($"[RynthAi] Couldn't delete the saved monster stats: {ex.GetType().Name}: {ex.Message}"); } } private void CleanupMonsterStatsSaves(DateTime now) { try { MonsterStatsStore.Cleanup(MonsterStatsDirectory, Environment.ProcessId, now); } catch { } } // ── /ra mstats ─────────────────────────────────────────────────────── /// /// "/ra mstats [monster]" prints a monster's numbers (no name: the monster combat fights, else /// the selected one); "list" the monsters with numbers; "reset" starts them over; "show", "hide", /// "toggle" the Damage panel (or, on an older engine, the Monster Stats window). Pump thread. /// private void HandleMonsterStatsCommand(string[] parts) { string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty; switch (arg.ToLowerInvariant()) { case "list": ListMonsterStats(); return; case "reset": case "clear": { int n = ResetMonsterStats("/ra mstats reset"); ReplyOk($"[RynthAi] Monster stats started over ({n} {(n == 1 ? "kind" : "kinds")} of monster cleared)."); return; } case "show": case "open": case "window": case "hide": case "close": case "toggle": SetMonsterStatsWindow(arg.ToLowerInvariant()); return; case "help": case "?": ChatLine("[RynthAi] /ra mstats [monster] — a monster's evades, resists, hits, spells and kills since login (no name: the one you fight or have selected)"); ChatLine("[RynthAi] /ra mstats list | reset | show | hide — every monster, start over, where they show (the Damage panel's Monsters tab)"); return; } MonsterStatsRow? row; if (arg.Length == 0) { string focus = MonsterStatsFocusName(); row = focus.Length > 0 ? _monsterStats.Get(focus) : null; if (row == null) { ReplyFail((focus.Length > 0 ? $"[RynthAi] No monster stats for {focus} since login yet." : "[RynthAi] Select a monster or name one.") + KnownMonsters() + " " + MonsterStatsUsage); return; } } else { row = _monsterStats.Find(arg, out List candidates); if (row == null) { ReplyFail(candidates.Count > 1 ? $"[RynthAi] '{arg}' matches {candidates.Count} monsters: {string.Join(", ", candidates)}. Name one exactly. {MonsterStatsUsage}" : $"[RynthAi] No monster stats for '{arg}' since login.{KnownMonsters()} {MonsterStatsUsage}"); return; } } foreach (string line in MonsterStatsText.ChatLines(row)) ChatLine(line); } /// " Monsters with stats: A, B, C." (the most recent few), or " No monster has stats yet." private string KnownMonsters() { MonsterStatsRow[] rows = _monsterStats.Snapshot(); if (rows.Length == 0) return " No monster has stats yet."; var names = new List(); for (int i = 0; i < rows.Length && i < 6; i++) names.Add(rows[i].Name); return " Monsters with stats: " + string.Join(", ", names) + (rows.Length > 6 ? ", ..." : "") + "."; } private void ListMonsterStats() { MonsterStatsRow[] rows = _monsterStats.Snapshot(); if (rows.Length == 0) { ChatLine("[RynthAi] No monster stats yet since login: fight something."); return; } ChatLine($"[RynthAi] Monster stats since login ({rows.Length} {(rows.Length == 1 ? "kind" : "kinds")}, most recent first):"); for (int i = 0; i < rows.Length && i < 10; i++) ChatLine(MonsterStatsText.ListLine(rows[i])); if (rows.Length > 10) ChatLine($"[RynthAi] ... and {rows.Length - 10} more (/ra mstats show)."); } /// "show" / "hide" / "toggle": the Damage panel where it shows them, else the fallback window. private void SetMonsterStatsWindow(string verb) { if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] Opening a panel needs RynthCore with plugin windows (plugin API 89+); /ra mstats prints the numbers."); return; } RynthPanelOpen mode = verb is "hide" or "close" ? RynthPanelOpen.Close : verb == "toggle" ? RynthPanelOpen.Toggle : RynthPanelOpen.Open; bool tab = EngineDrawsMonsterStats; string key = tab ? DamagePanelKey : MonsterStatsTitle; string what = tab ? "Damage panel (Monsters)" : "Monster Stats window"; int open = Host.SetPanelOpen(key, mode); if (open < 0) { ReplyFail(tab ? "[RynthAi] RynthCore has no Damage panel to open." : "[RynthAi] The Monster Stats window isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment."); return; } ReplyOk(open == 1 ? $"[RynthAi] {what} open{(tab ? ": each monster's evades and resists are under its line." : ".")}" : $"[RynthAi] {what} closed."); } /// The window's Reset (queued from the render thread, run on the tick). private void ResetMonsterStatsFromWindow() => ResetMonsterStats("the Monster Stats window"); /// The Session Stats view's "Monster stats" button (the fallback window only): open or closed. Any thread. internal void ToggleMonsterStatsWindow() { if (Host.HasSetPanelOpen) Host.SetPanelOpen(MonsterStatsTitle, RynthPanelOpen.Toggle); } // ── Fallback window (render thread) ────────────────────────────────── /// /// RynthPluginRenderEmbed "window:monsterstats": the Monster Stats window body, docked or popped /// out (the engine's current context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw). /// internal int RenderMonsterStats(bool popped, out Vector2 want) { want = default; if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0; Volatile.Write(ref _monsterStatsDrawnMs, Environment.TickCount64); IntPtr previous = ImGui.GetCurrentContext(); ImGui.SetCurrentContext(EmbedContext()); try { _monsterStatsWindow ??= new MonsterStatsWindow(() => QueueDashAction(ResetMonsterStatsFromWindow)); want = _monsterStatsWindow.Draw(_monsterStatsView); _monsterStatsFailures = 0; return 1; } catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "RenderMonsterStats"); return ++_monsterStatsFailures >= 3 ? -2 : 0; } finally { ImGui.SetCurrentContext(previous); } } /// /// The fallback window goes in the sections manifest on an engine with plugin windows (v89) whose /// Damage panel doesn't show the numbers (no GetUiHookFlags bit 8: the owner's API-90 core). /// private bool MonsterStatsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen && !EngineDrawsMonsterStats; }